I'm looking for a simple example and/or explanation of how to use the error parameter for .ajax.
This question (jQuery ajax error function) points to this jQuery documentation (http://api.jquery.com/jQuery.ajax/) which I do not understand.
I have the following code that does not work and I can't figure out why. I'm hoping the error parameter will help:
jquery:
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$("#myForm").submit(function(){
var user_input = $("#signup_id_email").val();
$.ajax
({
type: "POST",
url: "ajax_test.php",
dataType: 'json',
data: {email: user_input},
**error: ""**
})
.done(function(r)
{
$("#answer_id").append(r.email);
});
});
});
</script>
PHP (ajax_text.php)
<?php
echo json_encode($_POST);
?>
The error "property" of the $.ajax parameter object is used to supply a callback function known as a closure to the $.ajax method. In other words you need to provide an anonymous function to handle an error if one occurs during the ajax request. Here is a basic example.
$.ajax({
type: "POST",
url: "ajax_test.php",
dataType: 'application/json',
data: {email: user_input},
success: function(result) {
// You can use success instead of .done
},
error: function(requestObject, error, errorThrown) {
alert(error);
alert(errorThrown);
}
});
Keep in mind that the error callback function will only be invoked if the request actually errors out. If your code simply does not return anything but the request still returns a status of 200 you will have to handle that exception in the success callback function.
Hope this helps.
EDIT: note that I removed the use of chaining events and now all callback functions are handled inside the original parameters object passed into $.ajax.
I doubt you're even sending a request. Your whitespace is off.
Javascript does not require semicolons at the end of statements. Because of this, it sometimes infers them where you don't want them.
Try putting the '({' on the same line as the '$.ajax'. You didn't see the error because there isn't one. The $.ajax is a valid statement, even though it does nothing. Similarly, the object that you create inside of the parentheses is a valid object, even though it does nothing as well.
$.ajax({
type: "POST",
...
}).done(function(r) {
....
});
To answer your original question, error takes a function as a parameter. This function takes 3 parameters in this order:
the XHR (the request)
the status of the request
the error that was thrown (can be undefined)
An example looks like this:
$.ajax({
...
error: function(xhr, status, error) {
alert("oh no!");
}
})
Related
I have a working code using javascript event "onchange" :
<select id="mySelect" onchange="change_table(this)">
the jquery :
unction change_table(elem) {
var adressesInfo;
$.ajax({
type: "POST",
url: "test.php",
data: {id: elem.value},
success: function(data){
adressesInfo = jQuery.parseJSON(data);
},
async: false
});
and the php :
$data = array();
[...]
print json_encode($data);
This is working fine.
Now I want to do exactly the same, but using an onclick event on the th elements:
$(function(){
$("th").on('click', function(e){
change_table($('#mySelect')[0].value);
});
})
(This might not make much sense to do, but this is just for the sake of the example)
When I do this, i get the error Uncaught SyntaxError: Unexpected token <
I'm a bit confused on why it would work with onchange event and no onclick event, what is the difference ? i'm kinda new to jquery/ajax.
Thanks for your help.
Your change_table function expects an element that it can get value from (data: {id: elem.value}). So in the second case you should supply mySelect directly:
$("th").on('click', function(e){
change_table($('#mySelect')[0]);
});
$("th").click(function(){
change_table($('#mySelect')[0].value);
});
Please try this.
It looks like your error is jQuery trying to parse HTML output from your PHP, which probably means your back end is raising errors, probably due to posting it the wrong data.
Your original change_table function takes an element as its only argument, and in your final example you are passing it the string already evaluated. Perhaps this explains why the wrong data is going to your server.
Aside: there's no need to parse the json explicitly in jQuery. You can use dataType: 'json' in your ajax set up and the deserialized json will be passed to your success handler. If it fails your error handler will fire instead.
I copied this ajax call from another one that works and I can't figure out why it's not successfull. Here is the code:
$.ajax({
type: "POST",
url: "addTune.php",
data: {
database: setlist,
name: tune,
orderno: orderno,
midi: midi
},
error: function (e) {
alert("The PHP Call failed! hmmm");
alert(e.status);
},
success: function (response) {
alert(response);
}
});
I get the error function every time. Are there any blaring typos or other stupid mistakes?
Edit: trying to chase down the error with:
$.ajax({
type: "POST",
url: 'addTune.php',
data: {database : setlist, name : tune, orderno : orderno, midi : midi},
error: function(e){
alert("The PHP Call failed! hmmm");
alert(e.status);
$.ajaxSetup({
"error": function(jqXHR, status, thrownError) {
alert('error');
var responseText = jQuery.parseJSON(jqXHR.responseText);
console.log(responseText);
}
});
},
success: function(response){
alert(response);
}
});
});
Update: I was just able to add a row with the command line. any thoughts as to what I can do to try and narrow this down further?
i am no pro at this but maybe using single quote instead of double quotes? because i'm working on a project were i also have to do ajax calls and i use single quotes
i'm just suggesting something, not really good at this
If you get into the error callback then you have an error with the page you are calling and not with the js code. Check if the php page is reached. If it is check the php code if it returns a valid result.
From jquery DOCS.
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A
function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.
I'm trying to update a div with id=OCRID, which is a div on my page that contains some data. I used the code at the following URL first, however we switched to a jQuery approach. <-Ugly ajax->. Switched to this. Using alert, I saw that the message being returned on success was the correct message, but the document.getElementById(OCRID).innerHTML=msg doesn't change the value. I have some other javascript that does some similar things but not with data from the server. Please help?
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+document.getElementById(OCRID).value,
success: function(msg, OCRID){
document.getElementById(OCRID).innerHTML=msg;
}
});
First of all you mentioned OCRID is an id of div and you've used
document.getElementById(OCRID).value // a div doesn't have a value attribute
which returns value of an HTML element but a div doesn't contain any value attribute and in the success callback you have used
success: function(msg, OCRID){
document.getElementById(OCRID).innerHTML=msg; // innerHTML is right for a div
}
From the jQuery Documentation:
success(data, textStatus, jqXHR)
A function to be called if the
request succeeds. The function gets passed three arguments: The data
returned from the server, formatted according to the dataType
parameter; a string describing the status; and the jqXHR (in jQuery
1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in
turn. This is an Ajax Event.
in this case you shouldn't use OCRID as the second parameter because jQuery uses 3 parameters in the success callback and these are basically data, textStatus, jqXHR and in this case data is your msg, OCRID in this case become textStatus and it is the response's status message and the third parameter is the xhr object. So it should be
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+$('#'+OCRID).html(), // or text()
success: function(msg){
$('#'+OCRID).html(msg); // or text()
}
});
Also remember that you OCRID looks like a variable and this should be available in the scope of your ajax call and if this is not a variable then it should be $('#OCRID') in both places as given below
$('#OCRID').html();
and in the success callback
$('#OCRID').html(msg);
Replace this line:
document.getElementById(OCRID).innerHTML=msg;
With:
document.getElementById("OCRID").innerHTML=msg; // notice the quotes
If your success callback has OCRID as a parameter(which is incorrect) it will be used instead of the one you used in your data parameter, so remove it.
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+document.getElementById(OCRID).innerHTML,
success: function(msg){
document.getElementById(OCRID).innerHTML=msg;
}
});
Why not use the jQuery version for the interface to the element? To me it looks like OCRID is a variable, right?
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus=" + $('#' + OCRID).text(),
success: function(msg, OCRID){
$('#' + OCRID).html(msg);
}
});
I have the following ajax call. What I would like to do is set the variable "lan_setting" during the ajax requests, and be able to use that variable on success.
In reality I want to set that variable to be post data, which will vary depending on the form input, but as of now I can't even get it working with just this basic example. It just returns "undefined".
_jqXHR = $.ajax({
url: url,
data: {lan_setting: 'en'},
scriptCharset: "UTF-8",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(lan_setting, data, textStatus, jqXHR) {
alert(data.lan_setting);
}
});
How do I can I use post variable sent via ajax on success?
thanks!
Well, if you're posting, you should use the jquery post function here
$.post(
url,
{lan_setting:"en"},
function( data, status, jqXhr ){
alert(data.lan_setting);
},
"json"
);
then php:
<?php
// do stuff
$response = new stdClass;
$response->lan_setting = $_POST["lan_setting"];
print json_encode($response);
?>
Well, you're declaring the success function wrong (from the jQuery .ajax() documentation):
success(data, textStatus, jqXHR)
In other words, the success function gets data, textStatus, jqXHR and nothing else. You can't just will it to take your POST variable -- it only gets what it gets. You also can't pass a POST variable in by just specifying it in the config object: you have to pass it in via the data property. Lastly, .ajax() defaults to a GET request, so you have to explicitly specify that you want to use a POST request.
I'm a little confused about what you want to do; if you know the value of lan_setting before making the AJAX call, why do you need to have it passed into the success function? Just use it:
var lan_setting = 'en';
_jqXHR = $.ajax({
url: url,
type: "POST",
data: {
lan_setting: lan_setting
},
scriptCharset: "UTF-8",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(lan_setting, data, textStatus, jqXHR) {
alert(lan_setting);
}
});
If, on the other hand, you want to pass the lan_setting value in, have it modified by the server, and passed back, you will have to somehow encode it in the response, probably with JSON.
Well the success() method in jQuery.ajax, accepts 3 parameters.. The first being the response from the request.
success(data, textStatus, jqXHR)Function, Array A function to be
called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
Also, when using $.ajax, there are a certain number of objects you can pass. See http://api.jquery.com/jQuery.ajax/
As far as your post, you are able to do...
$.post("service.php", {lan_setting: "en"}, function(response) { alert(response); }
which will post the second parameter, {lan_setting: "en"} to that php service, and echo it's response.
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