I have problems with AJAX results using jQuery.
I have defined these functions:
<script>
function hello(callback, funct, val) {
var ret = 0;
console.log(val);
$.ajax({
type: 'GET',
dataType: 'json',
url: 'SGWEB/header.php',
data: {
'funct': funct,
'val': val
}
}).done(function (data) {
// you may safely use results here
console.log(data);
callback(data);
});
};
function change() {
hello(function (ret) {
console.log(ret);
$("#b1").text(ret);
}, "hello", 1);
};
change();
</script>
SGWEB/header.php:
extract($_GET);
$validFunctions = array("readPin","hello");
if(in_array($funct, $validFunctions)) $funct();
// functions
// ....
function hello($val) {
if ($val == 1) {
echo "1";
} else
echo "2";
}
The problem I have is that the AJAX passes only the first parameter in data {'funct': funct} and it's working, but val is completely ignored (it always echoes "2").
How can I solve this? Thanks
You are forgetting to pass the $val parameter to your function in PHP
Change this:
if (in_array($funct, $validFunctions)) $funct();
to this:
if (in_array($funct, $validFunctions)) $funct($val);
Another problem is that your AJAX is expecting JSON as you are defining it here dataType:'json' but you are not sending that. I would redo your ajax call like this so that you can see other errors as well:
$.ajax({
type: 'GET',
url: 'SGWEB/header.php',
data: {
'funct': funct,
'val': val
},
success: function (result) {
console.log(result);
callback(result);
},
error: function (xhr, textStatus, error) {
console.log(xhr);
console.log(textStatus);
console.log(error);
}
});
Related
i have ajax call inside my function make it reusable, when my ajax success i want to callback a function,
var ajaxPostCall = function(data , url ,callback){
// Return the $.ajax promise
$.ajax({
data: data,
dataType: 'json',
url: url,
method: 'POST',
beforeSend: function() {
onStartAjaxRequest();
},
success:function(data){
if(typeof callback == "function"){
callback();
}else{
console.log('not callback');
}
},
complete: function (XMLHttpRequest, textStatus) {
onEndAjaxRequest();
}
});
}
var ajaxGetCall = function(data , url ,callback){
// Return the $.ajax promise
$.ajax({
url: url,
dataType: 'json',
method: 'GET',
beforeSend: function() {
onStartAjaxRequest();
},
success:function(data){
//console.log('test');
if(typeof callback == "function"){
callback();
}else{
console.log('not callback');
}
},
complete: function (XMLHttpRequest, textStatus) {
onEndAjaxRequest();
}
});
}
function onStartAjaxRequest(){
$('#spinner').hide();
}
function onEndAjaxRequest(){
$('#spinner').show();
}
$(document).ready(function(){
data = {'name' : 'john'};
function callbackSuccess(){
console.log('success');
}
ajaxPostCall(data , '/proccess.php' , function(){
console.log('success 1');
});
ajaxGetCall(data , '/proccessGet.php?id=12' , function(){
console.log('success 2');
});
})
when i run this code, both of ajax post and get can work.but why only my ajaxget can call the callback 'success2' , the ajaxpost doesnt show 'success1' .. any idea?
image
well, i just find out myself and i know the problem...my proccess.php on ajaxpost is not returning json object properly , meanwhile i put dataType: 'json' in my ajaxpost, thats why my ajaxpost is not going to success callback
but i still wonder on my ajaxget still going to success callback even my /proccessGet.php?id=12 does not return json object , is ajax with GETmethod ignoring datatype:json?
i have an issue and i need an idea for solve :)
I have 2 call to $.ajax
First, is asynch, and during a lot of time (1 minutes for example)
Second, is sync (in ajax async: false) and it response fast (5 sec for example)
Second call is in a loop (requests->response->print data, request->response->print data).
I need when first finish (success or error), stop second call.
I attach an example code:
var success = false;
$.ajax({
type: "POST",
url: urlRest,
data: {
data: dataSend
},
success: processOK,
error: processError
});
do {
$.ajax({
type: "POST",
url: urlData,
data: {
data: dataSend
},
async: false,
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(data, textStatus, jqXHR){
console.log("Error");
}
});
} while (!success);
I hope it's clear :)
I corrected an issue that would cause some errors, try this out.
let printData = function( input ){
let config = {
urlRest: '',
data: { data: {} },
loop: false,
callback: false
}
$.each(config,function(k,v){ config[k] = input[k] });
config.loop = false;
$.ajax({
type: 'POST',
url: config.urlRest,
data: config.data,
success: function( data ){
// Based on the response if you need to run again change config.loop to true and it will run again
// you can also alter anything your sending through
if( config.loop ) printData( config );
else if( typeof config.callback === 'function' ) callback();
},
error: function(){
// Based on the response if you need to run again change config.loop to true and it will run again
// you can also alter anything your sending through
if( config.loop ) printData( config );
else if( typeof config.callback === 'function' ) callback();
}
});
}
printData({
urlRest: '', // URL Here
data: data, // Data Object
loop: true, // Set this to true if you want it to loop
callback: function(){
console.log( 'Job Complete' );
}
})
You can run async calls in synchronous manner using SynJS:
function ajaxWrapper(ctx, url, data){
var res={done:false};
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){
res.data=result;
},
error: function(){
res.error=true;
},
}).always(function(){
res.done = true;
SynJS.resume(ctx); // <-- tell caller that callback is finished
});
return res; // <-- return object that will hold the results
}
// function that is executed in synchronous manner
function myFunc(modules, urlRest, urlData) {
var success = false;
var res1 = modules.ajaxWrapper(_synjsContext, urlRest, urlData);
SynJS.wait(res1.done); // <-- wait for result from callback
do {
var res2 = modules.ajaxWrapper(_synjsContext, urlRest, urlData);
SynJS.wait(res2.done); // <-- wait for result from 2nd callback
} while (!success);
}
var modules = {ajaxWrapper: ajaxWrapper};
SynJS.run(myFunc,null, modules, "/", {}, function () {
console.log('done');
});
You can change the success value like this
$.ajax({
type: "POST",
url: urlRest,
data: {
data: dataSend
}
}).always(function() {success=true;});
Or you can create a self call function (after the second ajax finish, calls it again) but before the call its checks the success variable like #mplungjan did.
It is never a good idea to loop Ajax. You need to allow the call to return.
Here is an example that is NOT using async false
var firstDone = false,tId;
// call long ajax
$.ajax({
type: "POST",
url: urlRest,
data: {
data: dataSend
}
}).done(processOK);
}).fail(processError)
}).always(function() {firstDone=true; clearTimeout(tId);}); // stops the other loop
// setup function that can be looped
function callAjax() {
if (firstDone) return;
$.ajax({
type: "POST",
url: urlData,
data: {
data: dataSend
}
}).done(function(data, textStatus, jqXHR) {
console.log(data);
}).fail(function(data, textStatus, jqXHR) {
console.log("Error");
}).always(function() {
tId=setTimeout(callAjax,1000); // give the server time to recover
});
}
callAjax();
I have one html element (elem1) and 2 JS functions (func1, func2) that hides and shows elem1 respectively. These JS functions make individual ajax calls and func2 is calling func1 internally.
Problem: I need to call func2, which internally calls func1. Calling func1 hides elem1. After calling func1, I want to show elem1. But this show is not working.
JSFiddle: https://jsfiddle.net/46o93od2/21/
HTML:
<div id="elem">
Save ME
</div>
<br/>
<button onclick="func1()" id="func1">Try Func1</button>
<button onclick="func2()" id="func2">Try Func2</button>
JS:
function func1() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
$('#elem').hide();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
func1();
$('#elem').show();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
Make func1 take a callback function that tells it what to do after it gets the response. func2 can pass a function that shows the element.
function func1(callback) {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
if (callback) {
callback();
} else {
$('#elem').hide();
}
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
func1(function() {
$('#elem').show();
});
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
DEMO
I am trying to execute a WCF service call, from function one(). Only once this is complete I want function two() to be executed. The issue I have is that function two() is invoked before function one() completes execution and the WCF service returns the result. How can I solve this please? I am using callback function, so I can't figure out why, given that the response does not exceed 3 seconds.
<script type="text/javascript">
var jsonGetFileResult = "";
function one(callback) {
setTimeout(function() {
//var jsonGetFileResult = "";
console.log('01: into one');
$.ajax({
type: 'GET',
url: ‘http: //wcf.google.com’, //this is the wcf call
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {},
timeout: 10000,
success: function(data) {
jsonGetFileResult = stringifyNewsletter(data);
console.log('03: ' + jsonGetFileResult);
},
error: function(data) {
alert(error);
}
});
callback();
}, 3000);
}
function stringifyNewsletter(data) {
var removeHeader = JSON.stringify(data);
var file = removeHeader.split('"');
console.log('02: ' + file[3]);
return file[3];
}
function two(linkToNewsletter) {
window.open(linkToNewsletter, '_blank', 'location=yes');
return false;
}
/* now we make use of the callback */
one(function() {
alert(jsonGetFileResult);
// "one" triggers "two" as soon as it is done, note how "two" is a parameter
two(jsonGetFileResult);
});
</script>
You're invoking the callback outside of the ajax "success" function. The $.ajax() call is asynchronous — the call will return to your code essentially immediately, after launching the HTTP request and without waiting for it to finish.
If you move the line
callback();
to inside the "success" handler, then that will run after the HTTP request completes.
You need to put callback inside success function like that:
function one(callback) {
setTimeout(function() {
//var jsonGetFileResult = "";
console.log('01: into one');
$.ajax({
type: 'GET',
url: ‘http: //wcf.google.com’, //this is the wcf call
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {},
timeout: 10000,
success: function(data) {
jsonGetFileResult = stringifyNewsletter(data);
console.log('03: ' + jsonGetFileResult);
callback();
},
error: function(data) {
alert(error);
}
});
}, 3000);
}
I have a function in which I execute an ajax request and wait till I get a response and return a value but the value returned is undefined. What is wrong?
function GetVMData(url_s){
return $.ajax({
url: url_s,
crossDomain: true,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert('failed')
}
}).pipe(function(data) { return data[4]; });
}
If I print the value of data[4] within the ajax callback it prints the right value, therefore i know the request is going through but when I try this:
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord)
the value of cord is wrong.
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord)
This code runs asynchronously. So you need to perform everything in the callback, like:
GetVMData(url).done(function(cpu_USG) {
alert(cpu_USG);
});
Here:
var cord;
cord = GetVMData(url).done(function(cpu_USG) {
return cpu_USG;
});
alert(cord);
cord contains object, not the value. And by the way, you don't know where ajax calling will be finished, so you should be familiar with idea of callbacks..
As an example:
function makeRequest(url, callback) {
$.ajax({
url: url,
crossDomain: true,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert('failed')
},
success: callback
});
}
var do_something = function (data) {
alert(data[4]);
};
cord = makeRequest(url, do_something);