I'm having as issue loading a localhosted json file. The url path is correct. I have no idea why it isnt working. IDeas would be lovely
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '../json/test.json',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var title = json.results[i].event;
var href = json.results[i].event;
var button =
"<button class='redirect-button' color='green' data-url='" +
href + "'>Compare</button>";
$("#apple").append("<tbody><tr><td>" + title +
"</td><td>" + button + "</td></tr></tbody>"
);
$("#apple").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
},
error: function(error) {
console.log(error);
}
});
Think u're using the wrong parametr on the $.parseJSON, cause u defined the json as the name of the return variable on the succes: function(json) and is using the not declared data as the variable to the parsing, try to replace it to $.parseJSON(json) instead, or change the sucess: function(json) to sucess: function(data)
Related
I am trying to implement a comment feature on my page. I have an itemID 123. on that page, I would like to display the comments that people have posted about itemID 123. However as of now, I am unable to display these comments on my page. There are no errors in the console.
Javascript:
function mywall() {
var url = serverURL() + "/viewwall.php"; //execute viewwall.php in the server
itemID = decodeURIComponent(getUrlVars()["itemID"]);
var JSONObject = {
"itemID": decodeURIComponent(getUrlVars()["itemID"])
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_mywallresult(arr); //success. execute _mywallresult()
},
error: function () {
validationMsg();
}
});
}
function _mywallresult(arr) {
var i;
//for all the shouts returned by the server
for (i = 0; i < arr.length; i++) {
//append the following:
//<b>
//time of posting </b>
//<br/>
//the message
//<br>
//userid
$("#wallcontentset").append("<b>" + arr[i].timeofposting + "</b><br/>" + arr[i].message + "<hr>" + arr[i].userid);
}
}
HTML:
<div data-role="content" class="ui-content" id="wallcontentset"></div>
Try the following :
success: function (response) {
_mywallresult(response.arr);
},
i'm showing a drop down list in a page based on the selection i have to show dependent drop down by passing the selected value in drop down list to the controller and return json data as response.please find below code and help me for resolving this .
Please find below ajax code
<script type="text/javascript">
jQuery(document).ready(function () {
$.ajax({
type: 'POST',
dataType : 'json',
contentType : "application/json",
url : "${home}getOPList",
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var operatorList;
// alert("yes");
// alert(str);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].listOfOperators);
operatorList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].listOfOperators +
"</option>"
}
$('#opList').html(operatorList);
},
error: function(){
alert('Error while request..');
}
});
$("#opList").change(function(){
$.ajax({
type: 'GET',
dataType : 'json',
contentType : "application/json",
url : "${home}partnerDetails?operator =" +opList,
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var partnerList;
alert("yes");
alert("oplist " + opList);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].campaignName);
partnerList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].campaignName +
"</option>"
}
$('#ptList').html(partnerList);
},
error: function(){
alert('Error while request in partners..');
}
});
});
});
</script>
above is the ajax code and when the code gest executed it is directly showing " Error while request in partners.. ".in console it says it is a bad request with 400 response code for the below url.
http://localhost/Promotions/partnerDetails
please suggest on this
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();
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'm having troubles using a global variable in my ajax response.
LastDate is a variable defined in the page I loaded into my second page. (function load_table)
I am able to acces the variable before the ajax call, but I can't seem to acces it in my ajax succes. because it gives undefined. <==== in code
my code:
var dia_date = {};
$(window).load(function()
{
DP("eerste keer")
load_table();
} );
function load_table()
{
DP('load_table');
$.ajax({
type: "POST",
url: "/diagnose_hoofdpagina/table_diagnose/" + DosierID,
success: function (data) {
$("#diagnoses_zelf").html('');
$("#diagnoses_zelf").append(data).trigger('create');
//initialize_table();
update_table();
},
error: function(){
alert('error');
}
});
return false;
}
function update_table()
{
if(LastDate > Datum)
{
alert("LasteDate" + LasteDate);
}
else
{
alert("Datum" + Datum);
}
alert('gast .... ' + LastDate); // <========== this is promted on the screen so there is no problem
$.ajax({
type: "POST",
url: "/refresh_diagnose/" + DosierID,
dataType: "json",
data : JSON.stringify(dia_date),
success: function (data) {
var DataDate = new Date(data.Year, data.Month, data.Day, data.Hour, data.Minute, data.Second);
alert('lastdate :'+ LastDate + 'date.date :' + DataDate);
//<============ BUT HERE HE GIVES LastDate AS UNDEFINED
},
error: function(data){
alert(data);
}
});
return false;
}
I can't see what I'm doing wrong. Can annyone help me plaese ? Thanks in advance.
You can try making a function.
var lastDate = #;
function getLastDate(){return lastDate;}
ajax.blablabla.success :{getLastDate();}