javascript updating hidden value - javascript

I have a function:
function add() {
$.ajax({
type: "POST",
url: "add.php",
async: "false", // Tried both- async: "false/true"
data: {
name: 'Test',
},
success: function(data) {
document.getElementById('id').value = data;
id = document.getElementById('id').value;
alert(id); // alerts here proper value
}
});
}
function testMyFunction() {
add();
// 'id' was set in add function.
id = document.getElementById('id').value;
alert(id); // Here does not alert value but blank(no value)
// This 'id' value is used at other place but here is issue.
}
Calling testMyFunction() function gives above mentioned issue.
What could be a issue?

$.ajax is an asynchronous call and it updates "id" field after if it is completed. Your code checks for its value in function testMyFunction() instantly after the invocation (and before success: function(data) is invoked).

JavaScript is an asynchronous language. In a nutshell, this means that your code should NEVER block: functions should either complete immediately or get called later, i.e. after some input/output operation is complete (e.g. AJAX request).
Edited: BTW, your code does not work because even with async: false the success function is called in the event loop, thus this can occur even after the code that follows synchronous AJAX. If you use async: true, the AJAX will block, but the success function will be called asynchronously in any case.
So to handle data synchronously, you have to work not with success function, but rather with an object that is returned by $.ajax() call:
var xhr = $.ajax({
type: "POST",
async: false,
url: "add.php",
data: {
name: 'Test',
},
});
alert(xhr.responseText); // Alerts result
Thus, you should never use async: false. Instead, better refactor your code to be like this:
function add(callback) {
$.ajax({
type: "POST",
url: "add.php",
data: {
name: 'Test',
},
success: callback
});
}
function testMyFunction() {
add(function(data) {
// This closure will be called AFTER the request is complete.
document.getElementById('id').value = data;
alert(data); // Alerts proper value.
});
}
Basically, this pseudo-code is WRONG:
result1 = action1();
result2 = action2(result1);
result3 = action3(result2);
...and should be written like this:
action1(function(result1) {
action2(result1, function(result2) {
alert(action3(result2));
});
});

Related

simple hard coded ajax return value always undefined

I have an Ajax call and a PHP function. Firefox shows an HTTP 200 status. I can see the value "false" in the response, but it does not get passed to the success part of the Ajax handler; I always get undefined.
I have done a lot of Ajax before and many similar ones in my project and never had this issue. It is normal that the parameter is blank and should not affect anything.
I tried Async, print, return and even converting to JSON but not luck. No errors are showing up anywhere.
JavaScript:
function Init() {
$.ajax({
url: "php/file.php",
type: "post",
data: {
action: "userInit",
parameter: "",
success: function(result) {
alert(result);
},
},
});
};
PHP:
function userInit() {
echo('FALSE');
};
firefox report #1
firefox report #2
function Init() {
$.ajax({
url:"php/file.php",
type: "post",
data: {
parameter: "123"
},
success: function (result) { // Success is a callback function, it is part of your data object in the code which is wrong.
alert(result);
},
});
};

How to pass a variable from ajax to nested ajax

I'm sending ajax call and getting an answer that I need from the first ajax then I want to pass my result to my nested ajax, my var (result) is null in the nested ajax/settimeout fun, can I pass it ? Am I missing something ?
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
contentType:'json' ,
dataType:'text',
success: function (result) {
alert(result);**-> is fine - not null**.
// a or result is null when I hit the getCurrentDoc- function althought I get the data I need from getCustomerGuidId function
var a = result;-> tried to pass it to a new var..IDK.. I
thought it will help... it didn't.
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,-> here it's null
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});
You can try something like this will help to pass value to nested ajax call
function test(){
var myText = 'Hello all !!';
$.get({
//used the jsonplaceholder url for testing
'url':'https://jsonplaceholder.typicode.com/posts/1',
'method':'GET',
success: function (data) {
//updating value of myText
myText = 'welcome';
$.post({
'url':'https://jsonplaceholder.typicode.com/posts',
'method':'POST',
//data.title is the return value from get request to the post request
'data':{'title':data.title},
'success':function (data) {
alert(data.title +'\n' + myText);//your code here ...
}
});
}
});
}
An old question and you've likely moved on, but there's still no accepted answer.
Your setTimeout takes an anonymous function, so you are losing your binding; if you have to use a Timeout for some reason, you need to add .bind(this) to your setTimeout call (see below)
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,
success: function (data) {
}
});
}.bind(this), 2000);
At a guess you're using a Timeout because you want to ensure that your promise (i.e. the first ajax call) is resolving prior to making the nested call.
If that's your intention, you can actually scrap setTimeout completely as you have the nested call in the first ajax success call, which only runs once the promise has been resolved (providing there isn't an error; if so, jQuery would call error rather than success)
Removing setTimeout means you won't lose your binding, and a should still be result (hopefully a is an object, otherwise your second call is also going to experience issues...)
Lastly, after overcoming the binding issue you wouldn't need var a = result; you should be able to pass result directly to your nested ajax call.
Good luck!
In the nested ajax you send a as a param name, not as a param value.
So you can try the following (change param to actual param name which your server expects):
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
dataType:'text',
success: function (result) {
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
data: {param: result},
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});

How to add a callback on click jQuery function?

I have an asynchronous problem and for solve it I think I must use a callback. I want to execute some code after the code that is inside of the click() function finishes. How can I do that?
$("#mybutton").click(function() {
$.ajax({
type: 'GET',
data: {
accion: "get_option_child",
id: id
},
url: 'webservices.php',
success: function(data) {
var json = JSON.parse(data);
// some code
}
});
});
Just add a call to your desired function at the end of the success handler for ajax:
$("#agregar_opcion").click(function() {
// ...
$.ajax({
// ...
success: function(data) {
// ...
functionThatRunsAfterAjaxSuccess();
}
});
});
function functionThatRunsAfterAjaxSuccess() {
// gets called once the ajax call happening on click is successful
}

how to use ajax response data in another javascript

I am working with google map.My map data come from php using ajax response.
My ajax code:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
console.log(result);
}
});
</script>
Now I have need to put my response data in my map var location
function initialize() {
var locations = [
//Now here I put my ajax response result
];
How can I do that?
You'll have to refactor your code a little. I'm assuming you call initialize from the success callback.
Pass the locations array as an argument to initialize.
function initialize(locations) { ... }
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
initialize(result);
}
});
Then you can cut down even more and just do success: initialize, as long as initialize doesn't expect other parameters.
Here is a fiddle with an example using $.when but its for SYNTAX only not making the call
http://jsfiddle.net/2y6689mu/
// Returns a deferred object
function mapData(){ return $.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text'
});
}
// This is the magic where it waits for the data to be resolved
$.when( mapData() ).then( initialize, errorHandler );
EDIT** function already returns a promise so you can just use
mapData().then()
per code-jaff comments
This is done using callbacks, http://recurial.com/programming/understanding-callback-functions-in-javascript/ , here's a link if you want to read up on those. Let's see your current code here:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
console.log(result);
}
});
</script>
As you noticed, the 'result' data is accessible in the success function. So how do you get transport it to another function? You used console.log(result) to print the data to your console. And without realizing it, you almost solved the problem yourself.
Just call the initialize function inside the success function of the ajax call:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
initialize(result);
}
});
</script>
Is expected dataType response from $.ajax() to mapajax.php call text ?
Try
$(function () {
function initialize(data) {
var locations = [
//Now here I put my ajax response result
];
// "put my ajax response result"
// utilizing `Array.prototype.push()`
locations.push(data);
// do stuff
// with `locations` data, e.g.,
return console.log(JSON.parse(locations));
};
$.ajax({
type: "POST",
url: "mapajax.php",
dataType: 'text',
success: function (result) {
initialize(result);
}
});
});
jsfiddle http://jsfiddle.net/guest271314/maaxoy91/
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Two Ajax onclick events

So I have had to modify some old existing code and add another ajax event to onclick
so that it has onclick="function1(); function2();"
This was working fine on our testing environment as it is a slow VM but on our live environment it causes some issues as function1() has to finished updating some records before function2() gets called.
Is there a good way to solve this without modifying the js for function2() as this the existing code which is called by other events.
Thanks
Call function2 upon returning from function1:
function function1() {
$.ajax({
type: "POST",
url: "urlGoesHere",
data: " ",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//call function2
},
error:
});
}
Or wrap them in a function that calls both 1 and 2.
You need to use always callback of ajax method, check out always callback of $.ajax() method http://api.jquery.com/jquery.ajax/.
The callback given to opiton is executed when the ajax request finishes. Here is a suggestion :
function function1() {
var jqxhr = $.ajax({
type: "POST",
url: "/some/page",
data: " ",
dataType: "dataType",
}).always(function (jqXHR, textStatus) {
if (textStatus == 'success') {
function2();
} else {
errorCallback(jqXHR);
}
});
}
I'm assuming you use Prototype JS and AJAX because of your tags. You should use a callback function:
function function1(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function function2(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function both() {
function1(function() {
function2();
});
}
Then use onclick="both();" on your html element.
Example: http://jsfiddle.net/EzU4p/
Ajax has async property which can be set false. This way, you can wait for that function to complete it's call and set some value. It actually defeats the purpose of AJAX but it may save your day.
I recently had similar issues and somehow calling function2 after completing function1 worked perfectly. My initial efforts to call function2 on function1 success didn't work.
$.ajax({
type: "POST",
url: "default.aspx/function1",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // to make function Sync
success: function (msg) {
var $data = msg.d;
if ($data == 1)
{
isSuccess = 'yes'
}
},
error: function () {
alert('Error in function1');
}
});
// END OF AJAX
if (isSuccess == 'yes') {
// Call function 2
}

Categories