Ajax call always end up in error handler - php

I am trying to get a text value('selected crate') from the server using an ajax call. Ajax call is:
var selected_crate ='';
$.ajax({
url: OC.linkTo('crate_it', 'ajax/bagit_handler.php')+'?action=get_crate',
type: 'get',
dataType: 'text/html',
success: function(data){
selected_crate = data.responseText;
$('#crates option').filter(function(){
return $(this).attr("id") == selected_crate;
}).prop('selected', true);
},
error: function(data){
var e = data.responseText;
alert(e);
}
});
And the server side code snippet is:
case 'get_crate':
$msg = $bagit_manager->getSelectedCrate();
print $msg;
break;
I want to do something upon success but this call always end up in error handler. If there were complete handler, it would go in that handler. But I want to use both success and error handlers because I want to
Send error response if something is wrong from the server side
Do something on success in the client side
I am struggling to achieve this. Why this call always end up in error handler and how can I actually send an error response with regard to this call that would end up in error handler if any error occurs otherwise success response?

If the URL is right then try this:
dataType: "html"
See: http://api.jquery.com/jQuery.ajax/

see if in error handler data is been retrieved or not if data is been retrieved correctly it means your data-type is not matched for response in ajax call [see your server code that it must be returning some extra values in that case]

url: OC.linkTo('crate_it', 'ajax/bagit_handler.php')+'?action=get_crate',
in place of this try directly url like
url: www.yoursite.com/ajax/bagit_handler.php?action=get_crate
i think it will help you to get Sucess.

Related

Sending multiple variables in ajax

I have the following ajax request:
var value = $.ajax({
type: "POST",
url: "url.php",
data: { $(someform).serialize(), something: test_number },
cache: false,
async: true
}).success(function(data){
alert("success!");
}).error(function() {
console.log("FAILED");
});
But it is logging FAILED although the url is right. What happens is that the page refreshes the page and the php query isn't done. I guess there are no errors within the url... any idea on why this happens?
You are kind of mixing methods to send your POST data. You can't serialize a query strong and then also append additional data to it using javascript object construct. You will likely need to manually append the last data element to the query string like this:
data: $(someform).serialize() + '&something=' + encodeURIComponent(test_number),
Of course there could still be a problem on the server-side script which is causing a non-200 HTTP response code (and triggering error handler). You just need to fix this first, and if you still have a problem, debug the server-side issue.

How can make sure code after my ajax request only runs if the request was a success?

I have a link, delete, that removes an item from an array, and then removes a row from a table on my html page.
It runs the ajax request first to amend the array, then removes the row. If for some reason the ajax request was to fail then the html table row would still be deleted I think.
Is there a way to make sure subsequent code afer the ajax request only runs if it is successful? I tried moving it into the success function but then it didn't run at all..
This is how I have it set up at the moment...
$(document).ready(function () { //delete
$(document).on("click", "a[class='del']", function () {
var ID = $(this).attr("id"); //<----- get the ID of the column
$.ajax({
//contentType: "text",
url: 'proDel.php', //the url you are sending datas to which will again send the result
type: 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data: 'val1=' + ID, //Data you are sending
success: function (data) {
// do nothing, array was amended in php file
}
})
//Code here that deletes the table row(runs whether the array was changed or not!!
})
})
The problem might be that you are not returning valid JSON.
You were correct in thinking that you should move the code that deletes the table row into the success callback. You say you tried that, but the success callback was not executed.
Since you specify dataType: 'json', jQuery will attempt to parse the response body into a JavaScript object (or array or null). If the response body cannot be parsed (because it is not valid JSON), jQuery will call the error callback, rather than the success callback.
An empty response body is not valid JSON. You must at least return "null". Or if you do not plan on returning any data, just change to dataType: 'text'.
Move the code that deletes row to success callback.
$.ajax({
//contentType: "text",
url : 'proDel.php', //the url you are sending datas to which will again send the result
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// Code here that deletes the table row
}
});
Try you ajax with success parameter as well as an error to see if there is a problem, hope this helps..
$(document).ready(function (){
$(document).on("click", "a[class='del']", function(){
var elem = $(this); //to make $(this) accessible in you success callback
var ID= elem.attr("id"); // get ID of the column
$.ajax({
url : 'proDel.php', //the url you are sending datas to
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// success, Code here that deletes the table row , do something with 'elem'
},
error: function(x,e) {
//log error if any
console.log("failed with: "+x.status+", e="+e+", response="+x.responseText);
}
});
});
});
Since jQuery 1.5 you may use chainable methods of object returning by jQuery.ajax(). In your case (ensure executing code on ajax request completion) you have to use deferred.always() method. Somehow like this:
$.ajax({
...
})
.always({
//Code here that deletes the table row
})
In earlier jQuery versions you have to use complete option (handler) in jQuery.ajax() for your purpose.
First thing is that when looking at the ajax request success does not mean that the request returned a correct/true value. That just means that there was a response from the other end.
That tripped me up during my first couple times working with and debugging ajax calls.
I don't know if that's part of what is not working for you here, but something to consider.
Secondly, and to answer your real question, you'll have to put a function call in the success branch, else it might never get called, or be called at a non-deterministic time (the whole nature of an asynchronous call).
var a = function(){
$.ajax({
success : function (){
// code here fires if there is a response to your ajax request
// you should put in an function callback here to check the response for
// your success conditions.
// if your conditions are met, make the changes that you need to
b();
}
failure: function() {
// code here fires if the ajax request receives no response
}
})
// any code here will fire immediately after the ajax call is fired.
// it will not wait for the ajax response.
}
var b = function(){
// stuff you want to do according to the ajax response parameters
}

trouble with json response from php in jQuery.ajax call

I am using $.ajax to get a JSON response from a php script. if i log the data variable from the $.ajax success function it outputs a properly formatted JSON object, however when I try to access properties of the data var it's undefined. here is the php the is being sent back:
echo json_encode(array("status"=>true, "success"=>"Login Success", "message"=>"You have been logged in successfully."));
and here is my ajax call:
$.ajax({
type: "POST",
data: {
login: true,
username: $('#login-username').val(),
password: $('#login-password').val()
},
async: false,
url: "./php/client-login.php",
success: function (data) {
console.log(data.status);
if (data.status) {
console.log(data.success);
displayModal(data.success, data.message, "./js/login-modal-code.js");
} else if (!data.status) {
displayModal(data.error, data.message, "./js/login-modal-code.js");
}
},
error: function (jqXHR, status, responseText) {
console.log(status);
}
});
if i add the dataType: "json" option to the $.ajax call I get a parse error and if i try to do $.parseJSON(data); to access the data in the data var I get and unexpected token error. I'm not really sure what I'm doing wrong, I've used this setup before and it always has worked before but for some reason it isn't now. anyone see where i've gone wrong?
EDIT: forgot to mention here is the response from the php script:
{"status":true,"success":"Login Success","message":"You have been logged in successfully."}
EDIT 2: Here is a screen of my console. the top .length call is the json that was logged from console.log(data) and the bottom one is from the response in chrome dev tools network tab for the response from the php script. they line up perfectly yet the second is showing a length of 93, how can i fix this?
I was reading on jQuery Docs and found that "dataType: jsonp" does not work with sync request, and you're making this kind of request since you have async: false. Turning it on may solve your problem.
Also, give a look at the docs.
Good luck!
So I figured out a workaround for this problem, first I did JSON.stringify on the data followed by JSON.parse and lastly $.parseJSON() to get a javascript object to work with. Not sure why there are 2 invisible characters being added between when it leaves the php script and reaches the $.ajax call so if anyone knows why let me know

Ajax request multiple data info

I'm going crazy over this script, i'm trying to het this working by when some one click on a button then with ajax fetch data from another URL then fill form inputs with the fetched data can any one help please
my code look like this:
$(document).ready(function()
{
$("#getmetaData").click(function(){
var element = $(this);
var url = $("#url").val();
var dataString = 'url='+ url ;
//alert(dataString);
if(url=='http://')
{
alert("Please Enter URL to fetch Meta Data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loader.gif" >');
$.ajax({
type: "POST",
url: "fetch-metadata.php",
data: dataString,
cache: false,
success: function(data){
$("#title").val(data);
$("#description").val(data);
$("#keywords").val(data);
$("#flash").hide();
}
});
}
return false;});});
If you see no error, which I am guessing is the case, it means your request is failing. Since you have no error function, when your request fails, your jQuery code will do nothing.
Add something like this to your $.ajax object argument:
error: function(jqXHR, textStatus, errorThrown) {
// now you can set a breakpoint or log textstatus/errorThrown
},
As per HackedByChinese's answer I would add an error callback function.
Also, in your success callback function you are simply using the 'data' variable without doing anything with it. Depending on the format of the response from 'fetch-metadata.php' I think you'll need to do something first. It's either XML in which case you'll need to parse it. If its json you can use object dot notation to reference it's properties.
Lastly, I'd use something like Firebug to look at the request and response for this Ajax request to make sure it's being processed and not returning a 404 or 500. Assuming its returning a valid response, using Firebug you can look at the response to see the raw data that is being returned to your js.
Hope this helps

Can I return an output status from a JQuery AJAX request with PHP?

I have an AJAX request (using JQuery) that calls a PHP script which does some database business. The request code is as follows:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
alert(output);
}
});
However, I wanted to see if there was a way to also (in addition to the unchanged output string) return a status. It can be as simple as an integer. The point is I want to disable a button (with Javascript) if the PHP script for any reason fails to connect to mySQL, but I still want the PHP scripts output exactly as it would be.
I tried the error option:
...
success: function(output){
alert(output);
},
error: function(output){
// do something
}
but I do not know how to make PHP display an error and continue on the rest of the script. Again, I don't want to tamper at all with the output string.
In pseudo-code, I'm looking for something like this:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
if(output.status == 0){
alert(output);
}else{
// do something else
}
}
});
Is anything of the sort possible? Thanks for any and all help!
I usually return data from the server in JSON format. This way I can return as many different types of data as may be needed by the success function in javascript.
basically in PHP you would do something like
$response = new stdClass();
$response->error = 'Could not connect to Mysql';
$response->message = 'Some other text';
echo json_encode($response);
in JQuery, the ajax() method would automatically detect that the response is json and parse it into a javascript object, so you could access like this
if (typeof response.error !== undefined) alert(response.error);
for more on that look at dataType argument for the ajax() method in the jQuery documentation.
Yes. You can use HTTP status codes:
header('HTTP/1.1 500 Internal Server Error');
And use jQuery's statusCode property for jQuery.ajax():
$.ajax({
// stuff
statusCode: {
500: function(data) {
alert('Something went wrong!');
}
}
});
If your needs extend beyond what HTTP can offer, you can just return a status code within your data and process it in the success function, switching on data.status.
If I haven't misunderstood your question...
What I usually do is set the datatype of the AJAX call to 'xml' and output an xml from my PHP script. So I get multiple values in result. I usually make these attribute values.
<result status="success" something="etc" />
// vs.
<result status="failure" error="1" />
// consider 1 as the DB error
With this approach you might need to use the # tags in some PHP functions to prevent outputting the default errors.

Categories