Declaring Variable within AJAX function and Calling It Later (jQuery) [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I've got an AJAX function that works correctly but I can't seem to access variables that I'm declaring within the function later in the page. If you look at the below code, you'll see I alert the variable number_rows within the function which works but when I try to log it outside of the function, it comes back as 'undefined.'
var newData = "user_id=" + id;
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
var number_rows = response;
alert(number_rows);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
console.log(number_rows);
I understand my scope may be off. I tried to move all of my code within the success function but that causing a bunch of other issues so the easiest thing would be to get the response variable to be a global variable that I could use throughout the rest of the page's code. I also tried something like this:
success:function(response){
$('body').append('<span class="ajax_response" id="' + response + '"></span>');
}
var number_rows = $('.ajax_response').attr('id');
console.log(number_rows);
But for some reason it isn't able to pick up the ID value immediately that way. I can confirm that the span does get made with the correct ID value but for some reason it doesn't handle it correctly. Any help with this would be greatly appreciated.
Thanks!

Just add to your configuration:
async:false
Your code maybe look like this:
var newData = "user_id=" + id;
var number_rows = ""; //This is a global variable
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType:'text',
data:newData,
async:false, //<------This is the option you must add
success:function(response){
number_rows = response; //<----- receive data from the server
alert(number_rows);
},
error:function (/*stuff here*/){
//stuff here
}
});
//Check data
console.log(number_rows);
Good luck ^^!

Changed the scope of your variable.
Change async: false or wait till you get the response from server, then use the value.
var newData = "user_id=" + id;
var number_rows = ""; //Declare Here
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
async: false,
success:function(response){
number_rows = response; //assign here
alert(number_rows);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
console.log(number_rows); //Use here

Yes, your scope is off. If you defining a variable inside a function, as you do, you cannot access it outside. Also your ajax call is async and any code you.
Put your console.log inside the success function otherwise it will probably log undefined even if you declare the variable globally outside of the function.
var newData = "user_id=" + id;
var number_rows;
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
number_rows = response;
alert(number_rows);
console.log(number_rows); // here, so we are sure it's set.
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});

Related

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

How to make ajax success callback data available globally?

So i'have some data returned from a rails backend, and i would like to make those data available globally, i have read about windows.variable = success callback data but i have to set async:false on ajax request which is now deprecated and does not work.
Is there a new workaround on that?
here is my ajax code
function retrieve(date_partial) {
var jsondata = {
events: {
month: date_partial,
}
}
$.ajax({
cache: false,
type: "POST",
url: "/events/find",
data: jsondata,
success: function(data) {
for (var i = 0; i < data.events.length; i++) {
var day = data.events[i].date.substring(0, 2);
$("td[data-day='" + day + "']").addClass('added');
}
},
error: function(xhr) {
alert("The error code is: " + xhr.statusText);
}
});
}
i have read about windows.variable
That's exactly how you make a value available globally in JavaScript, setting it on the window object. Something like this:
window.someVariable = someValue;
but i have to set async:false on ajax request
You absolutely should not do that. It also has nothing to do with what you're asking. The window object is always available, that's what makes it global:
success: function(data) {
window.someVariable = data.someValue;
}
Once the callback runs, window.someVariable would contain the value and would be available to any other code on the page.

Passing an array to a web method in Javascript

I am currently trying to pass an array that I have created in Javascript to my webmethod in my aspx.cs.
Heres what I have:
JAVASCRIPT
function callServer(requestMethod, clientRequest) {
var pageMethod = "Default.aspx/" + requestMethod;
$.ajax({
url: pageMethod, // Current Page, Method
data: JSON.stringify({ request: clientRequest }), // parameter map as JSON
type: "POST", // data has to be POSTed
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 60000, // AJAX timeout
success: function (result) {
ajaxCallback(result.d);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
function myButtonCalls()
{
var values=[];
values[0] = "Hello";
values[1] = "goodbye";
callServer("myMethod", values);
}
ASPX.CS
[WebMethod]
public static string myMethod(string[] request)
{
return "This is test";
}
It fails before it even gets to my web method. I know this code works for regualr strings but The ajax code that uses JSON doesnt see to want to work with arrays.
Any ideas of what i need to change?
Thanks
In the aspx.cs, I needed to accept with type list not array. Thanks for the comments!

Array of Objects via JSON and jQuery to Selectbox

I have problems transferring a dataset (array of objects) from a servlet to a jsp/jquery.
This is the dataset sent by the servlet (Json):
[
{aktion:"ac1", id:"26"},
{aktion:"ac2", id:"1"},
{aktion:"ac3", id:"16"},
{aktion:"ac4", id:"2"}
]
The jsp:
function getSelectContent($selectID) {
alert('test');
$.ajax({
url:'ShowOverviewDOC',
type:'GET',
data: 'q=getAktionenAsDropdown',
dataType: 'json',
error: function() {
alert('Error loading json data!');
},
success: function(json){
var output = '';
for (p in json) {
$('#'+$selectID).append($('<option>').text(json[p].aktion).attr('value', json[p].aktion));
}
}});
};
If I try to run this the Error ('Error loading json data') is alerted.
Has someone an idea where the mistake may be?
Thanks!
If the error function is running, then your server is returning an error response (HTTP response code >= 400).
To see exactly what is going on, check the textStatus and errorThrown information that is provided by the error callback. That might help narrow it down.
http://api.jquery.com/jQuery.ajax/
The way you are setting the data parameter looks a bit suspect (notice JSON encoding in my example below). Here is how it would look calling a .Net asmx
$.ajax({
url: "/_layouts/DashboardService.asmx/MinimizeWidgetState",
data: "{'widgetType':'" + widgetType + "', 'isMinimized':'" + collapsed + "'}"
});
Also the return data is by default placed in the .d property of the return variable. You can change this default behavior by adding some ajax setup script.
//Global AJAX Setup, sets default properties for ajax calls. Allows browsers to make use of native JSON parsing (if present)
//and resolves issues with certain ASP.NET AJAX services pulling data from the ".d" attribute.
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
success: function(msg) {
if (this.console && typeof console.log != "undefined")
console.log(msg);
},
dataFilter: function(data) {
var msg;
//If there's native JSON parsing then use it.
if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
//If the data is stuck in the "."d" property then go find it.
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
handleAjaxError(XMLHttpRequest, textStatus, errorThrown);
}
});

Jquery post success variable scope

I'm trying to return the ajax success array from one function to another. For some reason I don't seem to be able to pass the data stored in a variable in the success part of the ajax function into the parent function to return.
I looked at this post to try and figure things out, but not such luck:
jQuery Ajax call - Set variable value on success
Thanks so much for any assistance.
Here's a simplified version of the code:
// make json_to_return global
var json_to_return;
function loop_through_data(){
// call the load_days function and put its array data into days_array
var days_data = load_days(03,2010);
// I'd like to be able to iterate through days_data here
//
//
}
function load_days(selectedMonth, selectedYear){
$.ajax({
type: "POST",
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
json_to_return = available_json;
},
error: function(msg){
alert("error " + msg);
}
});
return json_to_return;
}
This part of your function happens later:
success: function(available_json){
json_to_return = available_json;
}
So the variable you're returning is undefined, because the code to set it doesn't happen until the response comes back from the server. Either call the rest of the code to run from your success function, so it'll run when the data's ready, or set async:false (less desirable because it locks the browser).
The async: false method is like this:
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
json_to_return = available_json;
},
error: function(msg){
alert("error " + msg);
}
});
The better approach:
$.ajax({
type: "POST",
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
loopThroughTheDaysAndDoStuff(available_json);
},
error: function(msg){
alert("error " + msg);
}
});
$.ajax is an asynchronous function.
It means that when called, the function keeps executing.
In your code provided var days_data = load_days(03,2010); this happens:
Start an ajax call (asynchronous, function keeps executing)
return json_to_return (undefined)
days_data == undefined
ajax call finishes, json_to_return gets assigned (this can happen in any timespan)
You should rethink your logic, and start coding around the asynchronousity of the ajax call.
A first approach might be passing a function (callback) to load_days which should be called AFTER the success of the ajax call.

Categories

Resources