I have this code which works.
$.ajax({
type: "GET",
url: "includes/process.php",
data: "captcha=" + captcha,
success: function(data) {
if(data == 'true')
alert("OK");
else
alert("not ok");
}
});
However I have some more code after that like:
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
...
...
...etc
However, I need to stop the script when success:function(data) is false.
So, I thought that return false; should stop the execution
success: function(data) {
if(data == 'true') {
alert("OK");
} else {
alert("not ok");
return false;
}
}
, however it is not working and the code after $.ajax is executed anyway.
How to stop the script when the success is false?
Any advice? Thanks in advance.
ADDITIONAL INFO:
I have another ajax call which I want to execute when success is true:
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
alert ('mail was sent OK');
}
});
How to execute this code only after success of the first ajax call?
Your extra code should be in the callback itself.
$.ajax({
type: "GET",
url: "includes/process.php",
data: "captcha=" + captcha,
success: function(data) {
if (data == 'true') {
alert("OK");
// more code
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
// ... second ajax call
} else {
alert("not ok");
}
}
});
You could also add async:false to your AJAX call. This way, the code after won't execute until the request has ended. return false won't do anything either, but you could set a flag in the success function.
var isOk = false;
$.ajax({
type: "GET",
async: false, // prevent the asynchronous call
url: "includes/process.php",
data: "captcha=" + captcha,
success: function(data) {
if (data.length) {
alert("OK");
isOk = true;
}
}
});
if (isOk) {
// do your stuff
}
You can
1) add your additional code to the callback success function
$.ajax({
type: "GET",
url: "includes/process.php",
data: "captcha=" + captcha,
success:function(data){
if(data=='true') {
alert("OK");
//continue here
var datastring = ...
}
else
alert("not ok");
}
});
2) change the ajax call to not be asynchronous by adding this option to the .ajax call
var isSuccess = false;
$.ajax({
type: "GET",
url: "includes/process.php",
data: "captcha=" + captcha,
success:function(data){
isSuccess = (data=='true');
},
async: false
});
Then you can set a var in your success function to tell the rest of your code whether to continue or not.
Since $.ajax() is asynchronous, code after that will execute anyway. You can put the code in success handler. That way, it'll run only if its successful.
AJAX is an asynchronous call (hence the first 'A'). This means that jQuery makes your request and then goes on about its business while waiting for the call to complete.
The code after $.ajax is usually executed before the success function, because the $.ajax call is asynchronous. If you keep it asyncronous, you cannot stop the execution of the other code. You can set in the success function value of a variable in the outer scope and use syncronous code. But maybe it's better to move it in a function, called by the success callback? Anyway, to get better answer, please post more code.
Try this:
$.ajax({
type: "GET",
url: "includes/process.php",
data: "captcha=" + captcha,
success: function(data) {
if (data.length) {
alert("OK");
doMoreStuff(data);
}
}
});
function doMoreStuff(data){
// Code here will only be executed if ajax call is successful.
}
Related
I'm not sure this is the best way to send 2 ajax togheter for facebook api.
But it works, the problem is that sometimes i get the second ajax (result_flow.php) before the first (result.php)
Will be helpful delay second ajax (url:result_flow.php) for 3 seconds or change this code in someway to give a order.
I tried setTimeout but didn't work.
$('#sub').click(function () {
var data = $("input#dataInput").val();
console.log(data);
var total = $("input#totalInput").val();
var subscriber_id = $("input#subscriber_id").val();
var res_name = $("input#res_name").val();
var dataString = 'data='+ data + '&total=' + total + '&subscriber_id=' + subscriber_id+ '&res_name=' + res_name;
console.log(dataString);
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
success: function(data) {
console.log(data);
if(data==='success'){
//localStorage.clear();
MessengerExtensions.requestCloseBrowser(function success() {
console.log("Webview closing");
}, function error(err) {
console.log(err);
});
}
}
});
$.ajax({
type: "POST",
url: "result_flow.php",
data: dataString,
success: function(data) {
setTimeout(function(){
console.log(data);
if(data==='success'){
}
},3000);
}
});
}
I would suggest to use async/await nowadays, it is quite easy to use AJAX calls sequencially:
$('#sub').click(async () => {
...
try {
let data = await $.post({
url: "result.php",
data: dataString
});
if (data === 'success') {
...
}
data = await $.post({
url: "result_flow.php",
data: dataString
});
if (data === 'success') {
...
}
} catch (err) {
console.log(err);
}
});
Not tested, as i donĀ“t work with jQuery - but it should give you the idea. Since $.ajax/$.post supports Promises, it should work with async/await. Be aware that you may need to transpile your code with Babel for older browsers, but i suggest using Babel anyway.
If you want to use both AJAX calls in parallel, use Promise.all (because they do not depend on each other) - the results will be in order, so you can make sure the callback code is called in order.
First, setTimeout() is not working because you put it inside the callback, which means it will be executed when the request is already done. Anyway that's not a proper way to handle such a task, you should put the second request inside the first's callback, so that it will be executed as the first one finishes.
The code looks like this:
$('#sub').click(function() {
var data = $("input#dataInput").val();
console.log(data);
var total = $("input#totalInput").val();
var subscriber_id = $("input#subscriber_id").val();
var res_name = $("input#res_name").val();
var dataString = 'data=' + data + '&total=' + total + '&subscriber_id=' + subscriber_id + '&res_name=' + res_name;
console.log(dataString);
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
success: function(data) {
console.log(data);
if (data === 'success') {
//localStorage.clear();
MessengerExtensions.requestCloseBrowser(function success() {
console.log("Webview closing");
}, function error(err) {
console.log(err);
});
$.ajax({
type: "POST",
url: "result_flow.php",
data: dataString,
success: function(data) {
console.log(data);
}
});
}
}
});
}
Note that in my code the second request is sent just if the first one is successful because it's placed within the if (data === 'success') {...} statement.
You should call them in chain. Success... then... using promise is the best way.
Never trust the order you receive if is not explicitly written by you.
JQuery Ajax
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
You can do something like this:
// First Ajax call
$.ajax({
// Do the request
// Remove success to use new promise
})
.done(function( data ) {
// Add the success here
// Add the Second Ajax call here or create a function to call it, whatever you want
});
I am getting data from ajax call. But that data is coming in Jquery and I have saved it in a variable. Now I want that data to be utilized for running some php and mysql code. Can any one solve this?
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result) {
alert(result);
//$('.alert').show().html(result).delay(2000).fadeOut(3000);
setTimeout(function(){window.location.href = "index.php";},2000);
}
});
}
return result;
});
If what you want is to navigate to the index.php page on click of that button, then, do it this way:
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result) {
alert(result); //you may remove this. use console.log for debugging your js next time
setTimeout(function(){window.location.href = "index.php?result="+result;},2000); //why the timeout?
}
});
}
});
The easier and proper solution should be to re-use ajax to use this variable in another PHP file.
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result)
{
//AJAX code to execute your MySQL query
$.ajax({
type: "POST",
url: "read_data2.php",
data: result,
cache: false,
success: function (result)
{
//Manage your read_data2.php output
}
});
}
});
}
I have a script
$('#postinput').on('keyup',function(){
var txt=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt='+txt,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
Suppose someone types a ,ajax runs . Immediately he types b c and so on. Ajax runs everytime. Is there a way to stop previous request when new is made ?
You can use the abort() method of the xhr. Try this:
var currentXhr;
$('#postinput').on('keyup',function(){
currentXhr && currentXhr.readyState != 4 && currentXhr.abort(); // clear previous request
var txt = $(this).val();
var currentXhr = $.ajax({
type: "POST",
url: "action.php",
data: 'txt=' + txt,
cache: false,
context:this,
success: function(html) {
alert(html);
}
});
});
If you don't want to use a global variable, you could store the xhr in a data-* attribute of the #postinput element.
Another method is to only fire the AJAX request when the user has stopped typing:
var timer;
$('#postinput').on('keyup',function(){
clearTimeout(timer);
var txt = $(this).val();
var timer = setTimeout(function() {
$.ajax({
type: "POST",
url: "action.php",
data: 'txt=' + txt,
cache: false,
context:this,
success: function(html) {
alert(html);
}
});
}, 100); // sends request 100ms after typing stops.
});
You can do like this with Jquery-
jaxRequests = new Array();
queueRequest = function(whatever, you, want) {
if(ajaxRequests[ajaxRequests.length - 1]) {
ajaxRequests[ajaxRequests.length - 1].abort();
}
ajaxRequests[ajaxRequests.length] = //Insert New jQuery AJAX call here.
}
function getProject(){
var postData = {
'project' : proj_id
};
//console.log(postData);
var site_url = "<?php echo site_url('/'); ?>";
$.ajax({
type: "POST",
url: site_url + "maincontroller/project",
data: postData, //assign the var here
success: function(msg) {
$("#project").html(msg);
getSubProject();
}
});
Suppose that is a function now I want to apply a condition on AJAX response and response id is <div id="project"></div>. If response is successful then this div is generated otherwise not. Can anyone help me please?
Replace
$("#project")=.html(msg);
With
$("#project").html(msg);
try this
success: function(msg, status){
if (status == 200) {// ok
$("#project").html(msg);
getSubProject();
}
}
I need to post data to another server using jquery.
Here is the code i am using
$.ajax({
url:"https://www.thewiseagent.com:443/secure/webcontactAllFields.asp",
type:'POST',
data:"ID=" + $ID
+ "&Source=" + $Source
+ "¬ifyCc=" + $notifyCc
+ "¬ifyBcc=" + $notifyBcc
+ "&noMail=" + $noMail
+ "&CFirst=" + $first
+ "&CLast=" + $last
+ "&Phone=" + $Phone
+ "&Fax=" + $Fax
+ "&CEmail=" + $CEmail
+ "&Message=" + $message,
success: function() {
//window.location.href = "http://www.petlooza.com";
}
});
i got error (302 object moved) in case of firefox/chorme although data is inserting.. but in case of IE data is not entering in external database. In IE i got a Access denied error.
Can anyone have alternative?
I have tried with json and jsonp still same error.
$.ajax({
type: "POST",
url: "https://www.thewiseagent.com:443/secure/webcontactAllFields.asp",
data: dataString,
dataType: "jsonp",
success: function(data) {
}
});
If you want to use $.ajax() and make a request to another domain you must set crossDomain option to true as stated in the documentation
$.ajax({
url:"https://www.thewiseagent.com:443/secure/webcontactAllFields.asp",
type:'POST',
crossDomain: true,
data:"ID="+$ID+"&Source="+$Source+"¬ifyCc="+$notifyCc+"¬ifyBcc="+$notifyBcc+"&noMail="+$noMail+"&CFirst="+$first+"&CLast="+$last+"&Phone="+$Phone+"&Fax="+$Fax+"&CEmail="+$CEmail+"&Message="+$message,
success: function() {
//window.location.href = "http://www.petlooza.com";
}
});
You could make an AJAX request to a php script on your own server, which then gets the information from the other server and returns it to you jQuery. I can't think of any other way at the moment.
You have a crossdomain problem. Try using jsonp:
$.ajax({
url:"https://www.thewiseagent.com:443/secure/webcontactAllFields.asp",
type:'POST',
dataType: "jsonp",
data:"ID="+$ID+"&Source="+$Source+"¬ifyCc="+$notifyCc+"¬ifyBcc="+$notifyBcc+"&noMail="+$noMail+"&CFirst="+$first+"&CLast="+$last+"&Phone="+$Phone+"&Fax="+$Fax+"&CEmail="+$CEmail+"&Message="+$message,
success: function(data) {
//window.location.href = "http://www.petlooza.com";
}
});