I know questions about loading XML into a JS variable have been posted here many times, but I didn't find a solution that would work. In my script I declare a variable before an ajax request, and then add the result to the variable. This works only if I add alert to the script:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
myDB = xml;
}
});
alert(myDB); //returns: undefined
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
alert(question);
});
The above code works only with the alert. When I delete the alert, the code doesn't work. How can I make this work without the alert?
You need to add your code to success handler for doing that:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
});
}
});
An ajax request is asynchronous. That means, the function you gave in the success option is excuted somwhen later.
After you've started the request, you're variable is still empty. Only if you wait long enough to confirm the blocking alert, the variable will have been loaded.
You will need to add the iteration to the success function, where the xml data is certainly available.
Related
My question regards the $.ajax() jQuery method. I can't get the success parameter in $.ajax() to work.
This works:
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json',
success: window.alert("inside aJax statement")
});
This does not:
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json',
success: function(){
window.alert("inside aJax statement");
}
});
In the first case, I get a JavaScript alert window that lets me know the $.ajax() I called is working. All that is changed in the second block of code is I put the window.alert() inside a function() { window.alert(); }.
The point of this is to verify that the $.ajax is running so I can put some actual useful code in the function(){} when the $.ajax runs successfully.
In your second example nothing will happen unless you get a successful call back from the server. Add an error callback as many here have suggested to see that indeed the ajax request is working but the server is not currently sending a valid response.
$.ajax({
type: "POST",
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType:"json",
success: function(response){
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
helpful Link in tracking down errors.
Your first example does nothing whatsoever to prove that the ajax call has worked. All it does is prove that the ajax function was reached, because the values of the properties in the anonymous object you're passing into the ajax function are evaluated before the function is called.
Your first example is basically the same as this:
// THIS IS NOT A CORRECTION, IT'S AN ILLUSTRATION OF WHY THE FIRST EXAMPLE
// FROM THE OP IS WRONG
var alertResult = window.alert("inside aJax statement");
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent=" + $('#wClient').val(),
dataType: 'json',
success: alertResult
})
E.g., first the alert is called and displayed, then the ajax call occurs with success referencing the return value from alert (which is probably undefined).
Your second example is correct. If you're not seeing the alert in your second example, it means that the ajax call is not completing successfully. Add an error callback to see why.
In first case window.alert is executed immidiatly when you run $.ajax
In second it run only when you receive answer from server, so I suspect that something wrong in you ajax request
You may want to try and use a promise:
var promise = $.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json'
});
promise.fail( function() {
window.alert("Fail!");
});
promise.done( function() {
window.alert("Success!");
});
What this does is saves the ajax call to a variable, and then assigns additional functionality for each of the return states. Make sure that the data type you are returning is actually json, though, or you may see strange behavior!
Note that js is single-threaded; the reason your first example works is because it actually executes the code next 'success' and stores the result. In this case there is nothing to store; it just pops an alert window. That means that the ajax call is leaving the client after the alert is fired: use the developer tools on Chrome or equivalent to see this.
By putting a function there, you assign it to do something when the ajax call returns much later in the thread (or, more precisely, in a new thread started when the response comes back).
I think that you do it right, but your request does not succeeds. Try add also error handler:
error: function(){alert("Error");};
I guess that dataType does not match or something like that.
It is 100% your second example is correct. Why it does nothing? Maybe because there is no success in the ajax call.
Add "error" handler and check waht does your ajax call return with the browsers' developer tool -> Network -> XHR . This really helps in handling of broken / incorrect ajax requests
We need to load a given function on page load. Then, we should repeat that function execution, each time a given button is clicked. How can we do that?
Here's the code:
$(function showMember() {
$.ajax({ //Perform an asynchronous HTTP (Ajax) request.
success: function(html){
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>', //A string containing the URL to which the request is sent.
data: {index:$('#members div>h3').size()},
cache: false, //if false, it will force requested pages not to be cached by the browser.
dataType: 'html' //The type of data that you're expecting back from the server.
});
});
$('.addMember').click(showMember);
showMember doesn't trigger uppon click.
Can anyone please explain with detail, why is that ?
that is because your created function is in limited scope $(function ..)....
you can simply do
$(function(){ //document.ready function
showMember(); //call showmember when document is ready
$('.addMember').click(showMember); //call same function when clicked
});
function showMember() {
$.ajax({ //Perform an asynchronous HTTP (Ajax) request.
success: function(html){
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>', //A string containing the URL to which the request is sent.
data: {index:$('#members div>h3').size()},
cache: false, //if false, it will force requested pages not to be cached by the browser.
dataType: 'html' //The type of data that you're expecting back from the server.
});
}
As an addendum to bipen's answer: the reason your code does not work is because you don't seem to get what $ is.
Since you have tagged your question with jQuery, I assume that you are using it. When you include the jQuery library in your code it gives you a function called jQuery. This function is aliased as $. That is, $ is the same as jQuery.
When you call a function in javascript you can pass in arguments:
parseInt('1234');
At the top of your code you are calling $, and passing a function definition as an argument. So
$(function showMember()...
is the same as
jQuery(function showMember()...
That is syntactically correct, but limits the scope of the function to the list of arguments you have passed to the $ function. Once that call is complete the function showMember will no longer exist.
This is why you code does not work.
Here are few points:-
You don't need to call $(function showMember() like this.
You need to call it like function showMember() simply.
Also, you need to call the click function inside the DOM ready method.
Just to make sure that your click event is fired when the DOM is fully loaded, as follows:
$(document).ready(function () {
$('.addMember').click(showMember);
});
OR
$(function () {
$('.addMember').click(showMember);
});
When you pass custom function inside event handler (i.e click, change etc ) then you need to create function as normal, You do not need wrap function within $();
And also do not forget to wrap code inside $(document).ready();
function showMember()
{
$.ajax(
{
success: function(html)
{
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>',
data: {index:$('#members div>h3').size()},
cache: false,
dataType: 'html'
});
}
$(document).ready(function(){
$('.addMember').click(showMember);
});
You need to use ready function when using jQuery
$(document).ready(function(){
$('.addMember').click({});
});
Try this:
$('.addMember').click(function(){
showMember();
});
function showMember(){
$.ajax({ //Perform an asynchronous HTTP (Ajax) request.
success: function(html){
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>', //A string containing the URL to which the request is sent.
data: {index:$('#members div>h3').size()},
cache: false, //if false, it will force requested pages not to be cached by the browser.
dataType: 'html' //The type of data that you're expecting back from the server.
});
}
you may have this lement bind dynamically,
so I think you need to bind it after all binding is complete :
$('.addMember').live('click', function(){
showMember(); return false;
});
This is my first time posting on this site. I have looked over several of the previous postings related to this topic, but did not find anything that works for me. I am trying to use javascript and jquery $.ajax to call a php script on the server and return the contents of the file. Thus far I am not getting any data back. I am able to update the .txt file on the server using the $.ajax, but could use some help in finding out what I am doing wrong to retrieve it. I do not see any errors being generated from the php script and the events.txt file is not blank. vb.net and c# are my native languages so this is a bit foreign to me.
My js is:
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'get',
dataType: 'text',
success: function (data) {
result = data;
alert(result);
},
async: false
});
}
and my readdata.php script is:
<?
$file=fopen("events.txt","r");
$read=fread($file,filesize("events.txt"));
fclose($file);
echo $read;
?>
Any advise is welcome. Thanks!
The type in $.ajax should be in capitals
type: 'GET'
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'GET',
dataType: 'text',
success: function (data) {
result = data;
console.info(result);
},
async: false
});
}
After adding the error: function(){} to the ajax call, I was able to work through this issue.
It turned out that part of the issue was permissions on the server (not able to read from file in the file permissions on the server).
Also I was trying to run locally and I did not have php installed on my local machine.
Basically I have this code. I am trying to simply update a div but the first innerHTML call either does not work or never renders in the browser.
The second one does work though which appends "Complete" once the ajax call is complete. I'm sure it has something to do with the ajax call but I don't see why this is happening because in Firefox there is no issue. Does anyone know what is wrong or if there is a bug in firefox or something? Why would IE even be waiting to render the innerHTML call. Shouldn't the div be updated right after the call or does IE explorer wait a bit?
document.getElementById("status").innerHTML = '<div>Loading</div>';
$jQuery.ajax({
type: "POST",
url: urlValue,
data: parameters,
cache: false,
async: false,
dataType: "json"
});
document.getElementById("status").innerHTML = '<div>Complete</div>';
Why not just do it asynchronously?
var status = $('#status');
status.html('<div>Loading</div>');
jQuery.ajax({
type: "POST",
url: urlValue,
data: parameters,
cache: false,
dataType: "json",
success: function() {
status.html('<div>Complete</div>');
}
});
try to execute those code on load complete.
Possibly in moment when
document.getElementById("status").innerHTML = '<div>Loading</div>';
executed DOM is not ready for accessing it.
On DOM ready - putting "Loading Value"
Making ajax request ("loading is displayed till it will ends")
Once it will ends, setting "Complete"
Anyway till DOM is ready you can not change it. Except document.write, but it's little bit another story.
Probably that will help
setTimeout(function(){document.getElementById("status").innerHTML = '<div>Loading</div>';},0);
ajax post request ...
I have a set of text files representing a table of data from a third party that I'd like to download using a JavaScript application. They look something like this:
col1 col2 .. coln
vala valb .. valz
valA valB .. valZ
etc..
I've been trying to use jQuery to do this. I've been able to use $.load, but I don't want to store the data in the DOM, instead I'd like to parse it out into an object. Whenever I try to use an of the ajaxy methods I'm getting an error I don't understand. For example:
var myData;
$.ajax({
type: 'GET',
url: $(this).attr('source'),
dataType: 'html',
success: function(data) {
myData = data;
}
});
alert(myData);
Gives me an undefined value for myData. Any suggestions would be appreciated.
For that code to work the event needs to be syncrounus, in other word, set async: false in the $.ajax-call. The problem comes because ajax is normally async, meaning that when you do the alert, the request might, or might not have finished. Normally though, it won't cause it takes longer time to fetch a page than to do a function-call. So, by setting async: false, you tell jquery (and the ajax-handler) to wait till the page is finished loaded before you try to alert the data. Another method to achieve the same effect is to do something like this:
var myData;
function fin(data) {
myData = data;
alert(myData);
}
$.ajax({
type: 'GET',
url: $(this).attr('source'),
dataType: 'html',
success: fin
});
This approach is probably better than to set async to false, because it won't make the browser hang while waiting for the page your loading. However, asynchronous programming is not something that is easy to learn, therefore many will find it easier to use async: false.