Really simple question. I trying to test a Restful webservice that I am developing, and have this simple ajax call (using jquery):
<script type="text/javascript">
$(document).ready(function() {
var url = '/index.php/gettest/reallyLongRequest';
$.ajax({
url: url,
dataType:'text',
success:function(data) { $('#result').html(data);},
error:function(xhr,err,e) { alert ("Error: " + err);}
});
});
</script>
This runs when the page loads. As it's running, the page is blocking; i.e., (I can see the hourglass next to the mouse pointer) no other user actions can be handled. (Btw, this particular get request--intentionally--takes a very long time to return).
Why is this? A(asynchronous)JAX right? Obviously I am making a beginners mistake. Any ideas, please?
When I attempt this using plain javascript (no library) it works as expected. Does this have something to do with Jquery's handling of the xhr onreadystatechange?
Thank you for looking.
EDIT: multiple people have suggested setting async: true, which as it happens, is the default in jquery, and as such has no effect.
EDIT: As previously mentioned, if I use plain javascript and start this with a timer, e.g., window.setInterval(function() { startLongPoll(); }, 5000)
It updates as expected, without appearing to block. Ideas, anyone?
Here is an example of what I did to solve the problem:
jQuery(document).ready(function() {
setTimeout(function () {
$.getJSON("veryLongRequest", function(json) {
alert("JSON Result: " + json[0].id);});
}, 500); // You may need to adjust this to a longer delay.
});
Note: I am using the short-hand jquery method, "getJSON" which is a wrapper for the ajax call with datatype set to "json". However, this solution will work for all ajax requests.
Referenced:
Stop the browser "throbber of doom" while loading comet/server push iframe
I think that this should default to true, but try adding async: true to your ajax json parameter.
Does the code below work as expected?
<script type="text/javascript">
//$(document).ready(function() {
var url = '/index.php/gettest/reallyLongRequest';
$.ajax({
url: url,
dataType:'text',
success:function(data) { $('#result').html(data);},
error:function(xhr,err,e) { alert ("Error: " + err);}
});
//});
</script>
May want to try and Add async:true
<script type="text/javascript">
$(document).ready(function() {
var url = '/index.php/gettest/reallyLongRequest';
$.ajax({
url: url,
async:true,
dataType:'text',
success:function(data) { $('#result').html(data);},
error:function(xhr,err,e) { alert ("Error: " + err);}
});
});
</script>
Related
I've encountered an issue where a jquery ajax post method works on chrome but does not work on safari or firefox. I've looked through all the other similar posts and they don't solve the problem. Whenever I run the ajax code, it just returns the entire HTML of the page the form is found on.
Here's my javascript:
$("#piece-form").submit(function(e)
{
e.preventDefault();
// gets which submit button was clicked
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
var formData = new FormData(this);
$.ajax
(
{
type: "POST",
url: url,
data: formData,
cache: false,
processData: false,
success: function(data)
{
if(data == "Success!")
{
$("#error-box").css("display", "none");
$("#success-box").html("Success! Publishing...");
$("#success-box").css("display", "block");
}
else
{
$("#success-box").css("display", "none");
$("#error-box").html(data);
$("#error-box").css("display", "block");
}
}
}
)
});
No matter the content of the PHP file the function points to, it doesn't work as planned. I've tried making a PHP file with a single echo line and I still run into the same problem. I've implemented an error block in the ajax as well and it returns nothing. I also don't receive an error in the console other than: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/" in Firefox
Edit: I've added contentType:false and it still isn't functioning properly on Firefox and Safari
Have you tried wrap your code in document ready?
Also as much as i know now it is correct to use on():
$( document ).ready(function() {
$("#piece-form").on('submit', function(e){
//your main code here
});
});
For now it does not looks like there would be any issue. ..
I finally found the answer.
The error is in the following line of code:
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
For some reason, Firefox and Safari don't properly get the value of "selectedButton" (although Chrome does) resulting in the url variable being incorrectly set. In order to circumvent this, I did the following:
$(".piece-button").click(function (){
url = $(this).attr("name");
})
I needed the submittedButton method because I had two submit buttons for the form and was trying to find which one was clicked. This alternate method does that and is transferrable across all three browsers I have tested. This may not be an optimal solution to the two button submit issue but it worked for me and now the ajax works without a hitch.
Though you have got the solution but from interest I am sharing mine as I have just encountered same problem and got the workaround by adding event.preventDefault(); after success. Example code is given
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data: {
name: $('#nameInput').val(),
email: $('#emailInput').val()
},
type: 'POST',
url: '/post_for_db',
success: function(data) {
console.log(data)
$("body").html(data);
// This will navigate to your preferred location
document.location = '/render_table_from_db';
},
event.preventDefault(); // solution is this for me
});
});
I use jquery AJAX for web page and use async : false option as following. My client's network is very slow. When I try to load the web page from the server web page is slow and all the controls are freeze. Is that "async:false" matter? here my code
function ajaxRequestWithNoArguments(url) {
return $.ajax({
url: urlForPhp + '/' + url,
data: '',
dataType: 'JSON',
async: false,
method: 'POST'
});
}
When I try to load the web page from the server web page is slow and all the controls are freeze. Is that "async:false" matter?
Yes, this is exactly why you should not use async:false, it's used in very specific cases and sounds like you don't need it. Making the request synchronous means that browser will pause program execution (freeze all UI too) until the request is done, the data is loaded back and processed. You don't wan't it in most cases, that's why you need to use default async: true.
function ajaxRequestWithNoArguments(url) {
return $.ajax({
url: urlForPhp + '/' + url,
data: '',
dataType: 'JSON',
method: 'POST'
});
}
Returning a promise object is convenient way to deal with asynchronous function. In this case you would use ajaxRequestWithNoArguments as follows:
ajaxRequestWithNoArguments('/some/url').then(function(response) {
console.log('Data loaded', response);
});
function OpenAjax(link, form_id)
{
document.getElementById("page-wrapper").innerHTML = "";
$.ajaxSetup({ async: true });
$("#page-wrapper").load(link, function(){
$("#" + form_id).validator();
});
}
This is my code. I had the same issue and setting it to true will fix it. When set it to true another problem may occur. Your javascript code will continue to work and if you have a response text you must tell JQuery to run your code after response, as in my example:
$("#" + form_id).validator();
This code works after response, but if I write my code this way
function OpenAjax(link, form_id)
{
document.getElementById("page-wrapper").innerHTML = "";
$.ajaxSetup({ async: true });
$("#page-wrapper").load(link, function(){
//Code moved from this line
});
//Here
$("#" + form_id).validator();
}
$("#" + form_id).validator(); - code will work before Ajax response
I'm using the tutorial here, that used to work last month, but now it isn't. I've copied the relevant code below.
<script>
(function($) { //In case jQuery no conflict is being used
$(document).ready(function() { //wait for document ready
$("#loaddaold").click(function () {
alert("123");
//$( "#duplicateshere" ).empty();
$.ajax({
type: "GET",
url: "ajax-oldmessages.php",
dataType: "xml",
success: xmlParser
});
});
});
function xmlParser(xml) {
alert("456");
//$("#rev2").slideDown();
$(xml).find("result").each(function () {
$("#appendhere").append('' + $(this).find("title").text() + '<br>');
//$(".book").fadeIn(1000);
});
}
})(jQuery);
// http://www.webdevdoor.com/jquery/javascript-delay-input-field-change/
// http://papermashup.com/parse-xml-with-jquery/
// (not used) http://www.paulund.co.uk/process-each-node-of-xml-in-jquery
</script>
The problem is that the xmlParser() function isn't being called after the successful ajax request. It shows a 123 alert but not a 456 alert. Am I doing something wrong, or is the tutorial wrong?
Previously on the other question I was told it was a CORS issue, but I was calling the file off my computer, and in my example, so what is the problem now?
if youre using
dataType: "xml"
and if you have an invalid xml in youre response then success wont triger
check youre response because its invalid... if you want to test your code just change
dataType: "html"
and you will see your alert(456) that confirms invalid xml data
I've duplicated your issue and by placing in my response a valid xml, code was running fine
Also if youre expected data is just an string that contains an id, try using
dataType: "xml text"
NOTE: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require
I have an ajax query that's working if I call it from onpageload but not if I call it from a button click. Any reason why?
Edit: I've added the events as requested, please be aware I have debugged this and it is getting to the AJAX but just silently skipping it. It will call a failure function if I add one.
function detailsQuery(crn, semester, year, questionId, clickedButton)
{
$.ajax({
url: somebigurlwithnocallback (same domain),
type: "GET",
dataType: "json",
success: function (data) {alert(data)}});
}
-
$(function() {
$(document).delegate(".button", "click", function(){detailsQuery(CRN,Semester,Year,QuestionID, this);});
});
window.onload=(function() {detailsQuery(CRN,Semester,Year,QuestionID, this);});
Did you attempt to check if the click event was even working ? Try this code:
$(".button").live("click", function(){
function detailsQuery(crn, semester, year, questionId, clickedButton)
{
$.ajax({
url: somebigurlwithnocallback (same domain),
type: "GET",
dataType: "json",
success: function (data) {alert(data)}
});
});
});
This appears to be an issue with Google Chrome. If an HTML file is modified and only refreshed (even with ctrl+f5) Chrome does not always process the modified AJAX call properly. I don't have access to server side code so I can't see what's going on there, being a 'GET' not much can be going on. I can only see that it returns 'error'. Closing chrome and re-opening resolves the issue. Why it only happens when the AJAX occurs on a button click is beyond me.
Do this:
Change
$(function() {
$(document).delegate(".button", "click", function(){detailsQuery(CRN,Semester,Year,QuestionID, this);});
});
to
$(document).ready(function(){
$(".button").bind({"click": function(){
function(){detailsQuery(CRN,Semester,Year,QuestionID, this);}
}
});
});
That should resolve the issue.
Hope the explanation is clear and this helps.
I want to show the user a "loader" before and during the ajax call. Here's the code (simplified version...)
$(document).ready(function() {
$("#btn").click(function(){
$("#log").html("loading ajax call...");
anotherFunc();
});
});
function anotherFunc(){
$.ajax({
type: "GET",
url: correct_url,
data: data_to_send,
dataType: "jsonp",
success: function(data){
$("#log").html("new html");
}
})
}
the problem is that "loading ajax call..." never appears. I only see "new html" displayed. the singles ajax #log modification call work perfectly alone (without the other)
is there another way to do?
what am I doing wrong?
ps. I also tryed to write in another id (#log2) with the same result.
Most likely everything works just fine, but the AJAX call returns very quickly (especially if you are testing locally). To see if that is the case, just do the following:
$(document).ready(function() {
$("#btn").click(function(){
$("#log").html("loading ajax call...");
setTimeout(function(){anotherFunc();},2000);
});
});