How to get Xml data to dynamic list - javascript

test.xml
<Bock1>
<No>123</No>
<RoomNo>10</RoomNo>
<UpdateTime>1230</UpdateTime>
</Block1>
run.js
$.ajax({
type: "GET",
url: test.xml,
dataType: "xml",
success: function (xml) {
$(xml).find('Block1').each(function () {
var updateTime = $(this).find("UpdateTime").text();
var no= $(this).find("No").text();
var roomNo = $(this).find("RoomNo").text();
var status = no + '<br/>' + roomNo + '<br/>' + updateTime;
});
}
});
$('<div>')
.attr({
'data-role': 'collapsible', 'data-collapsed': 'false', 'data-mini': 'true'
})
.html('<h4>' + item_name + '</h4><p>' + status + '</p>')
.appendTo(collapsibleset);
}
});
I'm using this to generate collapsibleset with xml data,
but status can't correctly fill into
<p> + status + </p>
status will get correctly inside ajax, but can't get to collapsibleset.
I've tried to use global variable, but get same situation.
How could I fill it in correctly?
I'm new to jquery & javaScript,
Thanks for any answers!!!

jQuery.ajax() is expecting string for the URL value.
Therefore your URL just needs wrapping in quotes.
Then your DOM reference of the
$('< div >')
is wrong.
To reference an element in JQuery, you have several options, but the easiest is to give an element an id and then reference that (think CSS)
$('div') would get all divs
$('div#my_id') would get this particular element:

Related

AJAX jQuery Iterate through response on Button Click

I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}

jQuery .html(someHTML) is not working

I have a script that makes an ajax request to the server. Then the server returns HTML code. After the request finish, I want to take the HTML code and put it on my site.
The problem that I am having is that the function .html() will display the html as text instead of making it an html.
Here is what I have done
var postData =
{
'campaign_id': 1,
'page_role': 'intro'
};
$.ajax({
type: 'POST',
url: 'url/to/get/html',
data: postData,
dataType: "text",
beforeSend: function(jqXHR, settings){
$('#MasterContentViewer').html('<div class="well innerwell">' +
'<h3>Please wait while loading the next page</h3>'+
'</div>');
},
error: function( jqXHR, textStatus, errorThrown ){
alert('Loading content failed! Error Code: ' + jqXHR.status);
},
success: function(page){
$('#MasterTable').removeClass('heightForIFrame');
$('#MasterContent').removeClass('heightForIFrame');
$('#MasterContentViewer').html(page);
}
}).done(function(page) {
var tags = $("meta[name^='is_system_'],meta[name^='is_attr_']" );
$.each(tags, function(index, tag){
var value = $(tag).attr('value');
var name = $(tag).attr('name').replace('is_attr_', '').replace('is_system_', '');
$('#attr_' + name + ':input').val( value );
$('#attr_' + name).not('input').text( value );
$('.attr_' + name + ':input').val( value );
$('.attr_' + name ).not('input').text( value );
});
I tried to change the following like
$('#MasterContentViewer').html(page);
to
$('#MasterContentViewer').empty().append(page);
which also did not work.
I also tried to change the dataType from "text" to "html" which also did not work.
How can I make the force the page to display html code instead of text?
UPDATED
Here is sample of what the user sees on the screen
<strong>Store Name: </strong><span class="attr_storename"></span> </div> <div class="scripter_header_label"> <strong>Store Number: </strong><span class="attr_alt_id_1"></span>
If .html(string) is appending elements as text, then that means that the elements are already HTML Encoded (e.g., <'s are in the string as >'s). jQuery will only encode html if you tell it to by using .text(string) instead of html(string).
Two possible solutions are:
Modify your server-side code to send non-encoded HTML
HTML Decode the string using Javascript (I would not recommend this method, however, because it caters to HTML Injection attacks).

jQuery refresh div based upon HTML5 data element

My code is as follows:
$('*[data-pickup]').change(function(){
var value = $(this).val();
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + $(this).attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + $(this).attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + $(this).attr("data-pickup") + "']").show();
})
The AJAX call shows a response when viewed through Firebug, which wasn't being refreshed on the screen, so I changed it to a simple "Hello" response, which still doesn't work.
If I comment out the .html("HELLO 2") line, it shows the once hidden div containing the HTML5 data element of data-pick=1 or data-pick=2, etc. (depending on what attr("data-pickup") is) which is automatically filled with "Test", so it shows "Test".
If I uncomment the .html("HELLO 2") line, the div once shown says "HELLO 2". But, in the case of the commented out .html("HELLO 2") line, it should be being updated from "Test" to "Hello" via the AJAX call, but it isn't. If I change the data* to a simple HTML id element and update all the code to #" + $(this).attr("data-pickup") + ", it works the exact same with the data attribute (the AJAX call doesn't update anything).
And when I make a var called "el" and make it equal to *[data-pick='" + $(this).attr("data-pickup") + "'], and then print it to the console it appears as: "[data-pick='1']" or "[data-pick='2']", etc. Then if I update all the code from $("*[data-pick='" + $(this).attr("data-pickup") + "']").whatever to $(el).whatever (thinking there might be a bug somewhere), it still works the same as before.
So, what have I done wrong? Why won't the div get refreshed via the AJAX call but it will after the AJAX call?
The problem is that 'this' in the success handler of the ajax function is the ajax function itself not the element that triggered the event handler. What you need to do is store the value of the element var el = $(this) then reference that whenever you want to access the element taking advantage of closures.
$('*[data-pickup]').change(function(){
var value = $(this).val();
var el = $(this);
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + el.attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + el.attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + el.attr("data-pickup") + "']").show();
})
Try this:
$('*[data-pickup]').change(function() {
var self = this;
var value = $(self).val();
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + $(self).attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + $(self).attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + $(self).attr("data-pickup") + "']").show();
})
this inside the success function is not the same this as elsewhere in the change handler.
Here's a solution :
$('*[data-pickup]').change(function(){
var value = $(this).val();
var $el = $("*[data-pick='" + $(this).attr("data-pickup") + "']");//here keep a reference to the element(s) of interest.
console.log(value);
$.ajax({
type: "POST",
cache: false,
url: "a.php?pickup",
data: {'X': value},
success: function(data) {
$el.html("HELLO");//$el is still available here, from the closure formed by the outer function
}
});
$el.show().html("HELLO 2");
});

Get Javascript to work? $.ajax not working right?

So, the Javascript code which can be found below doesn't seem to be functioning properly.
The goal is to get the text below the map to change on hover of the rooms.
Map Page
The JSON (zadias.me/SVG/rooms.json) data that pulls the data seems to be where I'm faulting, I think. When I test/debug the code by placing .innerHTML statements that would print in the text field, it would work if I placed the .innerHTML before the $.ajax, however, if I put the .innerHTML function in the "success" part of the .ajax, it wouldn't work..
Javascript:
$(document).ready(function(){
var json = (function () { //this function obtains the data
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'http://zadias.me/SVG/rooms.json',
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
function hashTag(){
var hashTag, hash2;
hashTag = location.hash; //obtains the part of the URL with the hash tag and what follows
hashTag = hashTag.replace(/#*/, ''); //replaces the hash tag
if(hashTag.length > 0){
for(i=0 ; i<json.rooms.length ; i++){
if (json.rooms[i].roomId == hashTag) //linear search through array of rooms to see if any equal the hashTag
{
document.getElementById('room_info').innerHTML = '<img src="images/' + json.rooms[i].image + '" /><h4>' + json.rooms[i].name + '</h4>' + json.rooms[i].HTMLdescrip;
} //loads the data from the JSON data.
}
}
};
function setHash(){
window.location.hash = this.id; //creates the hash link based on the object's id (object id acquired from the JSON data) and sets it
};
function setHTML(){
for(i=0 ; i<json.rooms.length ; i++){
if (json.rooms[i].roomId == this.id)
{
document.getElementById('room_info').innerHTML = '<img src="images/' + json.rooms[i].image + '" /><h4>' + json.rooms[i].name + '</h4>' + json.rooms[i].HTMLdescrip;
}
}
};
window.onload = hashTag();
$(".active").click(setHash);
$(".active").mouseenter(setHTML);
//$(".active").mouseover(setHTML);
$(".active").mouseleave(hashTag);
});
I understand that it's a bit localized, how could I change this up?
If I'm getting it right, you need the variable json to be global. Just take off the var at the beginning and see if that helps.
You may want to try something more along these lines:
// this returns a promise
var json,
response = $.ajax({
'async': false,
'global': false,
'url': 'http://zadias.me/SVG/rooms.json',
'dataType': "json",
'success': function (data) {
json = data;
}
});
window.onload = function() {
// ensures that the ajax has returned a value
response.done(hashTag);
};
The document doesn't really have to be ready for you to run an AJAX request.
You may want to take a look here for accessing the SVG elements: How to access SVG elements with Javascript. Requires a change from <embed> to <object>
Here's a version of your code with a few updates:
var json;
$(document).ready(function(){
$.ajax({
'global': false,
'url': 'http://zadias.me/SVG/rooms.json',
'dataType': "json",
'success': function (data) {
json = data;
hashTag();
$(".active")
.click(setHash)
.mouseenter(setHTML)
.mouseleave(hashTag);
}
});
});
function hashTag(){
//get everything in the URL after the #
var hash = location.hash.replace(/#*/, '');
if(hash.length > 0){
//linear search through array of rooms to find the hashTag
$.each( json.rooms, function( room ) {
if (room.roomId == hash) {
$('#room_info').html(
'<img src="images/' + room.image + '" /><h4>' +
room.name + '</h4>' + room.HTMLdescrip
);
} //loads the data from the JSON data.
});
}
};
// creates the hash link based on the object's id
// (object id acquired from the JSON data) and sets it
function setHash(){
window.location.hash = this.id;
}
function setHTML(){
$.each( json.rooms, function( room ) {
if (room.roomId == this.id) {
$('#room_info').html(
'<img src="images/' + room.image + '" /><h4>' +
room.name + '</h4>' + room.HTMLdescrip
);
}
});
}
What I changed:
Made the json variable global.
Removed the async:true. Never use that!
Removed global:false. You don't have any global Ajax event handlers, so this flag has no effect.
Removed unnecessary quotes around the $.ajax() property names.
Removed the event handler setup at the end of the code.
Moved that initialization inside the $.ajax() callback since that is when the data is ready.
Chained together the event handler setup on $(".active") instead of repeating the selector call.
Used $.each() instead of the for loops for simplicity.
Changed the json.rooms[i] references to room thanks to $.each().
Used $('#foo').html(html) instead ofdocument.getElementById()and.innerHTML`, again for simplicity.
Simplified the setup of the hashTag variable and changed its name to hash to avoid confusion with the function name.
Removed unnecessary semicolons at the end of function definitions.
Made the indentation and formatting more consistent.
Shortened the excessive line lengths.
Some of these changes are just stylistic, but they're things I recommend. Naturally you can pick and choose among those after looking through the code.
The important point is making sure that the json data is available not just where it's needed, but when it's needed, and without using async:false.

$ajax is not working with ASP.Net

I am debugging my solution on localhost and this piece of code is not hitting the server
var cartInfo = $j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val() + '&email=' + email.val() + '&phone=' + phone.val() + '&date=' + date.val() + '&cart=' + cartInfo;
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
What am I missing here?
the are 2 potential problems
the url
the data
aspx assumes webforms, the page life cycle, etc. when all you want is to send response and get a reply. instead try targeting either a
web service (asmx)
generic handler (ashx)
a static pagemethod think ajax server hanlders embedded within a page object
second is the data. instead of passing a string as the data try passing a json object
data = {
name: "john",
email: "john#email.com",
...
}
Since you are passing the cartInfo as an html, it should be url encoded before it is posted. I think this is wat causing this issue. Try this
var cartInfo =
$j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val()
+ '&email=' + email.val()
+ '&phone=' + phone.val()
+ '&date=' + date.val()
+ '&cart=' + encodeURIComponent(cartInfo);
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
As suggested by in other answer you can also pass data as a key/value pair object to ajax method, jQuery will take care the rest but you still have to encode the html content.
Url Doesnt call any method ?
url: "LightBoxContactSender.aspx",
If yoy are trying to call a WebMethod inside aspx
url :"LightBoxContactSender.aspx/callStaticMethod",
Try to form Data as
dataString = "{'name=' + '"+name.val()+"'}"

Categories