This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
Hello I have a problem storing my json in a global variable, what I want is to do first all my ajax request then store each of the returned data to a global variable, but it seems it's not working correctly? Can Any help me to my problem? Thanks. :)
var series;
function columnChart(container)
{
url = base_url+"/codeigniter/index.php/AssistanceMonitoringModule/assistanceMonitoring/getSeries";
$.ajax(
{
type: "GET",
url: url,
success: function(data){
series = data;
},
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert("XHR:"+xhr.status+"Error:"+thrownError);
}
});
callColumnChart(container,series);
}
You are using the variable too soon. The Ajax request will not be completed when you call callColumnChart. Move it into the ajax callback.
$.ajax(
{
type: "GET",
url: url,
success: function(data){
series = data;
callColumnChart(container,series);
},
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert("XHR:"+xhr.status+"Error:"+thrownError);
}
});
Related
This question already has answers here:
AJAX not passing data to CodeIgniter Controller
(5 answers)
Closed 4 years ago.
is there anyway that i can pass a codeigniter session value through ajax and get results back ?my ajax request as follows
$.ajax({
method :'GET',
url: baseUrl+'ajaxcontroller/LoadData_To_View',
success:function(data){
$('#item').html(data);
console.log(data);
},
complete: function(){
$('#loadingImage2').hide();
},
error:function (xhr, ajaxOptions, thrownError){alert(thrownError);}
});
Yes you can actually! You can actually pass any variable through ajax through the data property but it has to be in a JSON Format. Here's the code below.
First Example:
$.ajax({
method: 'GET',
url: baseUrl + 'ajaxcontroller/LoadData_To_View',
data: {
id: "<?= $this->session->userdata('id') ?>",
username: "<?= $this->session->userdata('email') ?>"
},
success: function(data) {
$('#item').html(data);
console.log(data);
},
complete: function() {
$('#loadingImage2').hide();
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
OR you can pass the whole session like this!
$.ajax({
method: 'GET',
url: baseUrl + 'ajaxcontroller/LoadData_To_View',
data: <?= json_encode($_SESSION) ?>,
success: function(data) {
$('#item').html(data);
console.log(data);
},
complete: function() {
$('#loadingImage2').hide();
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
What matters is you have to have your variables in a JSON format for it to work! A JSON Format will be translated as a multidimensional array in the server side.
This question already has answers here:
Jquery load() only working in firefox?
(2 answers)
Read local XML with JS
(5 answers)
Closed 5 years ago.
I am using jQuery to call the AlphaVantage finance API for stock quotes in an HTML file on the local machine. However, the .get or .ajax calls are failing. I have tried using crossdomain and jsonp, but still the call fails in the error handler. The error text in the error handler is blank - so no indication is provided why it is failing. Any help would be appreciated. Here is the call:
$.ajax({
url: 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo',
crossDomain: true,
dataType: "json",
success: function(data, textStatus, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, error) {
console.log("Post error: " + error);
}
});
You have a typo (the ';' after the url). Remove it and try again...
$.ajax({
url: 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo'**;**,
crossDomain: true,
dataType: "json",
success: function(data, textStatus, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, error) {
console.log("Post error: " + error);
}
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've got AJAX which gets timezone information in a function and I want it to return the result.
I now understand that AJAX is asynchronous so I need to have a callback function. I've looked at examples but I can't wrap my head around it.... I'm not sure where the arguments in my getTimezone() function go if I change that to just take a callback function.
Any help would be appreciated, here's the code:
ztimezone=getTimezone(lat,lng);
function getTimezone( tlat, tlong) {
url = "https://maps.googleapis.com/maps/api/timezone/json?location="+tlat+","+tlong+"×tamp=1331161200&key=******";
$.ajax({
url: url,
type: "GET",
crossDomain: true,
dataType: 'json',
success: function (data) {
alert(data.timeZoneId);
zdata=((data.rawOffset/60)/60);
},
error: function (xhr, err) {
alert(xhr.responseText);
}
});
return zdata;
}
function getTimezone(tlat, tlong, callback) { // <----- HERE
var url = "https://maps.googleapis.com/maps/api/timezone/json?location="+tlat+","+tlong+"×tamp=1331161200&key=******";
$.ajax({
url: url,
type: "GET",
crossDomain: true,
dataType: 'json',
success: function(data) {
alert(data.timeZoneId);
var zdata = ((data.rawOffset/60)/60);
callback(zdata); // <----- HERE
},
error: function (xhr, err) {
alert(xhr.responseText);
}
});
// return zdata; // <----- HERE
}
The first line allows you to pass a callback into your function.
The one in the middle calls the callback with the result.
The last one is commented out because you can never return a result from an asynchronous function - you must use a callback (or, equivalently, a promise).
To use it, you would do this:
getTimezone(45, 16, function(zoneData) {
alert(zoneData); // or whatever
});
This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 8 years ago.
I'm trying to get a time data from json with the code bellow, but i get a error instead of the data, what can be happening?
$.ajax({
type: "POST",
url: "http://www.previsaodotempo.org/api.php?city=Rio+De+Janeiro",
success: function(data) {
alert()
data.location;
$("div").html(data);
},
error: function(data) {
$("div").html('can not get the json');
}
});
Here is a fiddle: http://jsfiddle.net/jodgjqwf/
Is http://www.previsaodotempo.org/api.php?city=Rio+De+Janeiro expecting you to POST to it? I just hit the url and it returned the JSON to me.
Change "POST" to "GET".
$.ajax({
type: "GET",
url: "http://www.previsaodotempo.org/api.php?city=Rio+De+Janeiro",
success: function(data) {
$("div").html(data);
},
error: function(data) {
$("div").html('can not get the json');
}
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have this javascript:
$ajax = $.ajax({
type: 'GET',
url: 'DBConnect.php',
data: '',
dataType: 'json',
success: function(data) {},
error:function (xhr, ajaxOptions, thrownError) {
dir(thrownError);
dir(xhr);
dir(ajaxOptions);
}
});
console.dir($ajax);
console.dir($ajax.responseJSON);
console.dir($ajax) shows it has a property named responseJSON, but when I try to access it with $ajax.responseJSON it returns undefined:
Well, of course it's undefined, because at the moment when you run console at last lines of your code, response hasn't yet came from the server.
$.ajax returns promise, which you can use to attach done() and fail() callbacks, where you can use all the properties that you see. And you have actually used callback error and success, and that's where you can run code and other functions that rely on data in the response.
You can use this trick to get the response out:
jQuery.when(
jQuery.getJSON('DBConnect.php')
).done( function(json) {
console.log(json);
});
It's late but hopefully will help others.
The response, is the "data", in success... so you can access to that writing data[0], data[1], inside the success.
For example:
success: function(data) {
alert(data[0]);
},
If you want this response, out of the success, you can set a variable outside, and try this:
success: function(data) {
myVar = data;
},
Hope, this help.
For those who don't really mind if it's synchronous, like I was, you can do this:
$('#submit').click(function (event) {
event.preventDefault();
var data = $.ajax({
type: 'POST',
url: '/form',
async: false,
dataType: "json",
data: $(form).serialize(),
success: function (data) {
return data;
},
error: function (xhr, type, exception) {
// Do your thing
}
});
if(data.status === 200)
{
$('#container').html(data.responseJSON.the_key_you_want);
}
});
It runs through the motions, waits for a response from the Ajax call and then processes it afterwards if the status == 200, and inside the error function if something triggered an error.
Edit the options to match your situation. Happy coding :)