AJAX jQuery Freezing IE/Safari - javascript

At my wits end here.
Im running this script
<script type="text/javascript" charset="utf-8">
jQuery(window).ready(function(){
//alert('running');
var sold = false;
var leads = [
["one", 120],
["two", 0]
];
jQuery.each(leads, function(index, value) {
var _data = "";
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?lead=" + value[0],
dataType: "json",
//contentType: "application/json; charset=utf-8",
timeout: value[1] * 1000, //Yes i need to wait 120 seconds for "one"
async: false,
cache: false
}).success(function(data) {
_data = data;
console.log(data.status + " Lead: "+ value[0]);
if (data.status == "sold") {
sold = true;
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?resetSession",
dataType: "json",
//contentType: "application/json; charset=utf-8",
async: false,
cache: false
}).success(function() {
//Silence is golden.
});
window.location.href = data.link;
}
}).error(function(jqXHR, textStatus){
console.log("ERROR: " + textStatus + " Lead: " + value[0]);
});
if (_data.status == "sold") {
return false;
}
});
if (!sold) {
//If we get here, None of the leads were sold.
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?resetSession",
//contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false
}).success(function(data) {
//Silence is golden.
});
window.location.href = '/thank-you.php';
}
});
</script>
The script takes some info submits it to submit_lead.php which will return a json response with a status, a message and a link. Once it has this link it needs to call the same script with ?resetSession and the redirect the user to the link received.
I have a sync turned off because I need to wait until I get a response from "one" before trying "two", because if I receive a link there's no point trying the next one.
When the script runs on FF or Chrome, it runs fine. There is a little animation that plays while the requests are going through and once a link is returned it redirects accordingly.
When the script runs in <= IE8 or Safari, the page sorta loads half then waits (The animation loads but does not animate.). Once the ajax response has returned the page suddenly springs to life and then you get redirected.
I have tried window ready and document ready and nothing seems to work.
Any suggestions would be appreciated.
Thanks for reading.

Like i said in the comments, turn async back on.
Add your redirect or whatever operations you want to perform in the callback from the ajax function. Thats most likely the reason you are getting locking.

Related

Lock state multiple ajax calls

I have multiple rich text editors on single page.
There is autosaving of both done by ajax calls that are separate.
Each text editor is saved on focus lost or when focus is inside of editor every 20 seconds.
When editor is not saved and user navigates away I am showing "navigate away warning".
Now I need to manage warning that when one editor is in the middle of saving and the other one finishes earlier warning will not be removed.
What I have now:
editorOneIsSaving=true;
SetNavigateAwayNotification();
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorOne",
data: mypostdata1,
success: function (msg) {
editorOneIsSaving = false;
if (!editorTwoIsSaving) {
RemoveNavigatingAwayNotification();
}
updateSavedInfo();
},
});
For second editor:
editroTwoIsSaving=true;
SetNavigateAwayNotification();
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorTwo",
data: mypostdata2,
success: function (msg) {
editorTwoIsSaving = false;
if (!editorOneIsSaving) {
RemoveNavigatingAwayNotification();
}
updateSavedInfo();
}
});
I was looking into adding object to array or list but it is not really nice in javascript. This way I would know who is the owner of lock or if there would be more editors I could make sure that same editor is not taking lock multiple times.
Maybe I am just overthinking and I should go with simply counter which if is 0 then remove navigate away.
One way to do this would be to add a counter to each ajax call to save.
You increment the counter before sending the data to the server and decrement it in the promise.
something like the following
function showSavingMessage(){
//code to show message
}
function removeSavingMessage(){
// code to remove message
}
var ctr = 0;
function saveData(){
showSavingMessage();
ctr++;
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorXXX",
data: mypostdata2,
success: function (msg) {
if (ctr > 0){
ctr--;
} else {
removeSavingMessage();
}
}
});
}
You can handle errors any way you like. may be change the "saving" message to error message.
You can also pass the url and the data to the saveData function to make it reusable, so you have a single function with the Ajax code.

IE11 JQuery ajax caching even with cache:false

I've tried everything I know and everything I've found to prevent IE (Edge!) from caching:
cache:false within the ajax params
add (manually) a timestamp in the call
set ajaxSetup
change request method from GET to POST
return a header inside the AJAX page that was called
I'm not using C# in order to use the param mentioned in some posts (I'm using coldfusion). Does someone know another method in order to fix that IE "feature"?
Here's the AJAX code in case you don't trust in me (like Dr. House says: everybody lies) or I'm skipping something:
$('a#showLista').click(function(event){
event.preventDefault();
$.ajax({
url: 'cfc/carrito.cfc?' + (new Date()).getTime() + '&method=preciosListaFav',
cache: false,
countentType: "application/json; charset=utf-8",
dataType: "json",
type: 'POST',
data: {
DataSource: DataSource,
IDCliente: clienteID,
IDUsuario: IDUsuario,
Sesion: Sesion
},
success: function(datos) {
i = datos.DATA.length;
if (i > 0) {
// Insert data into table
} else
// Alert empty list
}
});
});

AJAX Only Runs On First Page Load

I have a webpage that dynamically creates URLs on page load. The first time these links are clicked, they call a ajax query to load page data and it works perfectly. However, the second time the query is not executed and the data remains the same from the previous load.
Here is HTML code in activitylog.aspx where the URL items are added:
<ul class="ver-inline-menu tabbable margin-bottom-10 incidentlist"></ul>
Here is the jQuery Code in activitylog.aspx that is run on startup:
$(document).ready(function () {
// Get Parameter Values
var paramShiftId = getURLParameter('shift_id');
var paramIncidentId = getURLParameter('incident_id');
// Run Data Handler Query
$.ajax({
url: "queries/dataHandler_getShiftInfo.ashx",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { shift_id: paramShiftId, incident_id: paramIncidentId },
responseType: "json",
success: OnViewComplete,
error: OnViewFail
});
return false;
function OnViewComplete(result) {
//Cycle Through JSON Rows
$.each(result.aaData, function (i, row) {
$(".incidentlist").append("<li>" + row.INC_NUMBER + " </li>");
}
}
});
How do I create dynamic URLs that will load a refreshed page each time?
Ajax is something about no need to reload a page...
$(function(){
var paramShiftId = getURLParameter('shift_id');
var paramIncidentId = getURLParameter('incident_id');
loadData(paramShiftId, paramIncidentId);
})();
function loadData(paramShiftId, paramIncidentId) {
// Run Data Handler Query
$.ajax({
url: "queries/dataHandler_getShiftInfo.ashx",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { shift_id: paramShiftId, incident_id: paramIncidentId},
responseType: "json",
success: OnViewComplete,
error: OnViewFail
});
}
function OnViewComplete(result) {
$.each(result.aaData, function (i, row) {
$(".incidentlist").append("<li>" + row.INC_NUMBER + " </li>");
});
}
function OnViewFail(err){console.error(err);}

How to make jQuery JSON request and use response data to change html element values?

I'm not good at JQuery at all, in fact this is my first encounter due to Shopify. In other words I'm completely lost.
This is what I was able to do so far.
function FindPlayer()
{
var playerid = $('input[id=playerId]').val();
var clubname = $('input[id=teamname]').val();
$("#searchBar").attr('data-user-input', value);
$.ajax({
url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response(data);
}
});
}
The json response is going to look like this:
[{"playerFound":"true","tradeid":"123456"}]
I want to then check if playerFound is true or false before setting this element:
<input id="tradeId" type="hidden" name="attributes[tradeid]" />
This is probably pretty basic for JQuery users but not for me any help would be appericiated.
Try This:-
$.ajax({
url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if(data[0].playerFound == "true")
{
$('#tradeId').val(data[0].tradeid);
}
}
});
Since content type is JSON you can simply use like this
success: function (data) {
if(data.playerFound == "true"){
$('#tradeId').attr('name',data.tradeid) // if you want to change name
$('#tradeId').val(data.tradeid)// if you want to change value
}
}

JavaScript - Results Displaying in IE but not Chrome or FF

So, i'm new to Javascript, let's get that out of the way.
Anyway, I have the following code that works in IE, but not in Chrome or FF. It's supposed to grab the data from the Reddit RSS, then just output it, that's it. It only is working in IE. Can anyone explain what I'm doing wrong here?
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
document.write(result);
</script>
</head>
</body>
</html>
yes, this code doesn't look right. it's a race condition. document.write executes immediately. the ajax may or may not have set the result in time. you need to add the result to the page in the success event...something like:
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get', dataType: 'html',
async: false,
success: function(data) {
$("#some-div").html(data);
} });
You have race condition due to $.ajax being asynchronous. Display the result in the success handler instead, so that the request is guaranteed to have finished.
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
document.write(data);
}
});
Update
Since you set async to false, the above statement isn't applicable. However, I haven't ever found a good reason to use document.write(), which might be part of your issue. Try using another method to inject the data into your page such as .html(), .append(), alert(), etc. And it wouldn't hurt to do this inside document.ready either.
$(document).ready(function() {
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
alert(result);
$("body").append(result);
});
What about processing in this manner:
(function(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
})('http://www.reddit.com/.rss', function(feed) {
var entries = feed.entries,
feedList = '';
for (var i = 0; i < entries.length; i++) {
feedList += '<li>' + entries[i].title + '</li>';
}
jQuery('.rssfeed > ul').append(feedList);
});
HTML:
<div class="rssfeed">
<h4>RSS News</h4>
<ul></ul>
</div>
sample: http://jsfiddle.net/QusQC/

Categories

Resources