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...
}
);
Related
I have one Ajax function which is running properly.but i want when my Ajax response is
<h3>No Couriers found near by you.please select another location</h3>
i want to display some error message else i want to display another map div in else condition.
but every time when i hit Ajax only else condition is working..but when i alert response and see the output it shows this message when
<h3>No Couriers found near by you.please select another location</h3>
but still it not comes in if condition..can anyone help me to do this....
<script>
$('#weight0,#weight1,#weight2,#weight3').click(function() {
var checked = $(this).is(':checked');
if($(this).is(":checked")) {
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Orders","action" => "searchCourier")); ?>',
data: {
frmlat: $("#PoolLatitude").val(),
frmlong: $("#PoolLongitude").val(),
mylocation: $("#PoolLocation").val()
},
dataType: "html",
success: function(response) {
alert(response);
if(response =="<h3>No Couriers found near by you.please select another location</h3>"){
alert(thanks);
} else {
$('#map_canvas').css('display', 'none');//used to hide map after ajax success response.
$("#load_map").html(response);
}
},
complete: function() {
$('.spinicon').hide();
}
});
} else {
$("#secretcode").val("");
}
});
</script>
In your php script, return a boolean flag instead of a string :
<?php
if (some_condition) {
$return = true;
} else {
$return = false;
}
die(json_encode(array('return' => $return)));
And in the ajax success :
...
dataType: 'json',
success: function(data) {
if (data.return) {
alert("return is true");
} else {
alert("return is false");
}
},
...
Hope it helps.
PS : use Json Encode to parse the response and access values easily.
First of all, i suggest you to use status for ajax response something like:
1 for success
0 for failure
Than, as per your statement, your are getting the correct response in:
alert(response);
Than, you must need to check either response having <h3></h3> tags or not.
In your code, the main issue is that, you are using string without quotes in alert alert(thanks); this will return undefined thanks in console and treated as a variable.
This should be alert("thanks");
One more suggestion, it's always better to check browser console when you are not getting success in Ajax or any other script, this will help you to find the errors.
I'm trying to test an ajax call on post by doing the following just for testing purposes, but for some reason the call is never successful. I've been searching around and there isn't much that I could find that would explain why this isn't working.
$.ajax({
type: "POST",
url: "file.php",
success: function(data) {
if(data == 'true'){
alert("success!");
}
},
error: function(data) {
alert("Error!");
}});
file.php contains the following:
<?php
return true;
?>
Can someone please point me in the right direction. I realize that this may seem simple but I am stumped. Thank.
return true will make the script exit. You need:
echo 'true';
Firstly check your paths. Is file.php residing in the same folder as the file that your javascript is contained in?
If your path is incorrect, you will get a 404 error printed to your javascript console if you are using chrome.
Also you should change your php to:
<?php
echo 'true';
Once your path is correct and your php is amended you should be good to go.
Have you tried by accessing to the file directly and see if it outputs something?
return true shouldn't be use in that case (or any other, it's better to use exit or die), everything get by a AJAX call is hypertext generated by server side, you should use (as they pointed you before echo 'true';)
You could also try a traditional AJAX call XMLHttpRequest (without JQuery) if problem persists, and then check if there is any problem between the request and server..
EDIT: also, do not check by comparison, just make an alert to 'data' to see what it gets.
In addition to the echo 'true' suggestion, you can also try to alert the actual data that's returned to ajax. That way you can see if you have the proper value/type for your if statement.
success: function(data) {
alert(data);
}
try this, the new ajax syntax
$.ajax({ type: "POST", url: "file.php" }).done(function(resp){
alert(resp);
});
Here is correct way:
$.ajax({
type : "POST",
url : "file.php",
success : function (data) {
/* first thing, check your response length. If you are matching string
if you are using echo 'true'; then it will return 6 length,
Because '' or "" also considering as response. Always use trim function
before using string match.
*/
alert(data.length);
// trim white space from response
if ($.trim(data) == 'true') {
// now it's working :)
alert("success!");
}
},
error : function (data) {
alert("Error!");
}
});
PHP Code:
<?php
echo 'true';
// Not return true, Because ajax return visible things.
// if you will try to echo true; then it will convert client side as '1'
// then you have to match data == 1
?>
So, I am using jquery to make an ajax call to a php script on my server.
For some reason I cannot figure out, however, there is no querystring sent. Using var_dump() on the $_GET object shows that it is an empty string, and Chrome's network activity developer tool indicates no string is sent.
$.ajax({
"url":"../script/content.php",
"settings": {
"dataType":"html",
"type":"GET",
"data":{
"id":$(this).prop('id')
}
}
}).done( function(msg) {
//$('#debug').html(msg);
$('#dialog').html(msg);
$('#dialog').load(function() {
$('#close').click(function() {
$('#over').fadeOut(fadeTime);
});
if ($('#unique') > 0) {
$('#unique').load(function(){
$('#over').fadeIn(fadeTime);
});
}
else {
$('#over').fadeIn(fadeTime);
}
});
});
I had tried the ajax call without the quotes where they weren't necessary before hand, and the result was the same... I just put those in because I thought it might be the problem... though I think that in such notation the quotes don't make a difference unless one of the field values is supposed to be a string.
Is there anything clear in that code which might cause a querystring not to be sent? I guess there is a problem with my syntax... I just can't see it.
The #dialog load callback seems to never be called, either... but I guess that is another question.
Try this
$.ajax({
//The link we are accessing with params
url:'http://example.com/script/content.php'
+ '?id='
+ $(this).prop('id'),
// The type of request.
type: "get",
//The type of data that is getting returned.
dataType: "html",
error: function(){
//something here
},
success: function( strData ){
//something here
}
});
I have a php script that takes some user form input and packs some files into a zip based on that input. The problem is that sometimes the server errors, so all the form data is lost. I was told I could use ajax instead so that the user never even has to change the page. I've never used ajax, and looking at http://api.jquery.com/jQuery.ajax/ without any experience in ajax is quite difficult.
The page says that you can accept returns from an ajax call. How do you set up returns in the PHP file for an ajax call? If the server errors with the ajax call, how will I know?
edit: Also, is there a way to send an ajax request with javascript and jquery as if it were a submitted form?
How do you set up returns in the PHP file
just echo it in ajax page that will return as response
Simple Tutorial
client.php
$.post('server.php',({parm:"1"}) function(data) {
$('.result').html(data);
});
server.php
<?php
echo $_POST['parm'];
?>
result will be 1
edit on OP comments
Is there a way to use ajax as if you were submitting a form
Yes, there is
You can use plugins like jQuery form
Using submit
If you using jquery validation plugin, you can use submit handler option
using sumit
$('#form').submit(function() {
//your ajax call
return false;
});
every ajax function has a function param to deal with server returns.and most of them has the param msg,that is the message from server.
server pages for example php pages you can just use echo something to return the infomation to the ajax funciton . below is an example
$.ajax({
url:yoururl,
type:post,
data:yourdata,
success:function(msg){
//here is the function dealing with infomation form server.
}
});
The easiest way to get information from PHP to JavaScript via AJAX is to encode any PHP data as JSON using json_encode().
Here's a brief example, assuming your server errors are catchable
<?php
try {
// process $_POST data
// zip files, etc
echo json_encode(array('status' => true));
} catch (Exception $e) {
$data = array(
'status' => false,
'message' => $e->getMessage()
);
echo json_encode($data);
}
Then, your jQuery code might look something like this
$('form').submit(function() {
var data = $(this).serialize();
$.ajax(this.action, {
data: data,
type: 'POST',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
if (!data.status) {
alert(data.message);
return;
}
// otherwise, everything worked ok
},
error: error(jqXHR, textStatus, errorThrown) {
// handle HTTP errors here
}
});
return false;
});
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" );
}
} );