Javascript - How to get script to run with Ajax requested data - javascript

Battlefield Page
In the image above, there is a page that has a battlefield with 20 users on it. I have written JavaScript to capture the data and store it in a MySQL db. The problem comes into the picture when I need to hit next to go to the next page and gather that data.
It fetches the next 20 users with an Ajax call. Obviously when this happens, the script can't log the new information because the page never loads on an Ajax call which means the script doesn't execute. Is there a way to force a page load when the Ajax link is clicked?
Here's the code:
grabData();
var nav = document.getElementsByClassName('nav')[0].getElementsByTagName('td')[2].getElementsByTagName('a')[0];
nav.addEventListener("click", function(){
grabData();
});
function grabData(){
var rows = document.getElementsByClassName('table_lines battlefield')[0].rows;
var sendData = '';
for(i=1; i < rows.length -1 ; i++){
var getSid = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].getElementsByTagName('a')[0].href;
var statsID = getSid.substr(getSid.indexOf("=") + 1); //Grabs ID out of stats link
var name = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].textContent.replace(/\,/g,"");
var tff = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[3].textContent.replace(/\,/g,"");
var rank = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[6].textContent.replace(/\,/g,"");
var alliance = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[1].textContent.trim();
var gold = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[5].textContent.replace(/\,/g,"");
if(alliance == ''){
alliance = 'None';
}
if(gold == '??? Gold'){
gold = 0;
}else{
gold = gold.replace(/[^\/\d]/g,'');
}
sendData += statsID + "=" + name + "=" + tff + "=" + rank + "=" + alliance + "=" + gold + "#";
}
$.ajax({
// you can use post and get:
type: "POST",
// your url
url: "url",
// your arguments
data: {sendData : sendData},
// callback for a server message:
success: function( msg ){
//alert(msg);
},
// callback for a server error message or a ajax error
error: function( msg )
{
alert( "Data was not saved: " + msg );
}
});
}
So as stated, this grabs the info and sends to the php file on the backend. So when I hit next on the battlefield page, I need to be able to execute this script again.
UPDATE : Problem Solved. I was able to do this by drilling down in the DOM tree until I hit the "next" anchor tag. I simply added an event listener for whenever it was clicked and had it re execute the JavaScript.

Yes, you can force a page load thus:
window.location.reload(true);
However, what the point of AJAX is to not reload the page, so often you must write javascript code that duplicates the server-side code that builds your page initially.
However, if the page-load-code-under-discussion runs in javascript on page load, then you can turn it into a function and re-call that function in the AJAX success function.
Reference:
How can I refresh a page with jQuery?

Related

Mouse click needed in IE11 but not in Firefox

I have an HTML form that contains an AJAX call to get some data for the form, specifically a set of select options. This works fine and in Firefox (50.0.2) the results are selectable after handling the AJAX success response. To prevent the form from submitting, before I hit enter on the data needed for the AJAX jQuery GET, I preventDefault on the form submission and all that works OK.
But in Internet Explorer 11 the select data are not immediately visible after processing the AJAX call response but if I mouse-click (left mouse button) anywhere in the form area, the AJAX response data becomes visible and selectable.
I have tried to use jQuery trigger click to simulate the left mouse click anywhere in the form area but I can't get that to work. Can anyone suggest how to get IE11 to behave like Firefox does? Any suggestions will be most appreciated.
I have attached part of the AJAX response code if that might help - the response is in XML format..
// Now insert the received response(s) into the DOM:
$(data).find('result').each(function()
{
// $(data).find('result') creates an array (which hopefully will not be empty)
var dataToDisplay = $(this).text();
// we now have a pipe-delimited string - convert it into an array
var data_array = dataToDisplay.split('|');
var dog_pk = data_array[0];
var dog_name = data_array[1];
var dog_breed = data_array[2];
var customer = data_array[3];
var the_rest = dog_name + ", " + dog_breed + ", " + customer;
$('#dog_pk').append("<option value=" + dog_pk + ">" + the_rest + "</option>");
});
Here's the AJAX GET request:
$(function()
{ // get dog and owner names function
$('#dogname_start').change(function(event)
{
var params = "params=";
params += String ($('#dogname_start').val());
params = encodeURI(params);
$('#add_appointment').submit(function(event)
{
event.preventDefault();
// alert("In dogname_start change form submit function, params are " + params);
});
$.get(
'./modules/get_dognames.xml.php',
params,
handle_response
); // end AJAX get (note: type defaults to html)
}); // end change function on #dogname_start
}); // end get dog and owner names function

Trying to populate an html option list with jQuery's get method

I currently have a servlet setup to send over a list of our active servers. The method grabs the servlet data, processes it, then injects the html into the datalist tag. HTML injection process works, but when I'm splitting the array by the concat separator (which I've done before), I get no values. Below I'll explain with code examples:
HTML:
<label for="server_id_text">Server ID: </label>
<input id="server_id_text" list="server_names" name="server_id" required>
<datalist id="server_names">
<!--This gets injected with the active servers grabbed through a get request-->
</datalist>
Javascript connecting to server to get data:
Note: serverList is a global variable.
var serverList = "";
function setupAutoComplete() {
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
console.debug("server list auto comp at post mailing: " + serverList);
});
}
This method is called in the function that is called when the onload event is called in the body tag
Here are the two methods that inject the html:
function setupServerName() {
document.getElementById("server_names").innerHTML = getServerListHTML();
}
function getServerListHTML(){
console.debug("Autocomplete process running...");
var servArr = String(serverList).split('*');
var html = '';
var temp = '<option value="{serverName}">';
console.debug("Array:" + servArr.toString());
if (serverList == 'undefined' || servArr.length == 0){
console.debug("serverList is empty...");
return '';
}
for (var i =0; i < servArr.length; ++i){
html += temp.replace("{serverName}", servArr[i]);
}
console.debug("html: " + html);
console.debug("ServList size " + servArr.length);
return html;
}
When the page loads, setupAutoCompelte() is called first. Then, setupServerName() is called.
My issue is that after I load the page, I get the correct response from the server. For instance, I'll get server1*server2 as a response to the jQuery $.get(...) call. Then I go to split the string into an array, and I get back an empty html tag (<option value="">);
Also, the debug console info are as follows:
Autocomplete process running...
Array:
html: <option value="">
ServList size 1
Status with auto comp id: success
server list auto comp at post mailing: server1*server2
Thanks for the help!
I believe that your setupServerName() function is being called before the AJAX request in setupAutoComplete() returns, so your serverList is an empty string at that point. What you need to do is populate your <datalist> from inside your AJAX callback in setupAutoComplete().
// setup autocomplete datalist
function setupAutoComplete() {
var $datalist = $('#server_names');
$.get(baseURL + '/SupportPortal').then(function (data) {
// update datalist
if (!data || !data.length) {
// no servers, empty list
$datalist.html('');
} else {
// create options html:
// reduce array of server names
// to HTML string, and set as
// innerHTML of the dataset
$datalist.html(data.split('*').reduce(function (html, server) {
return html + '<option value="' + server + '">\n';
},''));
}
});
}
// on page load, setup autocomplete
$(function () {
setupAutoComplete();
});
As you can see from "debug console info":
the get function is asyncrhonous so you need to change your setupAutoComplete get part to:
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
setupServerName();
console.debug("server list auto comp at post mailing: " + serverList);
});
On page load try to call directly the setupServerName function within the success event of get function. A different approach is to divide the setupServerName function so that the part related to the serverList variable becomes part of another function.
The serverList variable is global but its content is filled after the setupServerName is executed.

Validating a directory from a javascript page using $.post to call a webservice PHP function

I am trying without success to use the $.post function to test (via a webservice that calls a PHP function "is_dir") if a folder already exists on a server and then I want it to return a string or boolean value back to my javascript page before I proceed to dynamically write the new files that will be placed there. The file path of the folder to be tested is "built" using jQuery which captures form data. I need to define (in a variable) if the directory exists and then be able to access that variable from outside of the $.post function (not from within, using success callback). This is so I can proceed in javascript as follows:
if {directory exists} then
capture more form data (via jQuery) and
$.post to webservice that calls PHP to update database
Outside of the $.post function, the value of my return variable is undefined.
I think I may be over-complicating this. Any suggestions? Thank you, in advance.
Please see my comment to #Steve above:
<script type='text/javascript'>
//function gathers form data, validates constructed file path and then writes to DB
function post_FormData() {
var week_number = $("#form_week_number").val();
var program = $("#form_program").val();
var course = $.trim($("#form_course_number").val());
var form_content_type = $("input:radio[name=content_type]:checked").val();
var content_type = "";
var activity_title_Val = $.trim($("#form_activity_name").val());
var activity_title_Split = activity_title_Val.split(" ");
var activity_title_Clean = new Array();
//this for-loop constructs a valid directory folder name from form data
for(var i=0, l=activity_title_Split.length; i<l; i++) {
activity_title_Split[i] = activity_title_Split[i].replace(/[^a-z0-9\s]/gi,"");
activity_title_Clean[i] = activity_title_Split[i];
activity_title_Split[i] = activity_title_Split[i].replace(/\b[a-z]/g, function(letter){return letter.toUpperCase();});
}
var activity_title = activity_title_Split.join("");
var file_path = "";
file_path += "/CourseFiles/" + program + "/" + program + course + "/" + content_type + "/Week" + week_number + "/activity-" + activity_title;
var message = "<div id=\"confirmation_container_contents\"><p><b>Confirm Content Repository file path: </b><br></p>";
//begin web service call to PHP function
$.post('webservices/create_PA_webservices.php', {web_service: "go_check_if_exists", data_file_path: file_path}, function(data){
var exists = data.does_exist; //json_encoded RESPONSE FROM ASYNC REQUEST
if(exists == "Y") {
message += file_path;
message += "<br><br><br><center><b>An activity folder with this name already exists.</b></center>";
message += "<br><br><center>Please edit the activity title and resubmit.</center>";
message += "<br><br><br><center><input type=\"image\" src=\"pa_images/editButton.jpg\" id=\"editButton\" value=\"edit\"></center></div>";
$("#confirmation_container").empty();
$("#confirmation_container").append(message);
}
else if(exists == "N") {
message += file_path;
message += "<br><br><center><input type=\"image\" src=\"pa_images/editButton.jpg\" id=\"editButton\" value=\"edit\">";
message += "&nbsp\;&nbsp\;&nbsp\;<input type=\"image\" src=\"pa_images/confirmButton.jpg\" id=\"confirmButton\" value=\"confirm\"></center></div>";
$("#confirmation_container").empty();
$("#confirmation_container").append(message);
}
$(function(){//edit proposed file path
$("#editButton").click(function() {
$("#confirmation_container").empty();
});//end function edit path button
});//end anonymous function
$(function(){//confirm proposed file path and write to DB
$("#confirmButton").click(function() {
go_post_FormData(activity_title_Val, file_path, week_number, program, course, content_type);
$("#create_practice_activity").hide();
$("#build_practice_activity").show();
$("#activity_is_new").val("N");
});//end function confirm path button
});//end anonymous function
}, "json").fail(function() {alert("The go_check_if_exists webservice call has failed");}); //end web service call
}//end function post_FormData declaration
</script>

Not able to append data to Div and redirect page

I have a default page with list of items. When I click on those Items I need to dynamically append data to div in Page B and redirect the app to Page B.
I added this div in PageB
''
On Click event I am doing following action in .js file:
'$(document).on('click', '#selectConcept', function (node) {
var ncid = this.textContent.slice(6,25);
$.ajax({
dataType: "json",
url: "http://txv-trmindexer01:8080/CommonTerminologyLeopardSearch/rest/getConceptByNcid/" + ncid,
error: function () {
alert("ERROR");
},
success: function (data) {
window.location.href = 'getfacets.html';
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
} });
});'
I am able to redirect page, but nothing is appended to Div.
Can anyone help me out with this..
I'm not really sure, but I guess the code runs before the new page is loaded. So you could try to wrap the code in a function run at onload event time
window.location.href = 'getfacets.html';
window.onload = function() {
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
}
The problem:
As soon as you set "window.location.href" property the page navigates to your page B and you loose your fetched data.
You have two solutions to the problem:
Use Single Page Application (SPA) application approach wherein you could create a new global scope for your fetched data, which can now be used by page B
Send the ncID as a querystring parameter to page B and and implement the service call and data appending logic on page B

Delay between dynamic posts

I have this JS code that is meant to display each dynamically loaded posts when clicked on:
function showPost(id) {
$.getJSON('http://hopeofgloryinternational.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
output += '<h3>' + data.post.title + '</h3>';
output += data.post.content;
$('#mypost').html(output);
}); //get JSON Data for Stories
} //showPost
When I test the page 'http://howtodeployit.com/devotion/' on my mobile or windows browser, clicked on Daily Devotional Messages and I navigate between each posts, I notice the previously accessed post still shows for few seconds before the new post gets displayed.
How do refresh the page or DOM so it clears out previously accessed page.
Just empty() the contents of myPost while clicked on the item or on click of back button. Reason is that your previous content is still there in the mypost div, and your content page becomes visible even before the ajax call is executed which may take some time to complete say 700ms, so you will see the old content for that much period of time.
function showPost(id) {
var $myPost = $('#mypost').empty(); //emtpy it
$.getJSON('http://hopeofgloryinternational.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
output += '<h3>' + data.post.title + '</h3>';
output += data.post.content;
$myPost.html(output);
}); //get JSON Data for Stories
function start with a line $('#mypost').html(""); before going to another request to clear display content.
Also you can add a waiting message $('#mypost').html("Please wait..."); before showing content from next request.
function showPost(id) {
$('#mypost').html(""); //add this line
//$('#mypost').html("Please wait..."); //also you can add it to show waiting message.
$.getJSON('http://hopeofgloryinternational.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
output += '<h3>' + data.post.title + '</h3>';
output += data.post.content;
$('#mypost').html(output);
}); //get JSON Data for Stories
}
You can empty() $mypost
var $myPost = $('#mypost').empty();

Categories

Resources