I have below output in json coming from a web method.
{"d":"[{\"id\":1,\"username\":\"deepak_nhm\",\"companyid\":4,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Deepak\",\"lastname\":\"Kerai\",\"avatarsmall\":\"/images_webdev/profile/634596544067649211654527189.jpeg\",\"company\":\"Orange\",\"CompanyRank\":1,\"OverAllRank\":3},{\"id\":2,\"username\":\"Mona_Co\",\"companyid\":1,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Mona\",\"lastname\":\"Sadhu\",\"avatarsmall\":\"/images_webdev/profile/AspNetForumAvatarguy35.jpg\",\"company\":\"3 Retail\",\"CompanyRank\":1,\"OverAllRank\":3}]"}
How do I render the above output, as the below attempt only returns 'undefined')?
<script type="text/javascript">
$(document).ready(function () {
GetProducts();
});
function GetProducts() {
$.ajax({
type: "POST",
url: "Default.aspx/GetContestants",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the ul's content with the page method's return.
var invoices = msg.hasOwnProperty("d") ? msg.d : msg;
var invoicesInList = [];
for (var i = 0; i < invoices.length; i++) {
invoicesInList.push("<li>" + invoices[i]["username"] + "</li>");
//console.log(msg.length);
}
$(invoicesInList.join("")).hide().appendTo("#ProductsList").fadeIn("slow");
}
});
}
</script>
Thanks in advance.
msg.d is actually json, so you have to decode it to use it as an object, something like
var invoices = msg.hasOwnProperty("d") ? JSON.parse(msg.d) : msg;
Related
The line which says it removes the markup doesn't completely and occasionally the text which gets displayed on the web page displays a 'rn' instead. I decided to skip removing the markup, but any attempt to remove or simplify the responseText.replace() function either gives me an error for the data.replaceAll() functions, or seems to do nothing. So how can I get the data to return with the markup and allow me to parse what I need?
var data = $.ajax({
type: "POST",
contentType: "application/json; charset=unicode",
url: '<%= ("Default.aspx/GetData") %>',
data: "{'fields': '" + fields}",
dataType: "json",
async: false
}).responseText.replace(/<\/?[^>]+>/gi, ''); //Remove markup
data = data.replaceAll("\\", "");
data = data.replaceAll("}}", "}");
data = data.replaceAll("{\"data\":", "");
data = data.replaceAll("{\"d\":", "");
data = data.replaceAll("]}", "]");
data = data.replaceAll("}}]\"}", "}]");
data = data.replaceAll("}]\"}", "}]");
I updated the code to the below and I am getting an error, "Uncaught SyntaxError: Expected ',' or '}' after property value in JSON at position 34" which is where dataset is defined. I played around with various combos of the replaces and it appears to be .replace("\", ""); is the one causing the issue, but I don't know why.
var data = $.ajax({
type: "POST",
contentType: "application/json; charset=unicode",
url: '<%= ("Default.aspx/GetData") %>',
data: "{'fields': '" + fields + "'}",
dataType: "json",
async: false
});
var json = JSON.stringify(data)
.replace("}}", "}")
.replace("{\"data\":", "")
.replace("{\"d\":", "")
.replace("]}", "]")
.replace("}}]\"}", "}]")
.replace("}]\"}", "}]")
.replace("\\", "");
var table = $('#dtable').DataTable();
table.clear().draw();
var i = 0;
var j = [];
var dataSet = JSON.parse(json);
$.each(dataSet, function (key, value1) {
$.each(value1, function (key, value) {
j[i] = value;
i++;
});
table.row.add([j[1], j[2], j[3], j[4], j[5], j[6], j[7], j[8], j[9], j[10], j[11], j[12]]).draw();
i = 0;
j = [];
});
HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);
Please can you help see the code. I would like to change the title name from 'Jason' to the temperature written in the JSON file.
var dataWithLabels = [
{
"title":"Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for(var i=0;i<1/*dataWithLabels.length*/;i++){
var statistic = data.current_observation;
dataWithLabels[i]['title']= statistic.temp_c;}}
//wanted to change Jason to the temperature written at the JSON file.Please help.
});
alert(dataWithLabels[0]['title']);
http://codepen.io/wtang2/pen/bEGQKP
It's NOT a duplicate, I am trying to replace the result from JSON file to title of dataWithLabels object
Since I don't know, if your JSON you are requesting is correct, I just assume it is. Still, if you like to see, what is happening in dataWithLabels after your Ajax-Request, you need to rewrite the function a little:
var dataWithLabels = [{
"title": "Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
var statistic = data.current_observation;
dataWithLabels[i]['title'] = statistic.temp_c;
alert(dataWithLabels[i]['title']);
}
}
//wanted to change Jason to the temperature written at the JSON file.Please help.
});
Now, the status of dataWithLabels is alerted AFTER you insert the statistic.temp_c. Your code always alerts the state BEFORE the Ajax-request.
Hope that helps!
This is because AJAX request works asynchronously so you need to alert the result only after the AJAX request is completed for that you can do
var dataWithLabels = [{
"title": "Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
var statistic = data.current_observation;
dataWithLabels[i]['title'] = statistic.temp_c;
alert(dataWithLabels[i]['title']); // Alert only after data is received
}
}
});
I have a javascript function
function TxEncrypt(event)
{ //perform encryption of token data, then submit the form like normal
//obtain public key and initial JSEncrypt object
var txPubKey = txJ$(".zwitch_encryptionkey").val();
var txEncrypter = new JSEncrypt();
txEncrypter.setPublicKey(txPubKey);
//get Data and encrypt it
var txData = '{}';
var txCryptData = '';
if(txJ$(".zwitch_data").length > 1)
{ //if there are more than one element with this class, convert it to json string
txData = txJ$(".zwitch_data").serializeObject();
txCryptData = txEncrypter.encrypt(JSON.stringify(txData));
}
else
{ //else, just encrypt the value
txData = txJ$(".zwitch_data").val();
txCryptData = txEncrypter.encrypt(txData);
}
dataString = txCryptData; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
alert(dataString);
}
I could get the value of dataString.But the ajax parrt is not working.I have added the jquery library.But doesnt seem to work
What's the error you are getting?
I think this should be:
$.ajax({
type: "POST",
url: "tokenize.php", //removed the dot
.....
Sorry this must be a very simple question.
on the following code
var myFunction = function (city){
var totaljobs =null;
$.ajax({
url: "/EN/taleo/GetTotalJobs",
type: 'GET',
contentType: 'application/json',
dataType: 'json',
cache: false,
data: { value: city },
success: function (result) {
var JobsHTML = "";
for (count = 0; count < result.length; count++) {
JobsHTML += "<p>" + result[count]["JobTitle"] + "</p>"; //your fields here
}
totaljobs = JobsHTML;
/* alert(totaljobs);*/
}
});
return totaljobs;
}
i am trying to return the totaljobs value with all the jobHTML info. But all I am getting is NULL. Can someone tell me where I am going wrong.
Many thanks in advance
Hesh
You need to make a synchronous call to the service.
try using this option :
async : false
This might work..