So, I have an ajax call that prevents default post submission, server side I do some validation and checking, if the data is correct I do some database operations (inserting item for user etc) but if the data is not correct I don't have to make anything but throw out an error (i.e. item already present). My case in the controller was something like this:
} else {
print('Item already present');
}
but now I have the ajax call that manages the error like this:
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
So obviously the php doesn't print anything.
How should I modify my php to act well with the ajax call?
When you make an ajax call, you should be expecting a particular type of data back. A typical (example) scenario is to get back data in JSON. If you are using jQuery, then I typically to look for errors in a two places because I think of ajax errors coming in two types:
network error or anything that results in a website error (404 - page not found, 500 - potential coding error, etc). This is caught in the ajax 'error' handler function as you have it above. I believe you could intentionally trigger an error in your PHP code to get this case.
logical error. This is an error that you might be expecting to handle - such as a bad username/password during a login call via ajax. In this case, you don't really want to throw a PHP error. Instead you want to return an error, but perhaps also include some meta data bout the error such as 'username does not exist' or whatever.
So, on your php server, you would have a view that needs to set the header to be a JSON response, and then output the JSON error, e.g.:
<?php
// output a json version of any list of objects that has the
// "toArray()" method defined.
// ...for ajax calls.
header( 'Content-type: application/json' );
$isError = 'false';
if (checkToSeeIfErrorOccurred())
{
$isError = 'true',
$errorMessage = getErrorMessages();
}
?>
<!-- define json result -->
{
error: "<?php echo $isError; ?>",
errorMessage: "<?php echo $errorMessage; ?>"
}
So, on your client side, in (for instance) your jquery ajax call, you would define a successHandler that needs to check for this error, and specify the dataType of the return value. Note that even though it is a successHandler, the 'success' part just means you had no network or programmatic/PHP error thrown. So, you still need to check for the logical error you might return in your JSON:
// your error handler
function myErrorHandler( xhr, status, errorThrown )
{
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
};
function mySuccessHandler( response )
{
// response is returned as an object
if (response.error === 'true')
{
// maybe call same error handler?
myErrorHandler( 'whoCares', 'logicalFailure', response.errorMessage );
}
else
{
// handle success
}
};
$.ajax(
url,
dataType: 'json',
error: myErrorHandler,
success: mySuccessHandler,
...
);
I don't know if this is typical for other folks and it is only an example but it has worked well for me...
One way you could think about this is use ajax to do your request and then return xml with a result from php echo statement. If the result is successful then your code does what it needs to do else as part of the php server return you have an xml error tag with why it went wrong and then process this in your ajax.
Another way you could return a result is with json.
Related
I have an Ajax request that runs fine for the most part, it expects a json return and processes it accordingly. However if my PHP server throws an Notice (or warning or error for that matter), it triggers the ajax fail function automatically, EVEN if the response contains the Json array as part of it (usually after the PHP notice)
For development purposes, I don't want to turn of these PHP notices, I was wondering if the ajax could still handle the PHP notice and actually realize that the json return array was also included as part of the return, and somehow trigger the "done" function instead.
Not that it really matters but here a cut down version of the my ajax code, where having a PHP Notice being output by the server automatically triggers the "fail" callback, instead of "done" callback.
function getTimeSlots() {
$("#reservationtimebuttonsplaceholder").hide();
$.post( "<?php echo Router::url(array('controller'=>'Bookings','action'=>'getMerchantAvailableTimeSlots_ajax')); ?>", $( ".reservationform" ).serialize(), function() {
$(".reservationtimebuttons").empty();
}, "json")
.done(function(data) {
var respstatus = data.status;
var message = data.message;
var failtype = data.failtype;
var timeslots = data.timeslots;
if (respstatus === false) {
$(".reservationtimebuttons").html(message)
}
if (respstatus === true) {
$.each(timeslots, function (dataKey, dataVal) {
$.each(dataVal, function(timeKey,timeVal){
$.each(timeVal,function(timePropKey, timePropVal){
btn_id_postfix = timePropKey.replace(/\:/g,"");
$output = "<button id=\"btn" + btn_id_postfix + "\" class=\"btn btn-grey btn-timeselection\" value=\"" + timePropKey + "\" type=\"button\">" + timePropVal + "</button>";
$(".reservationtimebuttons").append($output);
});
});
});
}
})
.fail(function() {
alert( "There was a problem getting the available timeslots! Please try again later" );
})
.always(function() {
});
}
you can use simple ajax call , and not specify "json" as part of it , then this will get anything that comes from the php into the response of your ajax call.
and then try to JSON.parse it , if this function cannot parse the reponse to JSON , this means reponse is not properly formated and that means you php code has maybe some error or warning ,
then you can check if the response has something like status , so it is what you want with no error , and if not , php has shoot some errors beside your response .
I know this had been disputed a lot and the short answer would be that I can't simply pass a javascript variable to a php variable in the same file. So instead here would be what I want to try: My user inputs a code, I send it to a php file by POST. There I check if the code matches a code from my database and I post again a boolean from there. Then in my first file, I tell the user whether the code is correct or not. Can this be achieved this way? I am a webdev newbie and I am trying to learn.
To pass a value from the client side to the server you can either send it on the URL or as a post variable.
This can be accomplished easily with ajax.
I recommend using jquery. example:
$.get("http://example.com/?var1=value&var2=othervalue", function (data) {
// your response
});
jQuery:
$.get( url, { userinput: value }, function( response ) {
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
}
javascript:
function get( url ) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false );
xhr.send();
return xhr.responseText;
}
var response = JSON.parse( get( url ) );
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
php:
header( 'Content-type: text/json' );
if( get_matches( $_GET['userinput'] ) ) exit( '{ "status": true }' );
else exit( '{ "status": false }' );
You can post that code through AJAX to your server, have your server return a boolean, and then output a message to your user, this is quite common.
Common implementations of this logic include autosuggest, username validity verifications, simple turn on / turn off interfaces, etc.
Workflow:
User inputs code
Javascript sends AJAX request to server
Server verifies code and returns boolean
Javascript reads boolean, generates HTML and appends it to the document
User reads output
Edit: Even though i advice you to try doing it with pure javascript first (for educational reasons), you should use jQuery or other equivalent framework if you are on a schedule.
I've been searching for a simple, clean and flexible way to return errors to the browser after a POST or GET request.
Example AJAX request with jQuery:
$.ajax({
data : {
method : 'example',
input : 1
},
success : function(i){
if(i != 'succes'){
alert(i);
}
}
});
Server side response:
switch($_POST['method']){
case 'example':
if($_POST['input'] == 1) {
echo 'succes';
} else {
echo 'error';
// or
die('error');
}
break;
}
This just doesn't feel solid enough. Does anyone know a good way to capture an error combined with a message?
#Esailija is correct; return HTTP status codes so that jQuery's ajax error handler can receive the error.
if you want your AJAX call to be compliant with HTTP standards send the proper status codes defined in HTTP using the header function in PHP. In the future you can call the same PHP page from other apps without forcing specific error-handling.
If the error is application-specific, then return a json-encoded message as said before.
Use JSON:
$error = array(
'error' => 'SOME_ERROR_DESCRIPTION',
'message' => 'You have an error blabla'
);
echo json_encode($error);
From your JavaScript you can just use the JSON object to handle the error as you like.
I'm running the following php script through AJAX and need to integrate some error management into it:
$exists = file_exists('../temp/' . $email . '/index.html');
if($exists) {
echo "ERROR!!!";
} else {
createUserDirectory($email);
}
In the AJAX success function, how can I determine whether the script ran successfully or produced an error?
If it returns OK, I want to perform the redirect as it is at the moment, but if there's an error, I want to instead add the error to a DIV within the document (and not redirect of course...).
$.ajax({
type: "POST",
url: 'generate/build.php',
data: $("#generateStart").serialize(), // serializes the form's elements.
success: function(data)
{
window.location.href="generate-site.php?user=" + data.replace(/^ +/,"") + ""; // Redirect to publish.php and remove any spaces from the URL (bug fix).
}
});
Thanks.
Your PHP script should return a 4xx or 5xx HTTP status code to indicate failure. Then, the error method of jQuery's ajax object will be called.
Inside your success handler, check if(data == 'ERROR!!!').
You probably want to add two parts to this: an error callback on the $.ajax function to see if the request failed on the net and then a check on the return value to see if it failed server validation (if a file exists in this case).
Example:
$.ajax({
...
success : function(data) {
if(data && data != "ERROR!!!") {
//redirect
}
},
error: function(jqXHR, textStatus, errorThrown) {
//Log error, display feedback to user, etc...
}
);
I am attempting to create a simple comment reply to posts on a forum using the AJAX function in jQuery. The code is as follows:
$.ajax({type:"POST", url:"./pages/submit.php", data:"comment="+ textarea +"& thread="+ currentId, cache:false, timeout:10000,
success: function(msg) {
// Request has been successfully submitted
alert("Success " + msg);
},
error: function(msg) {
// An error occurred, do something about it
alert("Failed " + msg);
},
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert("Complete");
}
});
Inside the submit.php file I have this simple if->then:
if(System::$LoggedIn == true)
{
echo "Yes";
} else {
echo "No";
}
This call works on all other pages I use on the site, but I cannot access any of my variables via the AJAX function. I've tested everything more than once and I can echo back whatever, but anytime I try to access my other PHP variables or functions I just get this error:
Failed [object XMLHttpRequest]
Why am I unable to access my other functions/variables? I must submit the data sent into a database inside submit.php using my already made $mySQL variable, for example. Again these functions/variables can be accessed anywhere else except when I call it using this AJAX function. After hours of Googling I'm just spent. Can anyone shed some light on this for me? Many thanks.
The PHP script that you have only returns a single variable. Write another script that that returns JSON or if you are feeling brave XML. below is a quick example using JSON.
In your javascript
$.ajax({
type: 'GET'
,url: '../pages/my_vars.php'
,dataType: 'json'
,success: function(data){
// or console.log(data) if you have FireBug
alert(data.foo);
}
});
Then in the php script.
// make an array or stdClass
$array = array(
'foo' => 'I am a php variable'
,'bar' => '... So am I'
);
// Encodes the array into JSON
echo json_encode($array);
First thing, you have a space in the Data Parameter String for the URL - will cause problems.
Secondly, your success and error functions are referencing a variable msg. It seems you are expecting that variable to be a string. So, the question then becomes - What is the format of the output your PHP script at submit.php is producing?
A quick read of the jQuery API suggests that, if the format of the response is just text, the content should be accessible using the .responseText property of the response. This is also inline with the response you say you are getting which states "Failed [object XMLHttpRequest]" (as you are trying to turn an XHR into a String when using it in an alert.
Try this:
$.ajax( {
type: "POST" ,
url: "./pages/submit.php" ,
data: "comment="+ textarea +"&thread="+ currentId ,
cache: false ,
timeout: 10000 ,
success: function( msg ) {
// Request has been successfully submitted
alert( "Success " + msg.responseText );
} ,
error: function( msg ) {
// An error occurred, do something about it
alert( "Failed " + msg.responseText );
} ,
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert( "Complete" );
}
} );