AJAX Get from a JSON Tree - javascript

I'm just starting out with AJAX, trying to use JQuery's $.getJSON function (or any related, ie $.load(), $.ajax(), etc). I have a JSON file with a structure something like this:
[
{
"id": 1,
"email": "user#domain.com",
"password": "password"
},
{
"id": 2,
"email": "one#two.com",
"password": "password"
}
]
How can I call a GET on this JSON file (let's call it users.json) for a user with a specific email? I thought it would be the second paramter in $.getJSON, but that seems to just return the whole tree.
Thanks!

Short answer - you can't do this directly with AJAX. jQuery can extract portions of HTML and XML documents, but not JSON.
Easiest answer - retrieve the entire object (you have to, anyway) and use jsonpath to get the structure you want
Longer answer - retrieve the entire object, and traverse it yourself to get the object you want
Best answer - make the email address a parameter to whatever script produces the json and have the server only return the data you want.

Once the JSON is parsed, you pass it to a callback function - then you can manipulate that array however you need.
You'll probably want some custom code:
$.getJSON(myURL, function(data) {
/* data is an array of objects */
for (var i=0, j=data.length; i<j; i++) {
if (data[i].email === some_value) {
/* do something with data[i] */
};
};
});
http://api.jquery.com/jQuery.getJSON/

You can 1 of 2 things, loop through the array on the client side, or dynamically have users.json generated on each call (this assumes a backend server language like php)
Using dynamically generated json file
JS
$.ajax({
url:"/users.json.php",
data:{
useremail:"someusersemail#here.com"
}
type:"POST",
dataType:"json",
success:function(userdata){
//users data will be in userdata
console.log(userdata.email);
}
})
Server Script (assumes PHP): users.json.php
$email = $_POST['useremail'];
//get user data based on email
...
echo json_encode($userdata);
die;
generated json file should end up outputing something like
{"id": 1,"email": "user#domain.com","password": "password"}
Loop Method: loop through the users array on client side
$.ajax({
url:"/users.json",
dataType:"json",
success:function(data){
for(i=0;i<data.length;i++) {
var user = data[i];
if(user.email == "someemail#gmail.com") {
//do what you need to with user data
}
}
}
})

Related

NodeJS not able to process array of objects received via POST

I'm having this collection of objects which are inside a html text area:
{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...
...
Is there a way to send the whole collection to node js and iterate through it to get values of objects?
My AJAX code:
$.ajax({
type: "POST",
url: "https://example.com/nodeapp",
data: '['+document.getElementById("list").value+']',
success: function(data) {
console.log(data);
}
});
I tried to do a foreach on req.body, but it doesn't seem to work:
var arr = req.body;
arr.foreach(element=>{
console.log(element.email);
})
Gives the error:
TypeError: arr.foreach is not a function
At first , you have to parse the body by using JSON.parse() function .
Like this :
var arr = JSON.parse(req.body);
arr.forEach(element=>{
console.log(element.email);
});
The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .
I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:
'[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},
{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...]'
Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:
{
"<<the array in string format>>" : ""
}
How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)

Can't access JSON object sent to PHP via POST

I am sorry if this is a duplicate question. I have searched for an answer but nothing seems to work.
I am trying to send quite a large JSON object to a PHP file via POST.
This is my JavaScript code :
var grid =
{
"user": 1,
"grid": JSON.stringify(hz),
"week": WEEK,
"AP": AP,
"X_VAL": X_VAL,
"Y_VAL": Y_VAL
};
grid = JSON.stringify(grid);
$.ajax({
url:"php/saveGrid.php",
type: "POST",
data : "g="+grid,
success: function (data, textStatus, jqXHR)
{
console.log(data);
}
});
This is my PHP code :
$g = stripslashes($_REQUEST["g"]);
echo $AP = $g->AP;
But this returns an error which says :
Trying to get property of non-object
What am I doing wrong?
Your primary problem is that you are trying to treat a string of JSON as if it were a PHP object.
You need to parse it first.
$g = stripslashes($_REQUEST["g"]);
$g = json_decode($g);
echo $AP = $g->AP;
You also have some secondary issues.
You failed to URL encode the JSON, so if it contains characters with special meaning in URLS, it will break.
data : "g="+grid,
should be:
data : { g: grid },
You should not need to run stripslashes over input from $_REQUEST/POST/GET.
If you don't have magic quotes turned on, then it could break the incoming data if it contains slashes.
If you do have magic quotes turned on, then you should turn them off or upgrade to a modern version of PHP (which wouldn't support them).
Nesting JSON inside JSON is silly. It bloats the data and makes it more work to read.
"grid": JSON.stringify(hz),
should be:
grid: hz,
$_REQUEST could get data from the query string, or the request body, or a cookie. You know it is coming in the request body so just use $_POST to remove the ambiguity.
You need to decode the json object then can use it as an array. Try, json_decode. Like,
$g = stripslashes($_REQUEST["g"]);
$json_de=json_decode($g);
echo $AP = $json_de['AP'];
Or if you want to see the full array then use,
print_r($json_de);
Hope this will help you.

Using JSON to store multiple form entries

I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.

How to get data returned from Ajax appended to a div? -- JQuery + Rails 3.1

I'm trying to get data returned from a controller and append it to a div. Here is the code I have:
$(this).parent().find('list').append(__WHAT_GOES_HERE?__);
How should I get data to append using ajax in JQuery? I know this is a very basic question -- I'm new to JS :(
PS. Lets assume the controller's path is /ajax_get_items
I assume you want to load it into a class, so list would be .list
Something like:
$.ajax({
url: "/ajax_get_items",
type : "POST",
data : { // If you need data to be posted
id : 12,
num : "test"
},
success : function(result){
$(this).parent().find('.list').append(result);
// If a JSON object is returned, use the following line:
// $(this).parent().find('.list').append(result.html);
}
})
Or if you want to just load data without params (GET method):
$(this).parent().find('.list').load("/ajax_get_items");
If you want more information about ruby rails and jQuery: http://brandonaaron.net/blog/2009/02/24/jquery-rails-and-ajax
This is what you need:
$.ajax({
url: '/ajax_get_items',
success: function(data) {
$('#selector').parent().find('list').append(data)
}
});
Note that you can't use 'this' in this context depending on where this call is made, or you might end up with unexpected results
$('somelink').click(function(e) {
e.preventDefault();
$.ajax(url, data, success:function(resData) {
resultSet = resData.extract(resData);
}
}
Basically this part handles the response from the ajax call and extract is supposed to build up your required html from the returned data.
After this you can simply say
$(this).parent().find('list').append(resultSet);
But this assumes the major work is done in the function extract with the returned data.
There you build up your list (or whatever) html is needed.

how to add json data to the server and display it in the jqgrid right after a button clicked

i have a running program that will display my data from a server to the jqgrid. what i want now is to save data to the server. here's my code:
function Add(){
var datas = {
"ID": "xyz",
"operation": "Add",
"fields": ["code", "desc", "type"],
"values": [$('#code').val(), $('#desc').val(), $('#type').val() ]
}
$('#tblData1').setGridParam({
url:'myni.php?path=' + encodeURI('this/update') + '&json=' +(JSON.stringify(datas)),
datatype: Settings.ajaxDataType,
});
$('#tblData1').trigger('reloadGrid');
}
this codes returns an error message "Exception error: Server Error: Parameter 'operation' is not specified." i already set an operation and i don't know what went wrong. can somebody help me fix this? please.
i want to know how to add data to the server after clicking the button and display it in the jqgrid right away. Please...
The function Add set local variable datas which exist only inside of the Add function. Probably what you want is to return the value from the function and set to the variable existing in the scope of usage the setGridParam call.
The next problem is that you should encode JSON.stringify(datas) with respect of encodeURIComponent before inserting it as the part of URL. You can also use jQuery.param function instead:
url:'myni.php?' + $.param({path:'this/update', json:JSON.stringify(datas)})
If you use HTTP GET (mtype:'GET') for requests to the server I would recommend you better to use postData parameter of jqGrid which contain functions:
$("list").jqGrid({
url:'myni.php',
postData: {
path: 'this/update',
json: function() {
return JSON.stringify({
ID: "xyz",
operation: "Add",
fields: ["code", "desc", "type"],
values: [$('#code').val(), $('#desc').val(), $('#type').val()]
});
}
},
// other parameters
});
The properties of postData parameter will be added to the URL ('?' and '&' will be inserted if needed) in case of the usage of mtype:'GET' or to the body of the posted data in case of mtype:'POST'.
The advantage of the usage functions inside of postData is that the corresponding values (like the value of json parameter) will be calculated on every ajax request. If the user changes the sort order or chooses another page the ajax request to the server will be send. So in the case the postData properties must be determined and the current values from $('#code').val(), $('#desc').val() and $('#type').val() will be inserted in the request.
If the value of path parameter should not be static you can make it also as the function.
In case of usage postData which includes functions you code could be reduced to $('#tblData1').setGridParam({datatype: Settings.ajaxDataType}).trigger('reloadGrid').
More about the usage of functions inside of postData you can read here.

Categories