jQuery AJAX function on success not working - javascript

Having an issue. I have two different buttons included with each image displayed. One is remove, the other is assign as "main".
Remove works. It hides the image, deletes the file, and the MySQL row.
Assign Main sort of works. It updates the row in the database changing "main" value to 1, as it should, however, it should also alert(), but it does not.
<script>
$(document).ready(function() {
$(".remove_image").click(function() {
var image_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { image_id:image_id,
image_remove:1},
success: function(response) {
$('#image_'+image_id).fadeOut(400);
showUploader();
}
})
})
});
$(document).ready(function() {
$(".assign_main").click(function() {
var assign_this_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { assign_this_id:assign_this_id,
image_assign:1},
success: function(response) {
alert("Success");
}
})
})
});
</script>

The success method is only called when a HTTP 200 or HTTP 304 is returned, therefore you may need to double check to see if this is actually the case.
This can be done in the ‘Inspector’ panel in most modern web browsers, usually under the ‘Network’ tab.
You can also add a error: function() {} event handler to catch any HTTP 4xx / 5xx codes.

Try and alert the error which for sure is there:
$(document).ready(function() {
$(".assign_main").click(function() {
var assign_this_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { assign_this_id:assign_this_id,
image_assign:1},
success: function(response) {
alert("Success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
})
})
});
This will show you if there is something wrong in your PHP code

Use done() instead of it :
$.ajax({
type: "post",
url: "imagecontrol.php",
data: {
image_id: image_id,
image_remove: 1
}
}).done(function(response) {
$('#image_' + image_id).fadeOut(400);
showUploader();
);

Related

how to detect a server error into a jquery ajax call?

I use Jquery to parse an json from url: the code is like this:
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
});
}
everything works fine, but if the server is not reachable I'm not able to detect it: I tried to do something in error: function, but seems that the code in error is fired only if the json has an error
have you got some ideas?
thank you!
You need to test the statusText from the jQuery textStatus response object. You can take advantage of your browser's developer console to inspect this object. You can expand the properties and methods for your perusal, however you wanna use it. Just click on the returned message of the console.log() to see these properties and methods that you wan't to use for error detection.
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(textStatus) {
console.log(textStatus);
console.log(textStatus.statusText, textStatus.status);
}
});
}
fetchdata();

Calling an AJAX function to a PHP function script in a REST (Paypal) section, works in jQuery not in REST

I'm in a bit of braiunfreeze here, puzzling for hours.
In a Paypal REST success section, i am trying to call a function. Before I moved it to the REST section I tested with a regular button onclick event. Worked fine.
Here the code:
...
onAuthorize: function(data, actions) {
return actions.payment.execute()
.then(function() {
// window.alert('Payment Complete!');
$.ajax({
type: "POST",
url: 'functions.php',
//dataType: "json",
data: {cuf_credits: '<?php echo $cuf_credits; ?>'},
success: function(data){
console.log(data);
$("#output").text("Thanks for buying " + data.cuf_credits + " credits");
}
});
// Show a thank-you note
document.querySelector('#paypal-button-container').style.display = 'none';
document.querySelector('#thanks').style.display = 'block';
document.querySelector('#orderdetails').style.display = 'none';
});
}
...
The query selectors are filled in fine, so is some basic text in the jQuery success section They return "undefined" though, but that is fine, I'm just trying to SEND, not GET back data.
The functions inside the functions.php are not executed, but when I use it in this code, it is:
var testme = document.getElementById('test');
testme.onclick = function () {
console.log('Test Started');
$.ajax({
type: "POST",
url: 'functions.php',
data: {cuf_credits: '<?php echo $cuf_credits; ?>'},
success: function(data){
console.log(data);
}
});
function error(err) {
console.log('Not Closed!');
}
};
If anybody could point me back in the right direction, that'd be awesome!
Let's try some debugging...
Modify your AJAX block like so:
...
onAuthorize: function(data, actions) {
return actions.payment.execute()
.then(function() {
// window.alert('Payment Complete!');
//check to make sure your code is getting this far
////////start debug
console.log("Calling AJAX...");
////////end debug
$.ajax({
type: "POST",
url: 'functions.php',
//dataType: "json",
data: {cuf_credits: '<?php echo $cuf_credits; ?>'},
success: function(data){
console.log(data);
$("#output").text("Thanks for buying " + data.cuf_credits + " credits");
}
//add a 'complete' function to get the status of the call
////////start debug
complete: function(obj, textStatus){
console.log("AJAX Status: " + textStatus);
}
////////end debug
});
// Show a thank-you note
document.querySelector('#paypal-button-container').style.display = 'none';
document.querySelector('#thanks').style.display = 'block';
document.querySelector('#orderdetails').style.display = 'none';
});
}
...
Let me know what your console log looks like after trying this...
I tried hardcoding the variables and noticed they work fine then. Sorry for the mishap, seems to work okay after a couple hours of not looking at it and taking another approach. Again, I apologize.

Calling Ajax request function in href

I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});

.done() jquery not working

Im using the below code for a ajax call
var getRequest = $.ajax({
type: 'GET',
url: Url,
async: false,
dataType: "text",
complete: function () {
$('#loading').hide();
}
});
the request is getting complete and data is also withdrawn after the data is recieved the following:
getRequest.done(function (dataDb) {
if (dataDb) {
alert('dataDb: ' + dataDb);
}
});
getRequest.fail(function (jqXHR, textStatus, error) {
alert('data error within getUsersRequest ' + textStatus + ' : ' + error);
});
I'm recieving a error that getRequest.done(function(dataDb) or getRequest.fail(function(jqXHR, textStatus, error) is not a function.
It is because your JQuery version is too old.
You can use success if you are not willing to upgrade the latest version of JQuery.
success: function(dataDb) {
}
success only fires if the AJAX call is successful from back end, i.e. it returns a HTTP 200 status as response. if any error fires if it fails and complete when the request finishes, regardless of success.
In jQuery 1.8 on the jqXHR object (returned by $.ajax) success is being replaced with the done, error with fail and complete with always.
However you should still be able to initialise the AJAX request with the current syntax. So these do similar things:
// set success action before making the request
$.ajax({
url: '...',
success: function(){
alert('AJAX successful');
}
});
// set success action just after starting the request
var jqxhr = $.ajax( "..." )
.done(function() { alert("success"); });
Last: you need to use .success rather then using .done
You can try using .success.
var getRequest = $.ajax({
type : 'GET',
url : Url,
async: false,
dataType: "text",
complete: function(){
$('#loading').hide();
}
}).success(function(dataDb){
if(dataDb) {
alert('dataDb: '+ dataDb);
}
});

How to callback a function on 404 in JSON ajax request with jQuery?

I want to make an Ajax request with response in JSON. So I made this Ajax request:
$.ajax({
url: 'http://my_url',
dataType: "json",
success: function(data){
alert('success');
},
error: function(data){
alert('error');
},
complete: function(data) {
alert('complete')
}})
This code works good but when my url send me a HTTP code 404, no callbacks are used, even the complete callback.
After research, it's because my dataType is 'json' so 404 return is HTML and the JSON parsing failed. So no callback.
Have you a solution to call a callback function when a 404 is raised ?
EDIT: complete callback don't call is return is 404. If you want an URL wit 404 you can call : http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697 it's with this URL I have my problem.
$.ajax({
url: 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697',
dataType: "json",
success: function(data) {
alert('success');
},
error: function(data) {
alert('error');
},
complete: function(xhr, data) {
if (xhr.status != 0)
alert('success');
else
alert('fail');
}
})
With your configuration jQuery uses jsonp to transport the data. This works by dynamically inserting a script element and setting the URL to the specified value. The data returned by the server is then evaluated as JavaScript - usually calling the provided callback. If the server returns a 404, the contents is obviously no JavaScript and the callback is never called. Some browsers support error handlers on the script tag, which are called in these situations. Unfortunately IE doens't support this. The best way to detect an error is to rely on a timeout.
In your case you should specify an additional timeout option, which causes the error handler to be called if the callback wasn't called in time (which would be the case for a 404 response).
$.ajax({
url: 'http://my_url',
timeout: 2000, // 2 seconds timeout
dataType: "json",
success: function(data){
alert('success');
},
error: function(data){
alert('error');
},
complete: function(data) {
alert('complete')
}
});
Use the statusCode-Option
$.ajax({
url: 'http://my_url',
dataType: "json",
statusCode: {
404: function() {
alert("I could not find the information you requested.");
}
},
success: function(data) {
alert('success');
},
error: function(data) {
alert('error');
},
complete: function(data) {
alert('complete');
}
})
If you want to handle errors when accessing the Twitter API with Javascript and jsonp you need to include the parameter suppress_response_codes in your request. This makes all responses from the Twitter API respond with a 200 OK response and include a error. Then you need to check if the response includes the error parameter or not.
$.ajax({
url: "https://api.twitter.com/1/users/show.json",
dataType: 'jsonp',
jsonp: "callback",
data: {
screen_name: "simongate1337",
suppress_response_codes: true // <- Important part
},
success: function(data) {
if(data.error) {
console.log("ERROR: "+data.error);
} else {
console.log("Success, got user " + data.screen_name);
}
}
});
Do not you think that the problem is not with the dataType but with cross-domain requests that you are not allowed to make?
The code below works as expected when you request data from the same domain and does not when you are making cross-domain requests:
function handle404(xhr){
alert('404 not found');
}
function handleError(xhr, status, exc) {
// 0 for cross-domain requests in FF and security exception in IE
alert(xhr.status);
switch (xhr.status) {
case 404:
handle404(xhr);
break;
}
}
function dumbRequest() {
var url = 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697';
url = 'http://twitter.com/';
url = '/mydata.json';
// url = 'mydata.json';
$.ajax(
{url: url,
dataType: 'json',
error: handleError}
);
}
Is it simply because the dataType is set to "json"? If so, try changing it to text and evaluate the JSON yourself:
$.ajax({
url: 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697',
dataType: 'text',
success: function(data, status, xmlHttp) {
try {
data = eval('(' + data + ')');
alert('success');
} catch (e) {
alert('json parse error');
}
},
error: function(xmlHttp, status, error) {
alert('error');
},
complete: function(xmlHttp, status) {
alert('complete');
}
});
Are you aware that even though the HTTP status is 404, the actual body is valid JSON? For instance, this link has the following JSON:
jsonp1269278524295({"request":"/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697","error":"Not found"})
As such, you should check if your data has the error property within your normal callback function.
UPDATE: apparently, even though the actual content of the page is valid JSON, the browser (I checked in Firefox) is not executing it, most likely because it is a 404. Because jQuery has to add a script element (because of the cross-domain issue), its JSONP wrapper is never called, and as a consequence, neither are your callbacks.
So, in short, I don't think there is a way to deal with this without manually adding that script element and checking if your pre-defined callback function has been called afterwards.
Just faced the same issue, and saw another question mentioned that jQuery-JSONP (jQuery Plugin) supports catching 404 errors or as they describe: "error recovery in case of network failure or ill-formed JSON responses"
And it works perfect :)
Here is my (simplified) code for fetching details about a YouTube video via JSONP:
$.jsonp(
{
url: "https://gdata.youtube.com/feeds/api/videos/ee925OTFBCA",
callbackParameter: "callback",
data:
{
alt: "jsonc-in-script",
v: "2"
},
success: function(json, textStatus)
{
console.log("WEEEEEEEE!");
},
error: function(xOptions, textStatus)
{
console.error(arguments);
}
});
Here's how I deal with this. I check the returned data for errors before trying to use it. What is shown below is just a sample that you could extend to more closely match your requirements. This also considers session time outs and other scenarios...
My initial call:
$.ajax({ type: 'POST',
url: '../doSomething',
data: 'my data',
success: function(data) {
if (HasErrors(data)) return;
var info = eval('(' + data + ')');
// do what you want with the info object
},
error: function(xmlHttpRequest) {
ReportFailure(xmlHttpRequest);
}
});
And the two helper functions:
function HasErrors(data) {
if (data.search(/login\.aspx/i) != -1) {
// timed out and being redirected to login page!
top.location.href = '../login.aspx';
return true;
}
if (data.search(/Internal Server Error/) != -1) {
ShowStatusFailed('Server Error.');
return true;
}
if (data.search(/Error.aspx/) != -1) {
// being redirected to site error reporting page...
ShowStatusFailed('Server Error. Please try again.');
return true;
}
return false;
}
and
function ReportFailure(msg) {
var text;
if (typeof msg == 'string') {
text = msg;
}
else if (typeof msg.statusText == 'string') {
if (msg.status == 200) {
text = msg.responseText;
}
else {
text = '(' + msg.status + ') ' + msg.statusText + ': ';
// use the Title from the error response if possible
var matches = msg.responseText.match(/\<title\>(.*?)\<\/title\>/i);
if (matches != null)
{ text = text + matches[1]; }
else
{ text = text + msg.responseText; }
}
}
// do something in your page to show the "text" error message
$('#statusDisplay')
.html('<span class="ui-icon ui-icon-alert"></span>' + text)
.addClass('StatusError');
}
Following solution is working fine for me :)
$.ajax({
url: 'http://my_url',
dataType: "json",
success: function(data){
alert('success');
},
error: function(data){
alert('error');
},complete: function(xhr, data) {
if(data==="parsererror"){
alert('404');
}
}
});

Categories

Resources