I have a set of json data which is generated in php with json_decode function, here is the results:
I then create a html document and try to call the result using jquery $.getJSON:
var apiSrc = 'http://localhost/api/ws-data';
var showData = $('#result');
$(function(){
$.getJSON(apiSrc, function(data) {
console.log(data);
var items = data.blog.map(function (item) {
return item.key + ': ' + item.value;
});
showData.empty();
if(items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
showData.text('Loading...');
});
and the results for above is:
REST - Get JSON from PHP file on the server side
undefined: undefined
undefined: undefined
undefined: undefined
undefined: undefined
..
Its shown the key and value as undefined: undefined
What's goes wrong in the script?
I think you should access the correct properties such as pid,category etc of response,
var items = data.blog.map(function (item) {
return item.pid + ': ' + item.category;
});
Related
I am trying to make a nested menu from 3 json files, but In the first step I stuck, it return nothing:
var json = {};
$.getJSON("/api/category.json", function(data){
json.category = data;
});
$.getJSON("/api/subcat.json", function(data){
json.subcat = data;
});
$.getJSON("/api/subsubcat.json", function(data){
json.subsubcat = data;
});
$.each(json, function(i,v) {
console.log(json[i]); // it return nothing
});
But when I tried console.log(json) it return object, but even when I get console.log(json.category) It return nothing, no error in console log.
If I solve this issue I want to make a nested menu with this three json file in a loop, something like this:
var obj = '';
$.each(json.category, function(i, v) {
obj += '<li data-id="' + data[i]['id'] + '">' + data[i]['name'] + '<ul>';
$.each(json.subcat, function(i, v) {
if (json.subcat["cat_id"] == json.category["id"]) {
obj += '<li data-id="' + data[i]['id'] + '">' + data[i]['name'] + '</li>';
}
});
obj += '</ul>';
// also subsub cat
$('.simulate-cat').append($(obj));
});
<ul class="simulate-cat"></ul>
Is this way right to make nested menu?
Thanks in advance
Problem is that you're not waiting for the requests to complete. Because of that json properties aren't populated yet
It should look like this
$.when($.getJSON("/api/category.json"), $.getJSON("/api/subcat.json") , $.getJSON("/api/subsubcat.json")).done(function( a1, a2, a3 ) {
json.category = a1[0];
json.subcat = a2[0];
json.subsubcat = a3[0];
// create menu here
});
See $.when for more info about how to wait for multiple async callbacks
I have a ajax call on my function
js part
_this.ajaxPost(appUrl + "reports/appointment/save", post_str, function(response) {
var res = eval("(" + response + ")");
if (!res.error) {
var data = res.msg;
} else {
if (res.status == "error") {
_this.showPopMsg("error", 'Error when updating db ', res.msg);
}
}
}, function(response) {
alert(response);
var res = eval("(" + response + ")");
_this.showPopMsg("error", 'Updating DB', res.msg);
});
php part
echo json_encode(array("error"=> false, "status"=>"success", "msg"=>$conditions['reg']->result()));
which returns a response like,
{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}
and I'm trying to extract the msg part using js, the msg part contains an array like
[{"name":"dream hunter","mob_num":"9876543210","email":"afl#thnfgd"}]
and here name,mob-num and email are keys and I'm trying to extract their values
I have tried
var res = eval("(" + response + ")");
var data = res.msg;
alert(data[name]);//which is the first key
which is not working. How can I extract this?
Assuming you have the following response:
var x = '{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}'
Using JSON.Parse you can extract the object:
var y = JSON.parse(x);
Now you have an object like this:
{
error:false,
msg: [{
email: "afl#thnfgd"
mob_num: "9876543210"
name: "dreamhunter"
}],
status:"success"
}
To access the properties, such as the email for example, of the first message you can do this:
console.log(y.msg[0].email);
var x = '{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}'
var y = JSON.parse(x);
console.log('msg[0].email: ', y.msg[0].email);
You can view the data using :-
alert(data[0].name);
Use the JSON object methods to handle JSON in javascript.
For instance
var data = JSON.parse('{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}')
alert(data.msg[0].name)
I have the following code in my razor view, I need to set some javascript variables to set the value coming from razor.
However the values of the variables are not being set.
var listPuntos =[];
function onSelect(e) {
var dataItem = this.dataSource.view()[e.item.index()];
#{
var proveedorID = 0;
<text>proveedorID = dataItem.ProveedorID</text>
var list = new UnitOfWork().PuntosVentaProveedorRepository.Get().Where(x => x.ProveedorID == proveedorID);
proveedorID = 0;
<text>listPuntos = list; </text>;
<text>
var displayText;
$.each(listPuntos, function (key, value) {
if (displayText == undefined)
displayText = value.Nombre + ', ';
else
displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);
</text>
}
}
Given your concrete example, I would start by reducing the number of <text> blocks needed by instead just wrapping the shorter C# bits with #{ … }. This improves readability & lessens confusion. For example:
var listPuntos =[];
function onSelect(e) {
var dataItem = this.dataSource.view()[e.item.index()];
#{ var proveedorID = 0; }
proveedorID = dataItem.ProveedorID;
#{ var list = new UnitOfWork().PuntosVentaProveedorRepository.Get().Where(x => x.ProveedorID == proveedorID); }
proveedorID = 0;
listPuntos = #Json.Encode(list);
var displayText;
$.each(listPuntos, function (key, value) {
if (displayText == undefined)
displayText = value.Nombre + ', ';
else
displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);
}
Next, to inject a C# value into JavaScript code being emitted by the server, you need to encode the value in JavaScript. The best way to do this is to convert it into JSON. This is done above using Json.Encode. In particular, the line reading:
listPuntos = #Json.Encode(list);
I've used Json.Encode but of course you are free to use whatever JSON library du jour that fits your project.
you should separate html code and javascript code.
First at all, don't call any server code from View when View is loading. Push all necessary arrays etc via model property in appropriate format (i.e. in json format) and then fill any client list from value of that property.
Secondly - move code like it :
var displayText;
$.each(listPuntos, function (key, value) {
if (displayText == undefined)
displayText = value.Nombre + ', ';
else
displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);
to appropriate section, like it:
#section scripts
{
<script>
.....
</script>
}
I would like to ask how could I convert the following $.getJSON() to $.ajax() please.
I have a set of arrays from var googleApi like this:
Array [Object, Object, Object, Object, Object]
// if stringified
[{"id":"0","name":"user1","type":"mf","message":"bonjour user1"},
{"id":"1","name":"user2","type":"ff","message":"hello user2"},
{"id":"2","name":"user3","type":"mm","message":"konnichiwa user3"},
{"id":"3","name":"user4","type":"mf","message":"ni hao user4"},
{"id":"4","name":"user5","type":"ff","message":"high 5! user5"}]}
I would like to ask how could I identify if the value of a declared variable (eg. content with the value of user1) is the same as a value within the list of name keys in the array?
Below is my attempt and you might find my full code in $.getJSON() here:
$.getJSON():
var googleApi = 'https://api.com/url_here';
$.getJSON(googleApi, function(json){
console.log(JSON.stringify(json));
var item = json.result.find(function(e){
return e.name == content;
}) || json.result[0];
console.log("PRINT ID: " + item.id);
var name = item.name || content;
$('#nameText').text(name);
console.log("Name: " + name);
});
Below is my attempt on $.ajax() but I got an error of "TypeError: data.result is undefined";I have also tried using $(this) to replace data.result but without luck... it would be very nice if someone could identify what have I done wrong please:
var googleApi = "https://sheetsu.com/apis/v1.0/f924526c";
var googleKey = "0123456789";
var googleSecret = "987654321";
var data = [];
$.ajax({
url: googleApi,
headers: {
"Authorization": "Basic " + btoa(googleKey + ":" + googleSecret)
},
data: JSON.stringify(data),
dataType: 'json',
type: 'GET',
success: function(data) {
console.log(data);
var item = data.result.find(function(e){
return e.name == content;
}) || data.result[0];
console.log("PRINT ID: " + item.id);
var name = item.name || content;
$('#nameText').text(name);
console.log("Name: " + name);
});
Merci beaucoup :))) x
...how could I identify if the value of a declared
variable ... is the same as a value
within the list of name keys in the array?
As per your provided response object you could iterate through it and check the values against your variable content:
var content = "user1";
$.each(response, function(i, v) {
if (v.name == content) {
console.log(v.name);
}
});
Example Fiddle
As for the second part of your question:
but I got an error of "TypeError: data.result is undefined";
The reason you may be getting your error is because find is expecting a jQuery object, you have received a JSON object back from your endpoint, so using dot notation as above will should work as well:
success: function(data) {
$.each(data, function(i, v) {
if (v.name == content) {
console.log(v.name);
}
});
}
You can see the answer to this question for a bunch of awesome information on how to access / proccess objects.
Also note your success callback in your code above is not closed, which will create errors.
function getID(name){
$.each(data,function(key,value){ //value = object.value (name)
$.each(value,function(key1,value1){ //value1 = user name (actual names in array)
if(value1 == content){
console.log(value.id);
var name = value.name;
$('#nameText').text(name);
console.log("Name: " + name);
return;
}
});
});
}
getID(data);
return false;
I am getting following json from php
{"status":{"message":"success","undeleted":[],"code":200}}
{"status":{"message":"success","undeleted":[{"id":7844118,"error":"This Document already Published"}],"code":200}}
I just want to check 'undeleted' is empty or not in jquery.If not empty,I need to take every ids and its error message from 'undeleted'.I am not getting an idea how to do this .I will get only one at a time.
Thinking about something like this
var result = jQuery.parseJSON(data);
$.each(result.data, function(index, value) {
});
I have done something like this but not getting desired answer
var result = jQuery.parseJSON(data);
$.each(result.status, function(index, value) {
alert(value);
});
Here is how to do it:
http://jsfiddle.net/2zLby4r8/3/
var result = jQuery.parseJSON('{"status":{"message":"success","undeleted":[{"id":7844118,"error":"This Document already Published"},{"id":999999,"error":"New Errr"}],"code":200}}');
if (result.status.undeleted.length > 0) {
$.each(result.status.undeleted, function(index, value) {
alert("ID: " + value.id);
alert("Error: " + value.error);
});
} else {
alert("blank");
}