Unable to display results using jquery ajax - javascript

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

Related

.html() not displaying fields

I am currently trying to use .html() to display out the resident id, name and telephone number. However, there is nothing appearing on my page. When I check my console for any errors, there were none. There is no error with the php and residentid is in the localstorage.
html
<div role="main" class="ui-content" id="main-ui">
<div id="txtresidentid"></div>
<div id="txtresident_name"></div>
<div id="txtresident_telephone_home"></div>
</div>
javascript
(function () {
var residentid;
var resident_name;
var resident_telephone_home;
$(document).ready(function () {
getProfile();
});
function getProfile() {
var url = serverURL() + "/getresidentprofile.php";
var JSONObject = {
"residentid": localStorage.getItem("residentid")
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getProfileResult(arr);
},
error: function () {
validationMsg();
}
});
}
function _getProfileResult(arr) {
residentid = arr[0].residentid;
resident_name = arr[0].resident_name;
resident_telephone_home = arr[0].resident_telephone_home;
$("#txtresidentid").html("Residentid : " + residentid);
$("#txtresident_name").html("Name: " + resident_name);
$("#txtresident_telephone_home").html("Telephone(Home): " + resident_telephone_home);
}
})();
Try this:
$("#txtresidentid").append("Residentid : " + residentid);
$("#txtresident_name").append("Name: " + resident_name);
$("#txtresident_telephone_home").append("Telephone(Home): " + resident_telephone_home);

load local json file issues

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)

How to correctly post data with ajax into div?

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

Variable not accesable in ajax response

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

Populate dropdown with json data

I am trying to populate a dropdownbox with data from a JSON page.
Here is the code I am using:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data
});
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
});
</script>
And here is what the json data returns:
{"d":"{\"16\":\"hello\",\"17\":\"world\"}"}
I am getting an error that "data is undefined." Do I have to somehow tell JQ how to read the json data?
Firstly, the data variable you are passing to the ajax call is not defined (well, not in the code sample you provided), and secondly the ajax call is happening asynchornously, so you need to do something with the returned data, i.e. via a success callback. Example:
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
also you shouldn't need to parse the data returned from the ajax call, as jQuery will automatically parse the JSON for you, ( should need the $.parseJSON(data.msg))
EDIT
Based on the interesting format of the JSON, and assuming that it cannot be changed, this should work (ugly though)
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
data = data.d.replace(/{/g, '').replace(/}/g, '').split(',');
var obj = [];
for (var i = 0; i < data.length; i++) {
obj[i] = {
value: data[i].split(':')[0].replace(/"/g, '').replace('\\', ''),
label: data[i].split(':')[1].replace(/"/g, '')
};
}
var htmlToAppend = "";
for (var j = 0; j < obj.length; j++) {
htmlToAppend += '<option value="' +
obj[j].value +
'">' + obj[j].label +
'</option>';
}
$('#taxList').append(htmlToAppend);
}
});
});
You need to use the success option to return the data.
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
success: function(data){
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
</script>

Categories