When my button is clicked,I want to change it's class instantly,but it seems that the ajax call is not letting it to happen.It's happening 3-4 seconds later.Why?I tested with alerts and it's ok.
the button:
$('#myButton').click(function() {
alert("ok");//it will alert instantly
$('#myButton').removeClass().addClass("btn btn-success"); //here, this code is running after 3-4 secs
});
ajax call:
$('button').click(function() {
...some code...
$.ajax({
async: false,
type: 'POST',
dataType: 'json',
url: myUrl,
data: myValue,
success: function(data) {
setTimeout(function() {
img.src = img.src;
}, 10);
}
})
}
Without the ajax call it works
Remove this:
async: false
Adding that makes the asynchronous operation artificially synchronous, blocking everything else from happening in the browser. You're probably even getting a warning about deprecation in your browser's development console.
Never use async: false. Keep asynchronous operations asynchronous.
Related
I have a problem with Google Chrome.
I try to post data from page to my MVC controller with AJAX and sometimes Chrome tries to do GET request after POST.
I saw that it happens in case when try to post data very frequently (push button 5-10 times with minimum delay) or in case when page doing nothing (stay) on the page about after 5-10 minutes.
$.ajax({
url: '#Url.Action("PO_Comparison")',
data: JSON.stringify(parameters),
dataType: 'json',
traditional: true,
contentType: 'application/json',
type: 'POST',
success: function (result) {
compare_with_data = result;
$.when(fillData(result)).done(function () {
EditShow();
ComparingUnloadPopupBox();
});
$("#compare_image_please_wait").hide();
},
error: function (error) {
alert(error.statusText + "! Please reload the page.");
ComparingUnloadPopupBox();
$("#compare_image_please_wait").hide();
}
});
MVC controller part:
public JsonResult PO_Comparison( List<Project_Items> parameters)
{
//Updating my Project_Items
return Json(new{ data:compared_data }, JsonRequestBehavior.DenyGet);
}
Internet explorer and Firefox works fine.
Thanks
I'm trying to use a GET HTTP cal, I got the request to work with the Advanced REST client (Chrome plugin) but cannot get it to work in JQuery.
Following the advice from this thread, I've set up the following:
$(document).ready(function() {
$('.ap1').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });
This is the output I'm trying to get (successfully with REST client)
{
url: "https://api2.panopta.com/v2/monitoring_node/41"
hostname: "phoenix01.monitorengine.com"
ip_address: "65.23.158.149"
name: "Phoenix"
textkey: "na.west.phoenix01"
}
I just want to be able to access the name variable from that JSON and pass it through my function. I wanted to at least get the above code to work before I try to figure out how to create an object so I can successfully call the name, something like .append(object.name)
I just started learning JQuery and this is my first post so sorry if I didn't include enough details.
You can't apply ajax calls to other domains. You can make workaround using server-to-server calls via curl() or file_get_content(url), and then make a js call to your script.
First make php file, which will call the server note that if you want to use file_get_contents you should allow_url_fopen in your php.ini:
myProxy.php
<?
$content = file_get_contents($yourUrl);
// do whatever you want with the content then
// echo the content or echo params via json
?>
your js should make call to your PHP, so you have workaround Same Domain Policy:
$.ajax({
url: 'myProxy.php',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
I am not sure if your api info is correct, but I think the main thing you need to do is change to jsonp instead of json due to the same origin policy that musa mentions.
The following JS fiddle "works" but the request is not authorized at the server: http://jsfiddle.net/cf8S9/.
$(document).ready(function() {
$('#button').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'jsonp',
success: function() { alert('hello!'); },
error: function() { console.log(arguments);alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });
I have many instances of the same type of problem using jQuery. Probably because I am missing some basic knowledge (jQuery newb). In my $.Ajax calls to get data - on the success: I perform many calls to other functions based on the data that gets returned. The calls need to be made in a specific order but this does not seem to happen. If I have a call to another jQuery function that I wrote and then three line later have a call to yet another function (which depends on some events that happen in the first function call) the second call is happening first. Ran this with debugger set many times in two different $.Ajax calls and it happens this way. Am I doing something completely wrong?
BTW - the data is coming in just fine and populating my table and form items. Per request I am posting code below - the comments show that GetInventory needs to execute before BuidlNav
$(document).ready(function () {
$('#searchNow').css('visibility', 'hidden'); //Hide Search Now button
$("#popup").css("display", "none");
$('#submit').prop('disabled', true);
$.ajax({
type: "POST",
url: "mypage.aspx/mywebmethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (states) {
var jsonCodes = JSON.parse(states.d);
for (var i in jsonCodes) {
$("#Select0").append(new Option(jsonCodes[i].regionname, jsonCodes[i].region_id));
}
var first = getUrlVars()["region"];
if (first) {
debugger;
$.fn.SetAllSelectors(reg);
$.fn.GetInventory(1, 10, reg, 'rank', 'asc'); //This should happen first
$.fn.BuildNav(); // This depends on GetInventory having been executed already.
}
else {
var myText = 'United States';
$("#Select0 option").filter(function () {
return $(this).text() == myText;
}).first().prop("selected", true);
$.fn.GetChildRegions("Select0");
}
}
});
}
);
If GetInventory and BuildNav also use ajax, you'll need a structure more like this. When making ajax calls, the data is fetched while not holding up the next command line, so chances are your 2nd or 3rd function is being called before the first finishes.
$.ajax({
type: "POST",
url: "mypage.aspx/mywebmethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (states) {
getInventoryAndBuildNav(states);
},
...
});
function getInventoryAndBuildNav(states){
$.ajax({
....
url: "mypage.aspx/getinventory",
success: function (inventory) {
$.fn.BuildNav();
},
...
});
}
The best way to accomplish this is to build functions for each item and allow a callback method to be passed.
Think of it this way
$.ajax({
type: "POST",
url: "mypage.aspx/mywebmethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (states) {
//This will trigger second since we had to wait for the process to finish
alert('The Ajax call has been made, finished, and the data received');
}
});
//This will trigger FIRST since the ajax call was initiated, but we're still waiting
alert('The Ajax call has been made. We're moving on to the next call.');
I am having trouble figuring out why jQuery Mobile will not handle my json return in an AJAX call. It works perfectly fine in any web browser but not on my mobile phone (android). The script just hangs, it will not even choose either of the if statement options in the success function.
$('#loginSubmit').click(function() {
$.mobile.showPageLoadingMsg();
$.ajax({
type: "POST",
url: "/include/login.php",
data: $('#loginForm').serialize(),
cache: false,
dataType: "json",
success: function (json) {
if(json && json.error != '') {
//alert(json.error);
$.mobile.hidePageLoadingMsg();
} else {
$.mobile.changePage('/mobile/cp/', { transition: "slide" });
$.mobile.hidePageLoadingMsg();
}
}
});
return false;
});
I had this problem once with the new beta, when i enabled ajaxLinks. If i then wanted to add code for elements, that were not on my startpage, i could not use
$(document).ready function.
I used the
$('#page').live('pageshow', function() ...
to add my code at pagechange. So my elements i wanted to add the javascript to were currently rendered.
Hope this helps.
I came across something weird, that I want to expose and know if someone as an explanation for it.
Some time back i had a simple post:
$.post("/Route/Save", { myObj: JSON.stringify(myObj), accessToken: getAccessToken()}, function(data)
{
//do stuff
});
and it was working nicely, now doesn't work, and only the accessToken paramenter is correctly received in the route controller
I changed it to:
$.ajax({
url: "/Route/Save",
data: '{ myObj:' + JSON.stringify(myObj) + ',accessToken:"' + getAccessToken()+'"}',
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (data)
{
//Do stuff
}
});
And now it works. I'm using firefox 4 and IE9 and believe the reason is connected to the way the browser is sending the info encoded... in the $.post() case it looks like it sends the data as application/x-www-form-urlencoded
I'll be glad to hear from you guys!
Regards,
byte_slave
I'm not sure why it was working before; perhaps a jQuery update changed behaviour?
As to your question on the content-type, $.post is a shorthand wrapper around $.ajax, and from the $.ajax api page, the default value for the contentType is 'application/x-www-form-urlencoded'.
AFAIK, you can't specify the contentType using $.post(). I could be wrong though.
The equivalent with $.ajax should be
$.ajax({
url: "/Route/Save",
data: { myObj: JSON.stringify(myObj), accessToken: getAccessToken()},
type: 'POST',
success: function (data)
{
//Do stuff
}
});