JQuery AJAX url call - sometimes don't work - javascript

I use JEasyUI framework in a page, and I have a form that calls an URL on submit which does some DB work.
Here is the function calling URL (which is defined in another function earlier in the code):
function saveClientItem() {
console.log("Save Client Item, url:" + url);
$('#formClientItem').form('submit', {
url: url,
onSubmit: function() {
return $(this).form('validate');
return false;
},
success: function(result) {
console.log("Success saving client item with url:" + url);
$('#windowClientItem').dialog('close');
$('#tableClientsList').datagrid('reload');
}
});
};
On some computers the page works fine, but on other computers it sporadically calls the URL, but always returns "success". Here is an excerpt from the Chrome console and network log on the computer where it works as it should:
I marked the "clients.php" which is called to do the DB work.
Here is an excerpt from the Chrome console and network log on the computer where it doesn't work as expected:
I have tried clearing the cache on the second computer, refreshing with Ctrl+F5, after that the page works a few times, and then back to not calling the URL. So far I tried on 4 computers with various results, 50-50 works-fails.
I need a hint on what to check with the computers where it doesn't work, or maybe another fail-proof way of submitting the form to a PHP page.
I added "error" event to function,
error: function(result) {
console.log("error saving client item with url:" + url);
}
...and what puzzles me is that "success" is always called. I realise that something is preventing URL to be called (guessing some network issue), but shouldn't "error" event be raised?

After trying:
Changing jEasyUI version from 1.9.7 to 1.4.2
Changing jQuery versin from 1.13.1 to 3.5.1
...with the same problem occurring every time (even after emptying cache and all browser data), I tried putting the function in a loop and called it up to 100 times with some random values to be posted, and the "clients.php" file was called randomly: sometimes after 1 try, sometimes after 17 tries, sometimes it was never called.
I ended up modifying my function to look like this:
function saveClientItem() {
$('#formClientItem').form('submit', {
url: url,
onSubmit: function() {
$.ajax({
type: 'POST',
url: url,
data: $(this).serialize()
})
.done(function(data) {
console.log("Posting success:" + data);
$('#windowClientItem').dialog('close');
$('#tableClientsList').datagrid('reload');
})
.fail(function() {
console.log("Posting failed.");
});
// prevent refreshing the page
return false;
}
});
};
Put in a loop of 100 consequent submits it submits every time (tested about 10 times so far), whereas the old function is still quirky.
I hope this helps someone.

Related

Why Ajax is not able to send array data?

Trying to send form data to a PHP page, all parameters are sending successfully except data:imagesBase64
this imagesBase64 is an array which I am trying to send, a few hours ago everything was fine but now it is not working I really don't know why.
All values are Posting successfully only this value is not posting also I am not able to see error in console because it redirected to URL where I am posting the data
var imagesBase64 = ['abcdfd','dhydsu333ud','djhbsd'];
$(function () {
var frm = $("#saveform");
frm.submit(function (ev) {
$.ajax({
type: frm.attr("method"),
url: frm.attr("action"),
data: {
data: imagesBase64,
PubId: $("#Publications").val(),
sdate: $("#datepicker").val(),
pnumber: $("#pnumber").val()
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
alert("New message received");
},
});
ev.preventDefault();
});
});
In PHP page -
print_r($_POST['data']);
it gives an error undefined data, though when I tried with postman everything is working fine.
also I am not able to see error in console because it redirected to URL where I am posting the data
That's the problem.
You are submitting data to the server using a regular form submission and not with Ajax. Since your Ajax code isn't used, the data added in from outside the form isn't included.
This is usually caused by the regular form submission interrupting the Ajax request, but since you have ev.preventDefault(); that shouldn't be the case here.
Possible reasons that might apply are:
var frm = $("#saveform") fails to find the form because the selector is wrong or the form is added after the document is loaded with other JS
You don't have jQuery loaded so the call to $ fails
You have jQuery Slim loaded which doesn't include an ajax method (moving the call to preventDefault so it is before the call to ajax would help catch this).
Your browser's developer tools should have an called something like "Persist Logs" which will prevent it from clearing the console when you navigate to a new page. Turn it on to aid your debugging. Here's what it looks like in Firefox:

Ajax request within partial view loaded through another Ajax request does not work properly in IE 11

Following is the exact scenario in my ASP.NET MVC application:
The parent page is having 3 tabs, and following javascript is written to bind click event to each of the tabs:
Each function invokes a controller action (specified in the data-url attribute), and renders the result in the partial view which is expected to be displayed within "ContactMainContainer" div.
jQuery(document).ready(function () {
$('#ContactTabs a').on('click', function () {
var dr = $(this).closest('li');
var url = $(this).attr("data-url");
if (url != undefined && url != '') {
var projectDetailTabModel = $("#ContactID").val();
$('#successDiv').hide();
$('#errorDiv').hide();
$.ajax({
type: "POST",
url: getUrlWithTabId(url),
data: projectDetailTabModel,
success: function (result) {
$('#ContactMainContainer').html(result);
},
error: function (errMessage) {
if (errMessage != null && errMessage.length > 0) {
$("#errorDiv").show();
$("#errorText").html(errMessage);
}
}
});
}
});
});
Contents of one of the partial view is built using javascripts (mostly ajax calls). (I am unable to put the whole javascript here as it is a client project and confidentiality agreement, and the javascript library is too large to place here).
The issue is that when a user navigates to that particular tab (having Ajax call), it takes a long time to execute and render the result. But after that if user clicks on any other tab the browser stucks and hangs for infinitely.
This issue is only in IE11, and works very well in all other browsers (Chrome, firefox, and all).
Could anyone please suggest what could be the reason?
It's a caching issue and IE is well known for caching. You need to make sure in your Ajax call to set the catching as false
Setting the cache property in an AJAX call
$.ajax(url, {
dataType: 'json',
cache : false,
//Other things ...
}
I prefer to use cache buster in the request URL, that is adding the current timestamp as parameter, so that it cant be cached

Signalr polling issue with Internet Explorer 9 and ForeverFrames

I use Signalr to show real time updates of long processes happening on the server.
The idea is that the user can see how many items have been processed out of a set amount.
An AJAX post request sends the call to the server to start the process through a controller, at the end of this a partial view is returned and the container element is populated with this result.
$("body").on("click", "#process-button", function ()
{
var hub = $.connection.myHub;
$.connection.hub.start().done(function ()
{
connectionId = $.connection.hub.id;
$.ajax({
type: "POST",
url: "StartProcess/MyController"+ "&connectionId=" + connectionId,
cache: false,
success: function (data) {
$(".modal #container").empty();
$(".modal #container").html(data);
}
})
});
hub.client.sendMessage = function (message) {
$(".modal #container").empty();
$(".modal #container").append(message);
}
});
I cant show the controller ActionResult method for legal reasons but im 100% sure the problem is in the above code. I just cant figure out why.
Ive tested this in Chrome, Firefox, IE10,11 and edge all fine (presumably cos they use websockets) but on IE9 which is using ForeverFrames the process is stalling.
Its worth noting that I tested IE9 using the document mode emulator through IE11.
Here is the output from the network trace.
Excuse the blacked out entries, trying not to broadcast the code.
As you can i have highlighted where the request simply stalls and to my knowledge the partial view is not returned because of this.
Anyone encountered this before?
You can try adding
$.connection.hub.start({ transport: ['webSockets', 'serverSentEvents', 'longPolling'] });
To your script to disallow the use of ForeverFrames.

Ajax Post getting cancelled in onclick attribute

I've seen duplicates of this question, however no solution seems to work for me. I'm trying to trigger an AJAX request based off of a link (the following). I'm writing in MVC 4. The AJAX request seems to go through well, I have a breakpoint getting hit on the other side, however the request gets cancelled by the browser. I can see this cancellation in Firebug, Chrome, etc. I found some suggestions that I need to return false at the end of the onclick handler to prevent other code from cancelling my event, however it doesn't seem to work. Are there additional quirks in the onclick handler that kill any outstanding AJAX requests? How would I stop that behavior?
Employees
function navClick(target) {
var serviceURL = '/Consequence/'+target;
try {
var dealerID = "5";
$.ajax({
url: '/Consequence/test',
data: { dealerID: dealerID },
type: 'POST',
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
} catch (err) {
alert("exception");
}
return false;
};
try adding a class to the link and trigger the click event off of that
Employees
then in your script
$('.linkEmployees').on('click', function(){
//your ajax call here
});

Unexpected JavaScript Actions reported by my Users

My users keep complaining that a link does not show up for them. For me, I have tested this on several browsers and it works for me.
What should happen is that a process is started via AJAX using JQuery and once that is done I keep checking with the server via AJAX how much of the process has been done and once the process is complete I show them a link. But a lot of users tell me that it shows them the link and it quickly disappears back to showing 100.0%!
I can't see how I can fix this and I was hoping you guys could help me write something fool proof so that the link is always shown!
Here is the code concerned (its been shortened).
var startTime;
var continueTime;
var done = false;
function convertNow(validURL){
startTime = setTimeout('getStatus();', 6000);
$.ajax({
type: "GET",
url: "main.php",
data: 'url=' + validURL + '&filename=' + fileNameTxt,
success: function(msg){
done = true;
$("#loading").hide("slow");
$("#done").html("LINK SHOWN HERE");
}//function
});//ajax
}//function convertNow
function getStatus()
{
if(done==false){
$.ajax({
type: "POST",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
textFileResponse = respomse.split(" ");
$("#done").html("PROGRESS SHOWN HERE IN PERCENTAGES");
}
});//ajax
continueTime = setTimeout('getStatus();', 3000);
}
}
Thanks all
P.S. I have this question before and was given an idea of using a conditional in the function but that didn't work when it should have!!
UPDATE
I have some of my users what OS and browsers they are using and they usually say a Mac Os and firefox or safari. Not sure if that help with the solution.
The behaviour described by the users suggests that the success callback of your getStatus function is called after the one in convertNow. You should test done variable in this callback
function getStatus(){
if(done==false){
$.ajax({
type: "POST",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
// FIX : Already done, just ignore this callback
if (done) return;
textFileResponse = respomse.split(" ");
$("#done").html("PROGRESS SHOWN HERE IN PERCENTAGES");
// BONUS : call getStatus only when previous ajax call is finished
continueTime = setTimeout('getStatus();', 3000);
}
});//ajax
}
}
EDIT : This solution should prevent the bug from appearing most of the time, but there is still a chance. The only way to be sure is to remove the callback from convertNow and let the one in getStatus set the link when the processing is done (don't forget to allow only one call to getStatus at a time, see "BONUS" modification above).
If done is never set back to false then the reported behavior would be expected upon the second call to convertNow.
Since the ajax call in convertNow uses GET instead of POST, it is possible that a browser is returning a cached result whenever parameters are identical to a previous call.

Categories

Resources