Chrome jquery ajax callback on success not firing - ajax

As far as I know, $.ajax has always worked pretty smoothly in every browser until now.
I have a pretty simple function, called when a couple of actions from the user occur.
In Firefox, everything runs smoothly. But in Chrome, while the $.ajax request is launched, the callback on success doesn't fire.
Here's the actual snippet:
var form = $("#templateCreator"),
formType = form.attr("method"),
formData = form.serialize(),
action = form.attr('action');
$.ajax({
type: formType,
url: action,
data: formData,
success: function(){
console.log('Can\'t see me in Chrome, but ok in firefox !')
// Handle all form submit events to form validator first
validator(form, targetInput);
}
});
What's puzzling is nothing seems wrong, data is serialized, and sent properly. Does anyone know what I missed?

Start by adding an error and complete method as #Jasper suggested.
$.ajax({
type: formType,
url: action,
data: formData,
success: function(){
console.log('Can\'t see me in Chrome, but ok in firefox !')
// Handle all form submit events to form validator first
validator(form, targetInput);
},
error: function() {
console.log($.makeArray(arguments));
},
complete: function() {
console.log($.makeArray(arguments));
}
});
Then you can:
open Chrome debugger (F12), go to the scripts tag, and put a breakpoint inside success/complete/error; check out the stack trace and values for an epiphany ;)
have a look at the console logs
For great joy, take off every Zig!

I had this issue, and set async: false. This works for me in Chrome. Looks like Chrome has an issue with async: true.
restget = function(url, cb){
$.ajax({
url: url,
dataType: 'json',
crossDomain: true,
async: false,
success: cb
});

Try this .....
data: formData,
async: false,
Chrome has some issues with async calls.

I had a similar problem while trying to get a json array. I had to add dataType: 'json' to my ajax so that non-Firefox browsers know what my data type is. For instance:
$.ajax({
type: 'Get',
url: "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo",
success: function(data){
var jsonArray = jQuery.parseJSON(data);
alert(jsonArray.status.message);
}
});
and
$.ajax({
type: 'Get',
url: "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo",
dataType: 'json',
success: function(data){
var jsonArray = data;
alert(jsonArray.status.message);
}
});
will display the same thing when ran in Firefox firebug. But when you run this in Chrome DevTools it will only work on the bottom one. I hope this fixes your problem.

Related

Error in ajax retrieving data

I wanted to retrieve data using ajax, when open the url in browser it showing data but when i execute this url in ajax code error msg function is running however data is showing in browser.
url: "http://live.nayatel.com/?json=1"
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://live.nayatel.com/?json=1",
cache: false,
success: onSuccess,
error: onError
});
});
its a wordpress site and i used a plugin to retrive its data working in browser but not giving response text.
I have two suggestions, since I am not that sure about your problem.
a) Try changing
success: onSuccess,
to
success: function(data, status) {
onSuccess(data, status);
},
b) If that fails, try adding
crossDomain: true,

Linking AJAX with PHP code. Do i need to write it again?

I have a real problem. I have a php code and a form where when the form is submitted a POST request is sent and the page reloads again and ofcourse the post is viwed in the page.But i want to work with AJAX in order page not to be refreshed.I know the basics of AJAX but i don't want to build all the project from the beggining.Is there a way in success function of AJAX to link to my php code??
$.ajax({
type: "POST",
url: "index.php",
datatype: "html",
data: dataString,
success: function(data) {
//How can i link here to start running my php code which is located in the same page.
}
});
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
// try this
console.log(data);
// see what 'data' actually is
}
});
then check in the browser by hitting F12 to look at the console.
also are you sure you want datatype of html ? you probably want a data type of json or XML , what is the server returning to you after the ajax post?
You have to cancel the form's submission so that the ajax request will take place, otherwise it is canceled. Also use .serialize to get a name-value pair string of the form data to use in the ajax call.
Html
<form id="MyForm">
<button id="MyButtonId">Submit</button>
</form>
JS
$("#MyForm").submit(function(e){
//Prevents the form from being submitted
e.preventDefault();
$.ajax({
type: "POST",
data: $("#MyForm").serialize(),
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
});

JQuery Ajax call often not working on Safari 6

My Ajax call is really simple as below:
function ajax(reqUrl, params , callback) {
console.log("Request URL "+reqUrl);
var cond;
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
error:function(){ alert("some error occurred") },
success: callback
});
console.log("Server response "+cond.readyState);
}
// Call it as
var url = "/getResult";
var params = {};
params.param1 = "test1";
params.param2 = "test2";
ajax(url, params, function(returnCallback) {
console.log(returnCallback);
alert("Success");
});
That works fine in most cases. But sometimes (about 1 times in 3) it doesn't return anything to callback.
I found many questions and answers for Not working ajax in Safari but fine in chrome and FireFox. My problem is different from them, because it's fine most of the time (I don't mean it was not fine usually because when I refresh my browser, that may cause my ajax call to work).
My main question is why does my ajax call sometimes fail? I don't get any errors on my JS console. When this situation, I refresh my browser to get my ajax call to. Any Ideas?
Update:
I found that sometimes my ajax call method didn't call out because console.log("Request URL "+reqUrl); did not execute. When I don't want to refresh my browser, I clicked many times on my page's link to produce result. will something late to execute?
Finally, I found error .. Safari doesn't reload my JavaScript files again even disable Cache. So I put all of my JS code into:
$(document).ready(function(){
// start load my js functions
init();
});
to reload my JS files when my page was ready. Cheer !
I also met this problem.
When I moved all code into $(function() {}), it worked.
After that, I found I had defined a variable named key, which caused the problem.
Just rename it, all things will be running.
This seems to be a Safari issue. In this post there is a suggestion to add a beforeSend to your ajax-request.
In your case:
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
beforeSend: function (event, files, index, xhr, handler, callBack) {
$.ajax({
async: false,
url: 'closeconnection.php' // add path
});
},
error:function(){ alert("some error occurred") },
success: callback
});
Please Test below Code. it is working fine.
$.ajax({
type: "POST",
url:'#Url.Action("getResult","Controller")',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.toString());
});
This is use for MVC application.
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
For Asp.net Application :
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
if u have still the issue than please post ur complete code here. i will test and reply soon

codeigniter ajax internet explorer

the following code works fine in FF, opera and chrome but fails in IE
function get_modelo(modelo) {
var selState = modelo;
alert (selState);
console.log(selState);
$.ajax({
url: "site/ajax_call", //The url where the server req would we made.
async: false,
type: "POST", //The type which you want to use: GET/POST
data: "state="+selState, //The variables which are going.
dataType: "HTML", //Return data type (what we expect).
//This is the function which will be called if ajax call is successful.
success: function(data) {
//data is the html of the page where the request is made.
$('#city').html(data);
}
})
}
Can't understand the problem.
console.log in IE doesn't work or causes problems.
See here:
What happened to console.log in IE8?
and here:
Testing for console.log statements in IE
and here:
http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
or just google search IE console log
Everything else in your code looks like it would work fine.
Try this. Below will work in IE8 :P
$.ajax({
url: "site/ajax_call", //The url where the server req would we made.
async: false,
type: "POST", //The type which you want to use: GET/POST
data: { state: selState }, //The variables which are going.
dataType: "html", //Return data type (what we expect).
//This is the function which will be called if ajax call is successful.
success: function(data) {
var newDiv = $('<div></div>');
newDiv.html(data);
newDiv.appendTo("#city");
}
});

How do I use data passed back in the response from ajax jQuery?

I am trying to use the response from a jQuery ajax request to set the innerHTML of a div with a certain id. This is the code I am using:
$(".show_comments").click(function(){
var articleName = $(this).closest("article").find(".articlename").attr('id')
$.ajax({
url: "commentView.php",
data: { 'articleName': articleName },
cache: false,
dataType: "html", // so that it will auto parse it as html
success: function(response){
$(this).closest("article").find(".comments").html(response);
}
});
however it doesn't seem to be doing anything at all, I've tried googling around, but everything I can find says to do it the way I am doing it... I have tested in Firebug and the ajax request is giving me the exact response I want it too... But I just cant access this to set the innerHTML of the div to the response!
In your ajax success handler there is another scope and this points to not what you think. So change your code to:
var articleName = $(this).closest("article").find(".articlename").attr('id'),
that = this;
$.ajax({
url: "commentView.php",
data: { 'articleName': articleName },
cache: false,
dataType: "html", // so that it will auto parse it as html
success: function(response){
$(that).closest("article").find(".comments").html(response);
}
});
What I've changed: I added that variable that points to this instance and use it in the success handler instead.
How would you debug it yourself: if you tried to output console.log(this) and console.log($(this).closest("article").find(".comments")); you would see that it returns a wrong object (in first case) and nothing in second.

Resources