I am trying to pass javascript variable to Controller action by calling "CreateURL" function,
JS Code:
Yii::app()->clientScript->registerScript('searchaevg', "
$('#newAddval_btn').click(function(){
var r = document.getElementById('cid').value;
window.location = '". yii::app()->createUrl('baseContact/add_refvalue',array("id" => ("#r"))). "'; });
");
Above code is not calling controller action, it throws
error "Error 400
Your request is invalid."
try this
window.location = '".
yii::app()->createUrl('baseContact/add_refvalue'). "/id/'+r
Related
Im using Postman platform for testing API. I'm actually new to Postman. So, Currently testing dummy APIs, where i fetched the GET response result from the URI
http://dummy.restapiexample.com/api/v1/employees , when i add validation points :
specifying test description as "name" See below
var response = JSON.parse(responseBody);
tests["name"] = response.data[2].employee_name == "Ashton Cox";
Test operation successfully passed. But when using specific id in the URI link
http://dummy.restapiexample.com/api/v1/employee/5
with same validations points as above, i'm getting response as TypeError: Cannot read property 'employee_name' of undefined, below is the screenshot
The correct reference and syntax would look like this:
pm.test("Check User", () => {
const responseJson = pm.response.json();
pm.expect(responseJson.data.employee_name).to.eql("Airi Satou");
});
I would like to display a custom view (using twig view) on production when there's something going wrong with my slim3 application.
I read the documentation concerning error handling but I cannot get the handler to display a twig view.
So this is working (displaying the error message in my browser):
if ('development' !== $container->get('settings')['environment']) {
$container['errorHandler'] = function($c) {
return function ($request, $response, $exception) use ($c) {
$c->get('logger')->critical("An error occured", [$exception->getMessage()]);
return $response->write('An error occurred (message: "' . $exception->getMessage(). '").');
};
};
}
but this is not working, ie. it's not displaying the view using the template (instead I get a blank page in my browser):
if ('development' !== $container->get('settings')['environment']) {
$container['errorHandler'] = function($c) {
return function ($request, $response, $exception) use ($c) {
$exceptionMessage = $exception->getMessage();
$settings = $c->get('settings');
$view = $c->get('view');
$data = [
'app' => $settings['app'],
'title' => 'Error',
'exceptionMessage' => $exceptionMessage
];
$c->get('logger')->critical("An error occured", [$exception->getMessage()]);
return $view->render($response, '500.twig', $data);
};
};
}
I really don't get why it's not working. Any ideas?
The error handler cannot catch all errors. PHP Fatal errors and syntax errors it will not catch because of the way PHP deals with Fatal/Parsing errors. Unfortunately there is no way to deal with those types of errors in PHP. An example could be a syntax error or out of memory error. Neither is recoverable
Just to add an observation,
to make twig render anything usually you echo $view->render ...
I am trying to figure out how to add, dynamically generated button in the code behind to the front page. The following code generating button in code behind like this:
Dim sortLinkButton As New LinkButton()
sortLinkButton.Text = "Click To Sort"
sortLinkButton.OnClientClick = New EventHandler(AddressOf sortLinkButton_Click); <- !!!
There is also an error in the last line.
Then I have a div or span or whatever that I can reference using Me.myDIV.innerHTML
I need this button to be click able and when the user clicks on it call code behind function/sub.
Can you show your HTML and indicate what you are trying to do? Below is what I'd do if I think I understand what you are trying to do.
You can set sortLinkButton.OnClientClick to point at a jQuery ajax function that will call a web method but it would be easier to handle in on client side click function eg
$('#LinkbuttonClientId').click(function(){ });
Include the following imports in your back end code
Imports System.Web.Script.Serialization
Imports System.Web.Services
Add a function to your backend code
<WebMethod()> _
Public Shared Function WebMethod(value As string) As String
Try
Dim ReturnString As New List(Of [String])()
'Add functionality - if success set first element of ReturnString = 1 else set to 0
ReturnString.Add("1")
'Add any other value to return
ReturnString.Add("another value")
Dim serializer As New JavaScriptSerializer()
Return serializer.Serialize(ReturnString)
Catch ex As Exception
'Create the same ReturnString variable to return information about an error
Dim ReturnString As New List(Of [String])()
ReturnString.Add("-1")
ReturnString.Add(ex.Message.ToString + ", " + ex.InnerException.ToString)
Dim serializer As New JavaScriptSerializer()
Return serializer.Serialize(ReturnString)
End Try
End Function
Add jQuery to your page (place in <head></head>)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
Add a function to called by button click to make ajax call to webmethod
<script type="text/javascript">
var WebMethodCall = function(value) {
$.ajax({
type: "POST",
url: "[page name].aspx/WebMethod",
data: "{'value' : '" + value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (obj) {
try {
var ret = $.parseJSON(obj.d);
if (ret[0] > -1) {
//run this code after successful return code
}
else {
console.log(ret[1])
}
}
catch (e) {
console.log(e.description || e);
}
},
error: function (ts, ajaxOptions, thrownError) {
console.log(ts.responseText)
}
});
};
</script>
Add a jQuery handler (also in frontend)
<script type="text/javascript">
$(document).ready(function() {
$("#LinkbuttonClientId").click(function(){
WebMethodCall(value);
//prevent click from submitting page
return false;
});
});
</script>
You could put both js parts in a separate file and include to tidy up. Also 'value' is not necessary but is there to show you how to pass variables into webmethod. It is possible to create the button dynamically in jQuery, if you do that then declare the handler function in the same section of code and use bind() or on() eg
$("#LinkbuttonClientId").on("click", function(){ });`
All this is probably overkill for you but it's how I make ajax calls to functions instead of using .net update panels and makes it easy to deal with events from dynamic elements without the need to submit the page.
Is it possible to get an alert popup on return to same view after success in mvc4 without using ajax begin form?
I'm trying to submit a form and on success want to show a alert box without using ajax and jquery .
When you submit form, I think then you are redirecting, am i right? So you can use TempData for this purpose:
In controller action:
if(success)
{
TempData["AlertMessage"] = "my alert message";
return RedirectToAction("SomeAction");
}
The view which SomeAction action returns (or in layout view):
#{
var message = TempData["AlertMessage"] ?? string.Empty;
}
<script type="text/javascript">
var message = '#message';
if(message)
alert(message);
</script>
NOTE: If you are not redirecting, but returning view, just use ViewBag instead of TempData.
I'm trying to use Dojo to post to my server. The server is returning a JSON response (I have debugged it and know its returning a sensible value) but I'm just getting a 'Syntax error' in the Javascript console when it returns. Any ideas?
function submitStatusUpdate() {
dojo.xhr.post({
form:"statusUpdateForm",
handleAs: "json",
load: function(data){
alert('Saved with id ' + data.id);
},
error: function(err, ioArgs){
// again, ioArgs is useful, but not in simple cases
alert('An error occurred');
console.error(err); // display the error
}
});
}
I've also tried it like this
function submitStatusUpdate() {
var posted = dojo.xhr.post({
form:"statusUpdateForm",
load: function(data){
},
error: function(err, ioArgs){
// again, ioArgs is useful, but not in simple cases
console.error(err); // display the error
}
});
posted.then(function(response){
alert('returned ' + response);
});
}
But the response that gets printed out in my alert just seems to be the HTML for my entire page. I'm expecting a JSON object. I'm struggling to find a simple example that tells me how to submit a form, and then have a callback function that reads the response.
Thanks
EDIT (thanks to Richard for the guidance)
This is the working version.
<script language="Javascript">
dojo.require("dijit.form.Button");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.CheckBox");
function sendForm(){
var form = dojo.byId("myform");
dojo.connect(form, "onsubmit", function(event){
// Stop the submit event since we want to control form submission.
dojo.stopEvent(event);
// The parameters to pass to xhrPost, the form, how to handle it, and the callbacks.
// Note that there isn't a url passed. xhrPost will extract the url to call from the form's
//'action' attribute. You could also leave off the action attribute and set the url of the xhrPost object
// either should work.
var xhrArgs = {
form: dojo.byId("myform"),
load: function(data){
// As long as the server is correctly returning JSON responses, the alert will
// print out 'Form posted. ' and then the properties and values of the JSON object returned
alert("Form posted." + data);
},
error: function(error){
// We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
// docs server.
alert("error");
}
}
// Call the asynchronous xhrPost
alert("Form being sent...");
var deferred = dojo.xhrPost(xhrArgs);
});
}
dojo.ready(sendForm);
</script>
This is (kind of) what my form looks like. This will work anyway (my real form is much bigger). Interestingly I had to change my normal [input type="submit"...] tag into a [button...] to get it to work properly
<form method="post" id="theform" action="postIt">
<input value="Some text" name="formInput" type="text"/>
<input name="checkboxInput" type="checkbox"/>
<button id="submitButton" type="submit">Send it!</button>
</form>
A JavaScript syntax error on parsing an XMLHttpRequest reply usually indicates invalid data from the server. My favourite tool for monitoring XMLHttpRequest traffic is Firebug. It parses JSON so if there's anything wrong, you'll know immediately.
Once you've determined that the JSON data from the server is valid, have a look at the following example from the Dojo documentation. I think it does what you're trying to do.