My example page url is http://example.com/itemurl/?23 where 23 is the item number.
On that page, I need to pull that 23 and make it a variable so I can append it to the url in an Ajax call to get an xml file:
Here is my script:
<script>
$(document).ready(function () {
$.ajax({
type: "Get",
url: "https://example.com/getxml/",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(xml) {
$(xml).find("product").each(function () {
$(".prod_title").append('<h1>' + $(this).find("item_name").text() + '</h1><span>' + $(this).find("short_description").text() + '</span><ol class="breadcrumb"><li>Browse Products</li><li>Your Dashboard</li></ol>');
$(".category").append('<div class="cat">'+ $(this).find("category_name").text() +'<div>');
$(".product-rating").append('<i class="icon-star3">'+ $(this).find("no_of_units").text() +' Units Available</i>');
$(".product-price").append('<ins>ARV: $'+ $(this).find("item_price").text() +' </ins>');
$(".product-image").append('<img src="'+ $(this).find("image_url").text() +'" alt="example_product"/>');
$(".exp-date").append('<li><i class="icon-caret-right"></i> Expires On: '+ $(this).find("prod_exp").text() +'</li></div>');
$(".posted_in").append('Category: '+ $(this).find("category_name").text() );
$(".prod_description").append('<p>'+ $(this).find("full_description").text() +'</p>');
});
}</script>
I need the url in the script to be https://example.com/getxml/23 but I'm not sure how to accomplish this.
The line with url should look like this:
url: "https://example.com/getxml/"+window.location.search.substr(1),
Related
I have a total of 4 XML files in same format representing 4 different categories of project contents. However some projects does have more than 1 category.
I want to merge all 4 XML files using jQuery and display all projects contents in a single page within a , but due to the fact that some projects have more than 1 category, the displayed results show duplicates of project contents.
How do I remove duplicates within the combined extracted XML files?
Here is my jQuery Code:
XMLLIST = {
//general settings
xml1: 'xml/structural_steel.xml?' + Math.random(0,1), //solve ie weird caching issue
xml2: 'xml/building_work_id.xml?' + Math.random(0,1), //solve ie weird caching issue
xml3: 'xml/shear_stud_welding.xml?' + Math.random(0,1), //solve ie weird caching issue
xml4: 'xml/custom_solution.xml?' + Math.random(0,1), //solve ie weird caching issue
appendTo: '#list', //set the id/class to insert XML data
init: function () {
//jQuery ajax call to retrieve the XML file
$.ajax({
type: "GET",
url: XMLLIST.xml1,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml2,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml3,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml4,
dataType: "xml",
success: XMLLIST.parseXML
});
}, // end: init()
parseXML: function (xml) {
//Grab every single ITEM tags in the XML file
var data;
data = $('item', xml).get();
var i = 1;
//Loop through all the ITEMs
$(data).each(function () {
//Parse data and embed it with HTML
XMLLIST.insertHTML($(this));
i++;
});
}, // end: parseXML()
insertHTML: function (item) {
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('image').text();
var title = item.find('title').text();
var html;
//Embed them into HTML code
html = '<div class="item">';
html += '<img src="' + image + '"><br>';
html += '<span class="contentsubtitle">' + title + '</span><br><br>';
html += '</div>';
//Append it to user predefined element
$(html).appendTo(XMLLIST.appendTo);
}, // end: insertHTML()
}
//Run this script
XMLLIST.init();
I hope my code is correct. Had no data to test with, but I think the idea of it should be a bit more clear.
edited: Now working, version after receiving xml test-data
<html>
<head>
<title>asdasd</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
</head>
<body>
<div id="list">
</div>
<script>
XMLLIST = {
dataToLoad: [
'test.xml'
],
loadedData: [],
appendTo: '#list',
rand: function() {
return new Date().getTime();
},
loadData: function(file) {
$.ajax({
type: "GET",
url: file + "?" + XMLLIST.rand(),
dataType: "xml",
success: XMLLIST.parseXML,
error: function(r) {
console.error(r);
}
});
},
init: function () {
XMLLIST.dataToLoad.forEach(function(file) {
XMLLIST.loadData(file);
});
},
parseXML: function (xml) {
var data = $('item', xml).get();
$(data).each(function (i, value) {
var $value = $(value),
item = {
url: $value.find('url').text(),
image: $value.find('image').text(),
title: $value.find('title').text()
};
if (!XMLLIST.itemIsInList(item)) {
XMLLIST.loadedData.push(item);
XMLLIST.insertHTML(item);
}
});
},
itemIsInList: function(item) {
var hits = XMLLIST.loadedData.filter(function(value){
return XMLLIST.compareItem(item, value);
});
return hits.length > 0
},
compareItem: function(item1, item2) {
return item1.url === item2.url && item1.image === item2.image && item1.title === item2.title;
},
insertHTML: function (item) {
var html = '<div class="item">';
html += '<img src="' + item.image + '"><br>';
html += '<span class="contentsubtitle">' + item.title + '</span><br><br>';
html += '</div>';
$(html).appendTo(XMLLIST.appendTo);
}
};
XMLLIST.init();
</script>
</body>
</html>
You have a list, where you push your objects to. This list has a checkFunction "itemIsInList". Additionally you need a seperate check-function "compareItem", because indexOf won't work with objects
Managed to modify my original script by adding a masterArr for comparison of duplicated data received accross the 4 XMLs.
Here's the codes:
XMLLIST = {
//general settings
xml1: 'xml/structural_steel.xml?' + Math.random(0,1), //solve ie weird caching issue
xml2: 'xml/building_work_id.xml?' + Math.random(0,1), //solve ie weird caching issue
xml3: 'xml/shear_stud_welding.xml?' + Math.random(0,1), //solve ie weird caching issue
xml4: 'xml/custom_solution.xml?' + Math.random(0,1), //solve ie weird caching issue
appendTo: '#list', //set the id/class to insert XML data
//end general settings
masterArr: [],
init: function () {
//jQuery ajax call to retrieve the XML file
$.ajax({
type: "GET",
url: XMLLIST.xml1,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml2,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml3,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml4,
dataType: "xml",
success: XMLLIST.parseXML
});
}, // end: init()
parseXML: function (xml) {
//Grab every single ITEM tags in the XML file
var data;
data = $('item', xml).get();
var i = 1;
//Loop through all the ITEMs
$(data).each(function () {
//Check if masterArr[] already contains a duplicate of the item by checking using the XML label <image> or any other value/label that is unique.
//Insert into masterArr[] if not duplicate and publish HTML if not duplicate.
var string1 = $(this).find('image').text();
if( jQuery.inArray(string1, XMLLIST.masterArr) == -1){
XMLLIST.masterArr.push(string1);
//Parse data and embed it with HTML
XMLLIST.insertHTML($(this));
};
//If it reached user predefined total of display item, stop the loop, job done.
//if (i == XMLLIST.display) return false;
i++;
});
}, // end: parseXML()
insertHTML: function (item) {
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('image').text();
var title = item.find('title').text();
var html;
//Embed them into HTML code
html = '<div class="item">';
html += '<img src="' + image + '"><br>';
html += '<span class="contentsubtitle">' + title + '</span><br><br>';
html += '</div>';
//Append it to user predefined element
$(html).appendTo(XMLLIST.appendTo);
}, // end: insertHTML()
}
//Run this script
XMLLIST.init();
i am trying to fetch google contact list using contact api. i got the result and its showing in chrome and firefox console. i want to print the data in php. on the same page
<script type="text/javascript">
function auth() {
var config = {
'client_id': 'xxxxxxxxxxxxxxxxxxxxx',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
dataType: "jsonp",
success:function(data) {
//alert(JSON.stringify(data));
// display all your data in console
console.log(JSON.stringify(data));
}
});
}
</script>
i tried ajax but not worked. is there any best way to do it. JSON.stringify(data) is a array
You have nothing to do with PHP here. You are receiving a callback from $.ajax and the only way to show that data on ur page is to use JavaScript/jQuery.
See example below on how to parse $.ajax callback and .append() the data to some element on ur page:
<div id="contacts"></div>
function fetch(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
dataType: "jsonp",
success:function(data) {
$.each(data.feed.entry,function(){
$('#contacts').append('<div>Name: ' + this.title.$t + ' Phone: ' + this.gd$phoneNumber[0].$t + '</div>');
console.log('Name: ' + this.title.$t + ' Phone: ' + this.gd$phoneNumber[0].$t);
});
}
});
}
Note: if You need to parse ur data with PHP then You have to use curl.
Script:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
$.load("#BuildedBox")
}
});
}
build.php:
include_once("$_SERVER[DOCUMENT_ROOT]/db.php");
$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];
echo"$block_id - $building - $nick";
index.php:
<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a>
<div id="BuildedBox"></div>
seems my script wont work. what i have done wrong?
check this out
function buttonBuild(id, building, nick)
{
$.ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
/***************/
$("#BuildedBox").html(response);
/***************/
}
});
}
var weightd = $("#weight").val();
var user_id = 43;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
});
<div id="result1">Result div</div>
change $.load("#BuildedBox") to $("#BulderBox").html(response).
When you ask the script for data via ajax, the data provided gets into the "response" variable. As you want to write this data into the div, you must use the ".html" method.
Easier using "load" in this way:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
}
The "load" method loads data from the server and writes the result html into the element: https://api.jquery.com/load/
EDIT:
As #a-wolff says in the comment, to use POST in load, you should construct like this:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php",{
block_id:id,
building:building,
nick:nick
});
}
I have a problem with my code, it's a like button. It shows the number of likes. If user haven't voted yet (cookie) he can click and counter increases. Problem is counter doesn't update on first click (if i deactivate cookie check and vote several times) on next refresh is everything updated. It seems some count happens before insert in the backend. I suppose probem is in JavaScript, ajax post cross domain works but gives error that's why "error: setCookieAndUpdateButton()"
here is my frontend code:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<div><a id="like_button" href="#">Like</a></div>
<script>
var url = "http://thumbs-up.some-server.com/";
var appName = "next_test";
document.write("<script src=\"" + url + "jquery.cookie.js\"><\/script>");
$(document).ready(function(){
updateButton();
$("#like_button").click(function(){
if ($.cookie(appName + "_voted") == "true") {return;}
$.ajax({
type: "POST",
dataType: "json",
crossDomain: true,
url: url + "increase_counter.php",
data: {referrer: appName},
success: setCookieAndUpdateButton(),
error: setCookieAndUpdateButton()
});
});
});
function setCookieAndUpdateButton()
{
updateButton();
$.cookie(appName + "_voted", "true", {expires: 20*365});
}
function updateButton()
{
$.ajax({
type: "GET",
async: false,
contentType: "application/json",
dataType: "jsonp",
jsonpCallback: 'callback4jquery',
url: url + "get_counter_for_referrer.php",
data: {referrer: appName},
success: function (json) {
if ($.cookie(appName + "_voted") != "true"){
$("#like_button").html("<a id=\"like_button\" href=\"#\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</a>")
}
else{
$("#like_button").html("<span id=\"like_button\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</span>");
$('#like_button').unbind('click');
}
}
});
}
</script>
In first ajax call change your code like this:
success: setCookieAndUpdateButton,
error: setCookieAndUpdateButton
without () in both of them
I'm trying to convert the json result into xml type. However, it doesn't seems to work. Couldn't find out what's wrong. Please help.
The code is:
<script src="../Jquery Autocomplete/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../Jquery Autocomplete/jquery.json-2.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$(".openModalLink").click(function()
{
var start=$(this).parent().parent().find(".start").val();
var end =$(this).parent().find(".end").val();
$.ajax(
{
type: "POST",
url: "frmCollegeExamScheduleMst.aspx/ServerSideMethod",
data: "{'paraml': '" + start + "','param2': '" + end + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success:function(result)
{
var xmlDoc = $.parseXML(result);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var data = new Array();
var i =0;
$.each(customers, function ()
{
//do something
});
},
error: function(err) {
alert('Error:' + err.responseText + ' Status: ' + err.status);
}
});
});
});
When you specify dataType: "json" the response is converted to a JSON object and does not remain a string.
Try removing the parameter.
Try like this:
success: function(result) {
var xmlDoc = $.parseXML(result.d);
...
}
Notice the result.d. I guess your ASP.NET PageMethod looks like this:
[WebMethod]
public static string ServerSideMethod(string param1, string param2)
{
DataSet ds = ...
return ds.GetXml();
}
This string is JSON serialized. In order to retrieve it on the client the ASP.NET infrastructure adds the d parameter:
{"d":"some xml here"}
Another thing that you should absolutely change in your code is replace:
data: "{'paraml': '" + start + "','param2': '" + end + "'}"
with:
data: JSON.stringify({ param1: start, param2: end })
to ensure that your request parameters are properly JSON encoded. Think for example what will happen if start = 'foo\'bar'. You will end up with:
data: {param1: 'foo'bar', param2: 'baz'}
which as you can see completely breaks your JSON.
If the response from your AJAX request is xml then you should set it accordingly.
$.ajax({
data: {paraml: start, param2: end},
dataType: "xml",
success:function(result) {
var $xml = $(result);
}
});
No need for contentType nor concatenating in data.