i'm having a problem with a variable at my jquery, follow the code:
var resp;
if(itcode != ""){
resp = $.ajax(
{url: url_rq}
);
resp.done(function () { alert(resp.responseText); });
}
If i put the "resp.responseText" like this above it prints the response, but if i try this code:
var resp;
if(itcode != ""){
resp = $.ajax(
{url: url_rq}
);
}
alert(resp.responseText);
It prints "undefined", what's going on with my "resp" variable?
Your Ajax example is asynchronous, so you need to use a callback function (as in your first example) to get and do something with the results. In your second example, you're not using a callback function, so the alert gets triggered before the Ajax call returns.
in your second code, when it print the variable, the ajax request was still on the fly, you should not code it like that and only follow the first sample as ajax is asynchronous
Well since $.ajax is asynchronous it will finish executing after your alert() shows up, so basically in the context of your alert the resp variable is undefined as it hasn't been processed yet by the ajax request.
I think the difference is that when you call
resp.done(function () { alert(resp.responseText); });
it waits for the ajax to return an answer and then prints the variable.
If you change that line for the one outside you will get undefined on both.
The thing is you always have to define a callback for the ajax call to start using its return value. Javascript is asynchronous and will not wait until the request is over.
Related
Hi i am using ajax first time
my i am using get method in Ajax
my code Ajax code is
$("#comboBox1").change(function() {
var text2 = $(this).children(':selected').text();
var value2 = $(this).val();
alert(text2 + " = " + value2);
document.getElementById("hid1").value = value2;
$.get('Check1',{hid1:value2},function(res){
$('#block3').load("new1.jsp");
});
if($('#cb5').length){
alert("Found");
combo2=$('#cb5').html();
alert(combo2);
}else{
alert("Not-found");
}
});
i need to call as asynchronous so where to put async:true in my code.
I am first time use Ajax so i Dose not know....
if anyone help me...
async:true is default in jQuery framework
If you want manage by $.ajaxSetup() function, because $.get dose not provide the pass additional setting params,
$.ajax() will be better and more intuitive
OR
$.ajaxSetup({async:true}); to setup globally
The "load" function you are using is already performing an (asynchronous) Ajax call. You do not have to add anything. It is asynchronous by itself.
See here for some more information.
To execute code after the function returns you can use
$('#block3').load("new1.jsp",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Found");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
I'm adding some custom JS to an application built in Wordpress to set appointments so that if an appointment request is made, both the client and worker are sent request emails. The appointment is made by pressing a button, and the request is made by binding the button to the .click() event.
To send the emails, I put the ajax function inside the success function of the first ajax function to approve the appointment, so that if the appointment was approved, the emails are sent. I was trying to set this up, but found that no matter what I did, the second ajax function inside the success function wouldn't fire, and it wouldn't even correctly report what the error was.
To test to see if this was the ajax function itself that was at fault, I took it out of the success function and put it within $(document).ready(function() { }), binding it to a different event to see if it would fire - and it did. So the function itself is not the problem, but rather that it is inside the success function of another ajax request.
What should I do to get this to fire? Other suggestions on Stack Overflow are very confusing at best, so please pardon me for asking again, but there doesn't seem to be a clear satisfactory answer to this.
This is the code that I put within the first ajax request's callback function, which worked perfectly well when I took it outside the callback function and bound it to a different eventy.
$.ajax({
type: "POST",
dataType: "JSON",
url: "[home url]/wp-admin/admin-ajax.php",
data: "action=finchJsonTest",
success: process_lesson_request,
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
alert("Something\'s not right!");
}
});
function process_lesson_request(data) {
alert("Hooray!");
console.log(data);
}
And this is the php function that Wordpress calls to handle this ajax request (determined by the "action" variable in the data string) - there's nothing too important going on, I was just testing to see if it would successfully return a JSON object
function finchJsonTest() {
$json_array[] = 'This is something!';
$finaljson_array = json_encode($json_array);
echo $finaljson_array;
die();
}
add_action( 'wp_ajax_nopriv_finchJsonTest', 'finchJsonTest' );
add_action( 'wp_ajax_finchJsonTest', 'finchJsonTest' );
Again, if I use this ajax call on its own bound to some event, it works perfectly and returns the desired JSON object (just text saying 'this is something'), but if I put this in the success callback function of another ajax request, it fails, and does not even throw what the error is. I have in fact read other Stack Overflow posts related to this, and wasn't able to make heads or tails of what to do. Any thoughts out there?
On my website I have mouse over and mouse out events set up on an HTML table. These events trigger ajax requests, and perform certain actions etc. However, i want to be able to not trigger a second request if one is already running. So, is there away to detect these requests, and therefore avoid a second. Incidentally Im using the jQuery $.ajax()
if it helps at all.
Thanks in advance
Chris
I'd try something simple like:
var requestMade = false;
function yourAjaxFunction(){
if(!requestMade)
{
requestmade = true;
$.ajax({
url: "page",
success: function(){
requestMade = false;
}
error: function(){
requestMade = false;
}
});
}
}
You can use the success: and error: settings to change the variable back to false.
I have never used the error so you may have to include some other things in it, but this is the general idea.
For this suppose I'd use ajaxStart() and ajaxStop() which would change specific variable ajaxRunning which could be checked before sending the request (maybe in ajaxStart() directly?)
Set global or local static variable to true when first ajax is about to trigger, than add if before triggering the second one ;) Than after one request is finished, set this variable to false
I have a page which needs to use $.post() but for some reason the exact code works when I run it from the firebug console but not from my script? My script is:
$(document).ready(function () {
$('#dl_btn').click(function () {
$.post(
"news_csv.php",
$("#dl_form").serialize(), function (data) {
alert('error');
if (data == 'success') {
alert('Thanks for signing up to our newsletter');
window.open("<?php echo $_GET['link']; ?>");
parent.Shadowbox.close();
} else {
alert(data);
}
});
});
});
It isn't the link as that does get printed properly but it gives me an error on line 140 of jquery min, I have tried using different versions of jquery and to no avail. I really dont understand why this isn't working.
When I changed from $.post to $.ajax and used the error callback I did receive an error of 'error' and the error is undefined?
Don't suppose anyone has any ideas? Would be much appreciated.
Thanks,
Tom
Is your click button placed inside a form element?
Cause doing so, clicking on it will not only trigger the onClick event you have binded to, but form submit as well, so you will end up in a case where your browser is executing both requests in parallel - with unpredicted outcome, of course.
I tried the same code with an element that does not trigger form submit and it worked as expected.
One point though: if you plan to use simple string as a return value and to do something with it (display it or so) then is ok to do what you do right now. However, if you have more complex response from the ajax request, you should specify the response type (xml, json..) as the last parameter of the post method.
Hope this helps.
What is the correct way of assigning to a variable the response from jQuery.get() ?
var data = jQuery.get("output.csv");
I was reading that jQuery.get() must have a callback function? why is that? and how would i use this callback function to assign the response back to the data variable?
Thanks in advance for your help and clarification.
Update:
Thank you all for your answers and explanations. I think i am starting to finally grasp what you are all saying.
My code below is doing the right thing only the first iteration of it.
The rest of the iterations its writing to the page undefined.
Am i missing something?
<tbody>
<table id="myTable">
<script type="text/javascript">
$.get('output.csv', function(data) {
csvFile = jQuery.csv()(data);
for ( var x = 0; x < csvFile.length; x++ ) {
str = "<tr>";
for ( var y = 0; y < csvFile.length; y++) {
str += "<td>" + csvFile[y][y] + "</td>";
}
str += "</tr>";
}
$('#myTable').append(str);
});
</script>
</tbody>
</table>
A callback function is required for asynchronous function calls, like an AJAX GET request. There is a delay between calling the get function and getting a response back, which could be a millisecond or several minutes, so you need to have a callback function that gets called when the asynchronous GET has completed its work.
Here's some more info on jQuery's AJAX get function: http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype.
From jQuery's examples:
// this would call the get function and just
// move on, doing nothing with the results
$.get("test.php");
// this would return the results of the get
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
If you get undefined when you try to use the data variable in the callback function, open up the console in Firebug in Firefox and watch the get request. You can see the raw request and the response that it comes back with. You should get a better indication of the issue after seeing what's being sent to the server and what's being sent back to the client.
tsvanharen answered the question well, but DCrawmer's still missing the point. Let me attempt a clarification for him. I'm oversimplifying some of this, and smoothing over some details.
Look at the code shown below. This is pretty much the same code as tsvanharen's, except that I've replaced the anonymous function for the callback with an actual function pointer, and am a little more explicit so you can see what's going on:
var x = null;
function myCallback(data)
{
alert("Data Loaded:" + data);
}
$.get("test.php", myCallback);
// the rest of your code
alert("The value of X is: " + x);
Assuming that test.php takes even a moment or two to load, notice the order that the alerts probably come up in:
1. "The value of X is"
2. "Data Loaded"
The function $.get() runs instantaneously. JavaScript moves on and runs the rest of your code right away. In the background, it's retrieving your page at test.php. jQuery hides some of the messy details of this.
The callback function (the second argument to $.get()) runs later (asynchronously). Or, said another way, the function myCallback is a handler to an event. That event is "$.get() has finished retrieving the data". It doesn't get run until that point. It doesn't run when $.get() runs! $.get() just remembers where that function is for later.
The function myCallback may run milliseconds or minutes later, long after $.get() has been dealt with.
If myCallback doesn't run until minutes later, then what's the value of x when the "The value of X" code is run? It's still null. There's your bug.
To use the data retrieved from the page in your script, you have to do things more like this:
Start your script, declare your variable to hold the data.
Call $.get(), with a callback function to handle the return.
Do nothing else. [Or, at least, nothing that requires the data]
Let the page just sit there.
...sometime in the future...
X. Your callback function will get run, and have the results of your web page.
Your callback function can:
* Display the data
* Assign that data to a variable
* Call other functions
* Go along it's merry way.
Actually in your example the data will be the XMLHttpRequest request object.
var x;
$.get( 'output.csv', function(data){
x = data;
console.log(x); // will give you the contents.
});
I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.
jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.
I tried many, many, many different methods, but in the end, the answer I needed was at this stackoverflow page: JQuery - Storing ajax response into global variable
Thanks to contributor Charles Guilbert, I am able to get data into my variables, even when my page first loads.
Here's an example of the working script:
jQuery.extend
(
{
getValues: function(url)
{
var result = null;
$.ajax(
{
url: url,
type: 'get',
dataType: 'html',
async: false,
cache: false,
success: function(data)
{
result = data;
}
});
return result;
}
}
);
// Option List 1, when "Cats" is selected elsewhere
optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");
// Option List 1, when "Dogs" is selected elsewhere
optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");
// Option List 2, when "Cats" is selected elsewhere
optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");
// Option List 2, when "Dogs" is selected elsewhere
optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");
You just need to specify the callback function in the parameter to get method. Your data will be in the variable you specify in the function.
$.get("output.csv", function(data) {
// Put your function code here, the 'data' variable will hold your data.
});