I have this JS:
$('.save').click(function(e){
var row = $(this).closest('tr');
var button = $(this);
var myParams = new Object();
myParams.id = row.find('.id').text();
myParams.data = row.find('.data').text();
myParams.descrizione = row.find('.descrizione').text();
myParams.movimento = row.find("select[name='tipo_mov']").val();
myParams.importo = row.find('.importo').text();
myParams.from = 'carta';
var params = JSON.stringify(myParams);
$.post( "edit_mov.php", params)
.done(function( data ) {
bootbox.alert("Movimento aggiornato correttamente");
button.toggle().prev('.edit').toggle();//ripristino il pulsante di edit;
row.removeClass('info').addClass('success').find('.tbe').attr('contenteditable', false).css('color','');
row.find('.tipo_mov').toggle();
setTimeout(function () {
row.removeClass('success');
}, 2000);
})
.fail(bootbox.alert("UPS! Something went wrong"));
});
This is done to update a table row with an AJAX request.
The PHP page responsible for update will return 200 or 500 depending if the query is successful or not:
if($count==0){
http_response_code(500);
}else{
http_response_code(200);
}
If I try with a query that will fail my JS will show only the alert in the .fail.
If I try with a query that will succeed then I will see both the alerts (.done and .fail).
I also tried to replace .done with .success buth with the same results. What am I doing wrong?
You should also use a function in .fail:
.fail(function() {
bootbox.alert("UPS! Something went wrong");
});
Otherwise the code inside the brackets is always executed.
as per docs.
https://api.jquery.com/jquery.post/
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
.fail should be supplied with a function
Related
I am sending data to a PHP script using an Ajax call, and I intend to use the Ajax return value in a Javascript function.
I have tried using return $.ajax({}) and it doesn't work. I also tried registering a callback function in my Ajax call, and that didn't work as well. Is there something am not doing right here?
function click_to_showResult() {
var score;
if (userName !="") {
var result = getResultData();
//display result for selected user
if (result == "Distinction") {
score ="A";
} else if (result =="Pass") {
score ="C";
} else {
score ="User has no result in DB";
}
}
alert(score);
}
function getResultData(callback) {
var data;
var userName = $.trim($("#user").val().toLowerCase()); //gets username input from the user
$.ajax({
type:"POST",
url : "getResult.php",
data: {'name':user},
success: function(resp) {
data = resp;
},
error: function(resp) {
alert('Error occured');
}
});
return data;
}
Let's say the user inputs Mike, then it should send the variable to PHP and get the results for Mike (for instance Pass), then alert C.
You should use the callback like this.
function click_to_showResult() {
var userName = $.trim($("#user").val().toLowerCase()); //gets username input from the user
if (userName != "") {
getResultData(userName, function (err, result) {
if (err) { console.log(err); return; }
var score;
//display result for selected user
switch (result) {
case "Distinction":
score = "A";
break;
case "Pass":
score = "C";
break;
default:
score = "User has no result in DB";
}
alert(score);
});
}
}
function getResultData(userName, callback) {
$.ajax({
type: "POST",
url: "getResult.php",
data: { 'name': userName },
success: function (resp) {
callback(null, resp);
},
error: function (resp) {
callback('Error occured');
}
});
}
If I understood correctly then you could perhaps rewrite the above code like this - the callback will process the response and alert the user. One issue I spotted after making the above comment was the data you send was user but this does not appear to be defined within the function - I suspect you intended userName?!
const click_to_showResult=function(e){
let userName=$.trim( $('#user').val().toLowerCase() );
if( userName!='' ){
/* callback function to process the response data */
const gradecallback=function( r ){
let score;
switch( r ){
case 'Distinction':score='A';break;
case 'Pass':score='C';break;
default:score='User has no result in DB';break;
}
alert( score );
};
$.ajax({
type: 'POST',
url : 'getResult.php',
data: { 'name':userName }, /* previously supplying user rather than userName */
success: function( resp ){
gradecallback.call( this, resp );
},
error: function(resp){
alert('Error occured');
}
});
}
}
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/*
do db lookup or whatever tasks the getResults.php
script actually does and send the response.
For the purposes of the demo send back some data
which might or might not reflect the actual data
from getResult.php...
Open the console to view output
*/
$name=$_POST['name'];
$score=mt_rand(0,100);
if( $score >= 75 )$grade='Distinction';
elseif( $score > 50 && $score < 75 )$grade='Merit';
elseif( $score > 40 && $score < 50 )$grade='Pass';
else $grade='Fail';
$payload = json_encode( array( 'name'=>$name, 'score'=>$score, 'grade'=>$grade ) );
/*
sleep is used ONLY to indicate that this backend process MIGHT take some time to perform ALL
the actions that are done by getResult.php
*/
sleep( 2 );
exit( $payload );
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
document.addEventListener('DOMContentLoaded',e=>{
let SCORE=false;
/* AJAX function bound with a promise to send POST requests only */
const ajax=function(url,params){
return new Promise( function( resolve, reject ){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 ){
/*
The request has completed and the response is available.
Resolve the Promise with the response data
*/
resolve( this.response )
}
};
xhr.onerror=function( error ){
reject( error )
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.send( params );
});
};
const alt__click_to_showResult=function(){
/*
asynchronous functions do not necessarily complete in the order
you would imagine like a standard synchronous function does
which is why returning a value from them is harder
*/
console.info('called before asynchronous request bound in a Promise');
let url=location.href;
let params='name='+document.getElementById('user').value;
ajax( url, params ).then(
res=>{
/* The Promise has been resolved */
console.info('The asynchronous request has now completed - trigger ajax callback');
return ajax_callback( res );
}
).then(
/* this is the value returned by the ajax_callback */
res=>{
console.info( 'The ajax callback returned this data: %o',res );
return true;
}
).then(
res=>{
alert( 'all done....'+res )
}
).catch(
/* For some reason the promise was rejected*/
e=>{ alert(e) }
)
console.info( 'After asynchronous request' );
};
/* do something with the data */
const ajax_callback=function(res){
SCORE=JSON.parse( res );
console.info( 'The user "%s" scored %s which is a grade "%s"', SCORE.name, SCORE.score, SCORE.grade )
/* modify the data to indicate that it has been intercepted and processed - only to show flow of data*/
SCORE.banana='yellow';
return SCORE
};
/* a slightly modified version of previously posted function */
const click_to_showResult=function(e){
let userName=$.trim( $('#user').val().toLowerCase() );
if( userName!='' ){
/* callback function to process the response data */
const gradecallback=function( r ){
let json=JSON.parse( r );// process JSON response rather than plain text as before
let score;
switch( json.grade ){
case 'Distinction':score='A';break;
case 'Merit':score='B';break;// added this...
case 'Pass':score='C';break;
default: score='User has no result in DB';break;
}
alert( 'User: '+json.name+' Scored: '+json.score+' Award: '+json.grade+' Grade:'+score );
};
$.ajax({
type: 'POST',
url : location.href, // "getResult.php"
data: { name:userName }, /* previously supplying user rather than userName */
success: function( resp ){
gradecallback.call( this, resp );
},
error: function(resp){
alert('Error occured');
}
});
}
}
document.querySelector( 'form > input[type="button"][name="std"]' ).addEventListener( 'click', click_to_showResult )
document.querySelector( 'form > input[type="button"][name="alt"]' ).addEventListener( 'click', alt__click_to_showResult )
});
</script>
</head>
<body>
<form method='post'>
<input type='text' name='user' id='user' value='geronimo' />
<input type='button' name='std' value='Click to show results' />
<input type='button' name='alt' value='Alternative - Click to show results' />
</form>
</body>
</html>
In my page, I call 15 ajax request. Also I have a button which cancels all the pending ajax requests. As per documentation, abort() terminates the request if it has already been sent.
Now when I check my console, even after I click cancel button, I get some replies from ajax script (I guess those were already sent by the time I clicked that button). So how can I make sure no reply should come once I press cancel button?
You can check the script here (couldn't use jsfiddle as not sure how to make ajax request).
JS Code
var xhrPool = [];
$(window).load(function(){
callAjax1();
});
$.ajaxSetup({
beforeSend: function(jqXHR) {
xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = xhrPool.indexOf(jqXHR);
if (index > -1) {
xhrPool.splice(index, 1);
}
}
});
var abortAjax = function () {
$.each(xhrPool, function(idx, jqXHR) {
if(jqXHR && jqXHR .readystate != 4){
jqXHR.abort();
}
});
console.log("All pending cancelled"); // Should not have any ajax return after this point
$.xhrPool = [];
};
$("#cancel-button").click(function (){
abortAjax();
});
function callAjax2(ajaxcallid){
console.log("Initiate ajax call " + ajaxcallid); // Should not have any ajax return after this point
$.ajax({
method: "POST",
url: "test.php"
})
.done(function( msg ) {
console.log(msg + ajaxcallid); // msg = "Ajax return for "
})
.fail(function( jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
}
function callAjax1(){
$.ajax({
method: "POST",
url: "test.php"
})
.done(function( msg ) {
for(var i = 0; i < 15; i++){
callAjax2(i);
}
})
.fail(function( jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
}
Console Output:
try this
$.each(xhrPool.slice(), function(idx, jqXHR) {
I think while you are aborting, some are returning, so the array gets messed up
this way you are working with a snapshot of the array
though, one or two may still sneak through due to timing of course
This is my code at www.domain-a.de/external.search.js. I call it from www.domain-b.de/test.php:
(function ($) {
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
var frm = $('#embedded_search form');
// click on submit button
frm.submit(function (ev) {
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
});
})(jQuery);
After running this code I don't get any message in console. What is wrong with that code?
frm.submit(function (ev) {
ev.preventDefault();
.....rest of code.
Your code is not calling the submit handler on the item, it is simply binding it. You should do the frm.submit(function binding outside of your $.getJSON callback; then inside the callback add
frm.submit()
Which triggers the event.
Also, when the submit happens, your actions will take place but then the form will submit to the back end as normal, causing a page reload.
After the line
frm.submit(function (ev) {
Add
ev.preventDefault();
So your overall code should be
(function ($) {
var frm = $('#embedded_search form');
var myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
frm.submit(function (ev) {
ev.preventDefault();
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
// click on submit button
frm.submit();
});
})(jQuery);
This question already has answers here:
What's the best way to retry an AJAX request on failure using jQuery?
(9 answers)
Closed 8 years ago.
I am having an ajax call that needs to run and if it fails then it should reinitialze the same ajax. As i have gone through some post there is failure function under where we can tell user that ajax call failed and follow some set of function.
But i wish to reintialiaze the same ajax call in failure or somewhere else so that when that ajax fails so in fails it intilized again.
deleteImage : function(objId,thumburl,original,ev){
jQuery('#imageBlocksDiv').append(jQuery("#confirmboxtmp").html());
setToCenterOfParent( $('#confirmbox'), document.body, false, true );
jQuery("#confirmbox").fadeIn().css({top:-210,position:'fixed'}).animate({top:50}, 100, function() {});
jQuery('#deleteconfirmbox').click(function(){
jQuery(this).text('Deleting..');
if(typeof objId!='undefined'){
var iputadatatologdelete = {
"media_image_objectId": objId,
"action" : "deleted"
};
iputadatatologdelete.company_objectId = jQuery('#cid').val();
iputadatatologdelete.edited_by_user_objectId = jQuery('#uid').val();
var inputData = {
'id' : objId,
'imgurl' : original,
'thumburl' : thumburl
}
jQuery.ajax({
'type':'POST',
'url': '#####/a###pi/###/####/#####',
'data' : inputData,
success : function(response){ //console.log(response)
jQuery('#'+objId).parents().eq(2).remove();
console.log(objId);
jQuery('#confirmbox').hide();
jQuery('#deleteconfirmbox').text('Delete');
pinterest(undefined);
logdata("sc_media_image_edited_log", iputadatatologdelete)
}
});
}
The function is something like this if i go to make function for every kind of ajax that i am calling then that will be bunch of codes. As i have already made loads of ajax with diffrent urls and type.
error : function(xhr, textStatus, errorThrown ) {
//try again
$.ajax(this);
return;
}
Will this work in case of reinitializing the same query.
You can do something like this:
function doAjax() {
$.ajax({
url: ...
success: ...
error: doAjax
});
}
doAjax();
Note, that in case of continuous failure, this will infinitely loop unless you implement a protection mechanism (e.g. a counter and a condition to stop the loop after a number of failed attampts).
To call exactly the same ajax, you can make it recursively, something like this:
function callAjax(){
$.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
callAjax();
})
.always(function() {
alert( "complete" );
});
}
Otherwise you can control it with a "control variable", like this:
function callAjax(){
var control = 0;
while (control === 0){
$.ajax( "example.php" )
.done(function() {
alert( "success" );
control = 1;
})
.fail(function() {
alert( "fail" );
})
.always(function() {
alert( "complete" );
});
}
}
I hope it helps you.
In error callback , call the the same ajax request method
Try below code:
$(document).ready(function(){
(function callAjax(){
$.ajax({
url: url,
success: function(res){ },
complete: callAjax
});
})();
})
You can use "complete" function for that because you either get success or error complete function will call in each case.. http://api.jquery.com/jquery.ajax/
As in the failure function we can reset the same ajax call by below lines .
error : function(xhr, textStatus, errorThrown ) {
jQuery.ajax(this);
return;
},
If i am some where wrong please give the feedbacks on the same
My problem is how JQuery knows when to receive data, when I watch the browser's console I see that GET call is first and then the POST call is second.
It should be POST first, then GET.
I tried solving my problem with .ready,and with some IF statements and so on but I still have not achieved what I wanted to achieve. Should I use some events?
My Javscript:
(function($) {
$(document).ready(function() {
$("form#userdata").submit(function(){
$.post( "savedata.php", $("form#userdata").serialize())
.done(function( data ) {
alert( "Send data" + data );
});
return false;
alert("Error by passing data to php");
});
})})(jQuery);
$.when($.ajax("savedata.php")).then(function(){
$.get("savedata.php", function(data){
alert("Php returns validation errors:+data);
});
});
My php script:
// Get POST data
$postData = $_POST;
// Print out for testing
// print_r($postData);
// Read data
$fistname = $_POST['firstname'];
$surname=$_POST['lastname'];
$email=$_POST['email'];
// VALIDATION
// Build return array and return JSON
$returnData = $postData;
//print(json_encode($returnData));
echo json_encode($returnData);
?>
$.get is called unconditionally, while the page is loading, because you didn't put it in an event handler.
$.post is only called when you submit the #userdata form, because it's called from the .submit() event handler.
You can try something like this:
PHP:
// Get POST data
$postData = $_POST;
// Print out for testing
// print_r($postData);
// Read data
$fistname = $_POST['firstname'];
$surname=$_POST['lastname'];
$email=$_POST['email'];
// VALIDATION
if(//validationError){
echo json_encode(array('error' => //Your error message here));
exit();
}
$returnData = $postData;
//print(json_encode($returnData));
echo json_encode(array('success' => $returnData));
?>
Then...
JS:
(function($) {
$(document).ready(function() {
$("form#userdata").submit(function(){
$.post("savedata.php", $("form#userdata").serialize())
.done(function( data ) {
if(data.error)
alert("Validation error: " + data.error);
else
alert( "Send data" + data.success );
})
.fail(function(){
alert("Error by passing data to php");
});
});
})})(jQuery);
You have your script incorrect
(function($) {
$(document).ready(function() {
$("form#userdata").submit(function(){
$.post( "savedata.php", $("form#userdata").serialize())
.done(function( data ) {
alert( "Send data" + data );
});
return false;
alert("Error by passing data to php");
});
})})(jQuery);
$.when($.ajax("savedata.php")).then(function(){
$.get("savedata.php", function(data){
alert("Php returns validation errors:"+data); // You did not close the string literal and it would throw an error
});
});