Assign ajax request result to variable in the jquery function - javascript

I am trying to assign value I receive from the php file to the jquery variable. The php file runs a loop and echos out a value. I am trying then to store the value in the jquery variable but I am getting NaN result back. How can I assign the value echoed from the php file into the variable in the jquery function?
var increment;
event.preventDefault();
$.ajax({
type: 'POST',
url: 'increment.php',
data: $(this).serialize(),
dataType: 'text',
success: function (data) {
//console.log(data);
data = increment;
}
});

You should be using
increment = data;
instead of
data = increment;
Also one more thing to note here is the request nature. Since the ajax request is asynchronous accessing the variable outside might show unexpected result. You have to access the variable once the ajax request is successful (inside success callback).

do like so,you should assign data recieved to increment var:
var increment;
event.preventDefault();
$.ajax({
type: 'POST',
url: 'increment.php',
data: $(this).serialize(),
dataType: 'text',
success: function (data) {
//console.log(data);
increment = data ;
}
});

Related

AJAX: Store PHP data in a Javascript variable

As stated in the title, I have an ajax call. On the success function I want to store the returned data into a variable for use in my javascript. randNum.php simply returns a random number every 2 seconds, and I would like to use that number for other functions in my scripts. How can I use the data sent back from the php file in my javascript?
I know there are more logical ways to go about this, but want to know how to accomplish the task this way.
var result;
var interval = 2000;
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
dataType: "html",
success:function (msg) {
result = msg; //Not working as I intend
setTimeout(myCall, interval);
}
});
}
function(){
do something with result;
}
Declare a Global variable outside of the function and assign response variable to it after the ajax response.
var results;
function TestJSONP(){
$.ajax({
url: "randNum.php",
jsonp: "callback",
dataType: "jsonp",
success: function (response) {
console.log(response);
results = response;
}
});
}
You might not need to specify dataType, but use jqXHR.responseText to get the raw response. Something like
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
success:function (data, textStatus, jqXHR) {
result = jqXHR.responseText;
setTimeout(myCall, interval);
}
});
}
When you set dataType, and the response is not that type, then the ajax did not succeed and error call back will be invoked.

Retrieve all 'data' properties of json data with ajax

I'm trying to figure out how to access to all the data from a json provided by movie database api, but I don't understand how to retrieve it.
The console log give me an "data is not defined" error.
So here is my code:
$(document).ready (function(){
var key = 'api key provided';
$.ajax({
type: 'GET',
url : 'http://api.themoviedb.org/3/search/movie'+key+'&query=Minions',
dataType: 'jsonp',
data: {
format:'json'
},
error: $('#result').append("errore"),
success: function(data){$('#result').append("ok")}
});
var jsonData=data.results.original_title;
//this give me a data is not provided
});
Here a portion of json:
Let's assume that I only want to access to the release_date propriety, how can I achieve this?
data not is defined out of $.ajax() closure, you need to move the code to success handler like, then loop through the JSON data.results.
success: function(data){
$('#result').append("ok");
console.log(data);
$.each(data.results, function(i, result) {
console.log('Release date is' + result.release_date);
});
}
alternatively, you can define a variable, then update that variable in success handler of $.ajax()
var ajaxResponse;
$.ajax({
/* skipped lines*/
success: function(data){
ajaxResponse = data
}
});

Javascript append to variable data echoed back from php

I have this lines of code placed inside an app i am currently developing. I send to the url the valdat variable which is then processed through a php file and then echoed back to the app. How can i append to a variable x the data the alert message displays?
var valdat="foo";
$.ajax({
url: 'http://www.link./file.php',
type: 'POST',
data: {
valdat:valdat
},
error: function(data) {
alert(data);
},
success: function(data) {
alert(data);
},
});
If you mean append the returning value directly to a known variable you can just use +=:
var valdat ="foo";
var x = "Something";
$.ajax({
url: 'http://www.link./file.php',
type: 'POST',
data: {
valdat:valdat
},
error: function(data) {
x += data;
alert(x); //Will output "Something" + the content of `data`
},
success: function(data) {
x += data;
alert(x); //Will output "Something" + the content of `data`
},
});
this resolved it...the ajax call was being performed async which means it runs parallel with the rest of JS, meaning that the compiler does the following things:
1)valdat=foo
2)x=bar
3)h=x
4)ajax call
so the program didn't know who x was because it didn't have one until the end of it
https://stackoverflow.com/a/5936026/5467736

variable appearing blank after ajax, but has value within ajax success function

As the title says, I have an ajax function that I am using to call a function that assigns a value to a variable in js from my mysql db. On success, I can print the echoed data out and it appears in the console fine. However, calling the variable after the ajax call yields an empty variable. What is going on?
Code below:
request = $.ajax({
url: "/fans/get_url_tag",
type: "post", success:function(data){url_tag = data; console.log(url_tag); //prints the correct value},
data: {'fbid': result.id} ,beforeSend: function(data){console.log(data);}
});
//prints nothing
console.log(url_tag)
Sounds like the scope is wrong.
Maybe just declare it before your $.ajax call:
var url_tag;
request = $.ajax({
url: "/fans/get_url_tag",
type: "post", success:function(data){url_tag = data; console.log(url_tag);},
data: {'fbid': result.id} ,beforeSend: function(data){console.log(data);}
});
console.log(url_tag); //Should print the same value
You need to put the console.log in the callback function.

javascript & jQuery scope question

I have the following method:
function priceRange(FESTIVALID){
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
}//success
});//ajax;
//
return formatedPriceRange;
};
The second console.info correctly displays the formatedPriceRange,
but outside the function is undefined.
how can I access this variable out side the priceRange function?
Thanks
It's normal, that's how AJAX works. It's asynchronous, meaning that the jQuery.ajax function returns immediately and in this case formatedPriceRange hasn't yet been assigned a value and once the server responds (which can be for example 10 seconds later), the success callback is invoked and the variable is assigned a value.
So always consume the results of your AJAX requests inside the success callback function.
You also have the possibility to pass the async: false option to your jQuery.ajax call which will perform a synchronous request to the server and block until the result is retrieved. Obviously this will lead to your browser freezing during the execution of the request. So it would no longer be AJAX (Asynchronous Javascript And Xml) but SJAX (Synchronous Javascript and Xml).
You have to make sure that the AJAX request finishes before you access the price range data.
You need to expose the price range data outside the scope of the success function.
Here's how you can do it:
function priceRange(FESTIVALID, callback) {
jQuery.ajax({
url: '/actions/festheads.cfc?method=getPriceRangeByGUID',
type: 'POST',
data: 'FESTIVALID=' + FESTIVALID,
dataType: 'json',
success: function(data) {
console.info("AJAX:qPrices", data.MINPRICE);
formatedPriceRange = '$ ' + data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
callback.call(this, formatedPriceRange);
} //success
}); //ajax;
}
var myFestivalID = 1;
priceRange(myFestivalID, function(priceRange) {
// this code runs when the ajax call is complete
alert('The formatted price range is:' + priceRange);
});
how can I access this variable out
side the priceRange function?
Like Darin said, you have to use your results in the success callback function.
Assuming you're using your current function like this:
var range = priceRange(festivalId);
// ... doing stuff with range variable
You'll want reorganize your code so that anything you do with the range variable stems from the success callback. For example, you can create a function to handle updating the UI with the new range:
function handleRangeVariabe(range) {
/// ... do stuff with range variable
}
Call it from success:
success: function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
handleRangeVariable(formatedPriceRange);
}
Flower the steps of sample Code:
//declare function
function priceRange(FESTIVALID, functionCallBack){
//1º step
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
//3º step, because this function will only trigger when server responds to request
//handle data in other function
functionCallBack(data);
}//success
});//ajax;
//more code
//2º step
//no return value, because this method no know when the data will return of server
//return formatedPriceRange;
};
var formatedPriceRange;
//using function
princeRange(1 , function(data){
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
});

Categories

Resources