AJAX - Double Results on Page Refresh - javascript

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()

Related

Javascript image timout

Good day, i'm having a problem with my code, can't get to show the loading image for few seconds, while POST code is getting in database and gives backinformation to show.
$("#poll_vote").click(function(){
var answer = $("input.panswer:checked").val();
var p_id = $("#p_id").val();
$("#poll_load").html("<tr><td align='center'><img src='/images/ajax/ajax4.gif'/></td></tr>");
$.ajax({
type: "POST",
data: "action=poll_vote&p_id="+p_id+"&answer="+answer+"&module="+module+"",
dataType: 'html',
url: "/ajax.php",
success: function(data)
{
$("#poll_content").html(data);
}
});
});
I would hope on your fast help, i'm begginer in java, so can't dicide it myself.
If what you want is to create a delay so the loading animation shows (I believe that is... mmm different, I'm going with that...)
what you need is to set a timeout like so:
setTimeout(function(){ alert("Hello"); }, 3000);
now in your code the function could contain the ajax call:
$("#poll_vote").click(function(){
var answer = $("input.panswer:checked").val();
var p_id = $("#p_id").val();
$("#poll_load").html("<tr><td align='center'><img src='/images/ajax/ajax4.gif'/></td></tr>");
setTimeout(function(){
$.ajax({
type: "POST",
data: "action=poll_vote&p_id="+p_id+"&answer="+answer+"&module="+module+"",
dataType: 'html',
url: "/ajax.php",
success: function(data)
{
$("#poll_content").html(data);
}
});
}, 3000);
});
or be inside the success function, which I believe is better:
$("#poll_vote").click(function(){
var answer = $("input.panswer:checked").val();
var p_id = $("#p_id").val();
$("#poll_load").html("<tr><td align='center'><img src='/images/ajax/ajax4.gif'/></td></tr>");
$.ajax({
type: "POST",
data: "action=poll_vote&p_id="+p_id+"&answer="+answer+"&module="+module+"",
dataType: 'html',
url: "/ajax.php",
success: function(data)
{
setTimeout(function(){$("#poll_content").html(data);}, 3000, data);
}
});
});
I didn't test it, so check if in the second case data can be seen inside the callback function (it should I think...)
Hope it helps.

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

Using jQuery or Javascript redirect to given page with a value

I have a dropdown, on its change it should redirect to a page with the dropdown's value say as a POST
I tried something like this:
$(document).ready(function() {
$('some_dropdown').change(function() {
var id = $(this).val();
var datastring = 'id=' + id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
window.location.href("xyz.php");
}
});
});
});
On the xyz.php page:
if ($_POST['id']) {
Blah Blah..
}
It's not recognizing that id value on the xyz page. I want it's value on the redirected page.
Edited - To make things more clear, I tried out to print the xyz.php's contents on my original page (instead of redirecting) like this -
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
FYI, "somediv" was <div class="somediv"></div> in my original page(no-redirecting) and it worked!! It could identify the id. Some how can't work it out with redirecting. It can't identify the id.
Edited --
Last thing, if I don't redirect and use
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
The data loads perfect, my question is can I make some changes in the dynamically loaded textboxes and insert them in the database
If you have to make a post request can make it by appending a virtual form.
Here is the code for that.
$(document).ready(function() {
$('[name="some_dropdown"]').change(function() {
var mval = $(this).val(); //takes the value from dropdown
var url = 'xyz.php'; //the page on which value is to be sent
//the virtual form with input text, value and name to be submitted
var form = $('<form action="' + url + '" method="post">'+
'<input type="text" name="id" value="' + mval + '" />'+
'</form>');
$('body').append(form); //append to the body
form.submit(); //submit the form and the page redirects
});
});
and on PHP
if(isset($_POST['id'])){
echo $_POST['id'];
}
Your datastring should be key value pair. Like this.
var datastring = {'id':id};
you have few mistakes in your code so your correct code will be like this
$('.some_dropdown').change(function(){
var id = $(this).val();
var datastring = 'id='+id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html){
window.location.href= "xyz.php?"+datastring+"";
}
});
});
});
and php code
if(isset($_GET['id'])){
Blah Blah..
}

using ajax how to show the value after success without refreshing the page

i am adding the value to database by using ajax after adding i want to display the value in front end but now after success i am using window.location to show the data because of this the page getting refresh,i don't want to refresh the page to show the data ,anyone guide me how to do this.
below is my ajax
$(function() {
$(".supplierpriceexport_button").click(function() {
var pricefrom = $("#pricefrom").val();
var priceto = $("#priceto").val();
var tpm = $("#tpm").val();
var currency = $("#currency").val();
var dataString = 'pricefrom='+ pricefrom +'&priceto='+priceto+'&tpm='+tpm+'&currency='+currency;
if(pricefrom=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html;
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
window.location = "?action=suppliertargetpiceexport";
$("#flash").hide();
}
});
} return false;
});
});
The code that you are using to post the data needs to return some meaningful data, JSON is useful for this, but it can be HTML or other formats.
To return your response as JSON from PHP, you can use the json_encode() function:
$return_html = '<h1>Success!</h1>';
$success = "true";
json_encode("success" => $success, "html_to_show" => $return_html);
In this piece of code, you can set your dataType or JSON and return multiple values including the HTML that you want to inject into the page (DOM):
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
//Set the type of data we are expecing back
dataType: json
success: function(return_json){
// Check that the update was a success
if(return_json.success == "true")
{
// Show HTML on the page (no reload required)
$("#display").after(return_json.html_to_show);
}
else
{
// Failed to update
alert("Not a success, no update made");
}
});
You can strip out the window.location altogether, else you won't see the DOM update.
Just try to return the values that you need from the ajax function.Something like this might do.
In your insert.php
echo or return the data at the end of the function that needs to be populated into the page
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(data){
//Now you have obtained the data that was was returned from the function
//if u wish to insert the value into an input field try
$('#input_field').val(data); //now the data is pupolated in the input field
}
});
Don't use window.location = "?action=suppliertargetpiceexport";
This will redirect to the page suppliertargetpiceexport
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$('#your_success_element_id').html(html); // your_success_element_id is your element id where the html to be populated
$("#flash").hide();
}
});
your_success_element_id is your element id where the html to be populated

How can I use AJAX to dynamically change span text in this example?

LOGIC DEMO (jsFiddle): Click Here!
The demo linked above is the result I would like to achieve. However, I need to translate this to dynamically fill this content from XML variables asize & aprice. Below is the current method I am using for cascading dropdowns using AJAX.
XML DATA:
<avar aval="1" asize="Small Flag" aprice="$26.00" atext="Size 0"/>
JS DATA:
if($('#drpType').val() == "1")
{
$.ajax({
type: "GET",
url: "Flags.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('avar').each(function(){
$('#drpSize').append($('<option></option>').val($(this).attr('aval')).html($(this).attr('atext')));
});
}
});
}
LOGIC (Non-Functional):
if($('#drpSize').val() == "1")
{
$.ajax({
type: "GET",
url: "Flags.xml",
dataType: "xml",
success: function(xml) {
// GET XML Value (asize) & print to <span class="ms"> onChange (#drpSize)
// GET XML Value (aprice) & print to <span class="mp"> onChange (#drpSize)
$('#drpSize').change(function (){
$(xml).find('aval').each(function(){
if ($(this).val() == "1") {
$('.ms').text('asize');
$('.mp').text('aprice');
});
}
});
}
You need to parse the xml into a traversable xmldoc before you can use find.
var xmlDoc = $.parseXML(xml);
$(xmlDoc).find(...

Categories

Resources