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.
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
});
});
So, I have this problem. I am using a plugin named jRating, it is esentially a rating system in jquery. My problem is, that onClick, the ajax request fires twice.
After searching a lot, I tried those things:
I checked and double checked that the $(document).ready(function(){} and the jQuery shortcut $(function() {}); is not twice in the page.
I also checked that the id of the call is unique.
So, here is my code:
jQuery:
$("#rating").jRating({
step:true,
length : 5,
canRateAgain : true,
nbRates : 3,
onClick : function(element,rate) {
var data = (rate, 1);
$.ajax({
url: 'application/index/rate',
type: 'POST',
dataType: 'x-www-form-urlencoded',
async:false,
contentType: 'application/x-www-form-urlencoded',
data: rate,
success: function () {
console.log('SUBMIT WORKS');
},
error: function () {
console.log('There is error while submit');
}
});
}
});
pHTML:
<div id="rating" data-average="<?=$average //note that this is working everytime!?>" data-id="1"></div>
Thanks for any inputs!
EDIT: JsFiddle: http://jsfiddle.net/Je79U/ ;
To recreate the problem, click run, then go to console/network, clear all contents, then click anywhere on the yellow/orange bar, to rate, and see what happens. Thanks again for your time!
with reference of http://demos.myjqueryplugins.com/jrating/ , already jRating will work as ajax. So, that it takes ajax running twice
Please check their demo website clearly.
In that once you rate it will update the records to http://demos.myjqueryplugins.com/jrating/php/jRating.php
and use the following version of jRating
https://github.com/alpixel/jRating
I have a button click event that initiates an ajax call, and I need the ajax call to be synchronous so I set async:false. I want to provide feedback to the user so they know that the ajax call is happening in the back. So I have the following:
$('#ajaxBtn').on("click",function() {
$('#ajaxBtn').html("processing ...");
$.ajax({
type: "Get",
url: "example.php?data=test",
async: false,
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
})
}
On Chrome (haven't tested on other browsers) When I click the button, everything freezes while the ajax call completes, however the text on the button doesn't update until the success alert pops up. If I step through the code in the debugger it works as I would expect. The text on the button changes before the ajax call initiates.
If I set Async: true it also seems to work as expected. The text changes immediately and then I get to the success function.
Is Chrome reordering the ajax call to happen before the changing of the text? Why am I seeing this?
What about something like this.
$('#ajaxBtn').on("click",function() {
$.ajax({
type: "Get",
url: "example.php?data=test",
//note that I have removed the async: "false",
beforeSend:function(){
$('#ajaxBtn').html("processing ...");
},
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
}).done(function(data){
//submit your form here depending on which data is returned
});
}
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);
});
});
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>