AJAX Only Runs On First Page Load - javascript

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);}

Related

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
}
}

AJAX jQuery Freezing IE/Safari

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.

Code after ajax (code) block needs a delay

I had a long question along with my complete code but now it is shorter one.
function showRecord(tbl) {
myDataTable.fnDestroy();
$.ajax(
{
data: "tableName=" + tbl,
url: "showTable.php",
dataType: "html",
success: function (data) { $("#example").html(data); }
});
alert('I get desired output as long as I do not comment/remove this alert');
myDataTable = $('#example').dataTable();
}
BUT if i just comment the alert I do not get data from database
If I do not use $('#example').dataTable(); (a jquery plugin for pagination from datatables.net ) then code works fine without alert.
function showRecord(tbl) {
//myDataTable.fnDestroy();
$.ajax(
{
data: "tableName=" + tbl,
url: "showTable.php",
dataType: "html",
success: function (data) { $("#example").html(data); }
});
//alert('I get desired output as long as I do not comment/remove this alert');
//myDataTable = $('#example').dataTable();
}
I need to know why alert is necessary in first sample of code. If it causes delay, why delay is necessary here and how to achieve this without using alert
Ajax calls are asynchronous. In the first block of code (if there is no alert) ajax call get executed and then immediately after that (before server responds) this line executes:
myDataTable = $('#example').dataTable();
and since server did not return result yet $('#example') is empty. You can put it it like this:
function showRecord(tbl) {
myDataTable.fnDestroy();
$.ajax(
{
data: "tableName=" + tbl,
url: "showTable.php",
dataType: "html",
success: function (data) {
$("#example").html(data);
myDataTable = $('#example').dataTable();
}
});
}
Try this.
function showRecord(tbl) {
//myDataTable.fnDestroy();
$.ajax(
{
data: "tableName=" + tbl,
url: "showTable.php",
dataType: "html",
success: function (data) {
$("#example").html(data);
myDataTable = $('#example').dataTable(); }
});
//alert('I get desired output as long as I do not comment/remove this alert');
//
}

AJAX - Double Results on Page Refresh

I have this bit of code where it displays some locations from an XML feed using AJAX:
$.ajax({
type: "GET",
url: "testxml.xml",
dataType: "xml",
success: function(xml) {
$(xml).find("Country[Name='"+localStorage.ArrivalCountry+"']").find('Destination').each(function(){
var destinationName = $(this).attr('Name');
$('<a class="listItem" href="#" id="'+destinationName+'">'+destinationName+x+'<div class="arrow"></div></a>').appendTo('#destinationList');
});
}
});
First time it displays correctly but if I refresh the page it displays each result two times. If I do it again it displays it three times and so on.
You need to empty() the previous AJAX calls' data from the #destinationList before you add the updated set:
$.ajax({
type: "GET",
url: "testxml.xml",
dataType: "xml",
success: function(xml) {
$("#destinationList").empty(); // This will clear out all the previously appended 'a' elements
$(xml).find("Country[Name='"+localStorage.ArrivalCountry+"']").find('Destination').each(function() {
var destinationName = $(this).attr('Name');
$('<a class="listItem" href="#" id="'+destinationName+'">'+destinationName+x+'<div class="arrow"></div></a>').appendTo('#destinationList');
});
}
});
More information about empty()

window.Open Open popup Instead of new window

I have a, ajax function in jQuery and I want in complete function to open a url in a new window or tab.
Link
And :
function Add(ID, url)
{
var data = "{'ID' : '" + ID + "'}";
$.ajax({
type: "POST",
url: "Function.ashx/Add",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function ()
{
window.open(url);
}
});
}
window.open function works as popup but I want to open the link in a new window. w3School Example works prefect.
But my browser detects it as a popup and blocks it.
What's wrong with my code?
Why do you specifically wait till the AJAX call completes to load the URL?
Why not simply trigger the AJAX call and open the new window directly after.
Example:
Link
function Add(ID, url)
{
var data = "{'ID' : '" + ID + "'}";
$.ajax({
type: "POST",
url: "Function.ashx/Add",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
window.open(url);
}
I'm guessing w3cschool.com probably gets the popup previlige for being an authorised tutoring site.
AFAIK, any means to open an extra window without direct user interaction (e.g. a click) is considered a "popup" and would be blocked by most of the browsers with popup blocker enabled. Your best bet is probably open the link upon a click and inject whatever you want upon the AJAX completion:
Link
function Add(ID, url)
{
var newWindow = window.open(url);
var data = "{'ID' : '" + ID + "'}";
$.ajax({
type: "POST",
url: "Function.ashx/Add",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (data)
{
// do whatever you want with newWindow
}
});
}

Categories

Resources