Sending a multi-level javascript object to the server with AJAX fails - javascript

I have a javascript object that looks somthing like this:
var obj = {
"name": "username",
"userid": "9999",
"object1": {
"subObject1": {
"subArray1": [],
"subArray2": []
},
"subObject2": {
"subArray3": [],
"subArray4": []
}
},
"object2": {
"subObject3": {
"subArray5": [],
"subArray6": []
}
},
"array1": [],
"array2": []
};
I have tried to use a jQuery ajax call like this:
$.ajax({
url: "test.php",
type: "POST",
dataType: "text",
processData: false,
data: obj,
success: function(data, status) {
alert("Sucsess");
}
});
The problem is that PHP doesn't receive anything. The $_POST variable is empty. I'm not sure what I'm doing wrong.
Thanks

First, include JSON2.js (Link at bottom of that page) on the page, then change your call to this:
$.post(
"test.php",
data: JSON.stringify( obj ),
function(data, status) {
alert("Sucsess");
});

Try out jQuery 1.4.1 the $.param function was completely rewritten to support things like this.

Why not send it by using something like the json2 library to serialize the whole object as JSON, then send that via a single parameter? I don't know PHP but I would be stunned if there weren't dozens of alternative JSON parsers available.

I don't believe it is possible to send a data object like that.
If you wanted to do something like that you would have to serialize it before you send the data and then unserialize at the server. HTTP has it's limits.

Related

Trouble receiving JSON data from nodejs application?

The below jQuery ajax method makes a call to node.js application that returns a json formatted data. I did check the console and it returns the json in this format
{ "SQLDB_ASSIGNED": 607, "SQLDB_POOLED":285, "SQLDB_RELEVANT":892, "SQLDB_TOTSERVERS":19}
However, when i try to access the element using the key name i get "undefined" on the console ?
Nodejs
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Jquery Ajax
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data);
for(var i in data)
{
console.log(data[i].SQLDB_ASSIGNED+"---"+data[i].SQLDB_POOLED+"---"+data[i].SQLDB_RELEVANT+"---"+data[i].SQLDB_TOTSERVERS );
}
}
});
Your Node.js part is very weird. You are stringifying a string:
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Why not just this? That's probably what you are looking for:
res.send(JSON.stringify({
SQLDB_ASSIGNED: assigned_tot,
SQLDB_POOLED: pooled_tot,
SQLDB_RELEVANT: relevant_tot,
SQLDB_TOTSERVERS: servertotal
}));
And then in the callback just this:
data.SQLDB_ASSIGNED; // Here you go
I don't know why you are iterating over the keys of the json. You want this:
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
So the code would be:
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
}
});
You seem to be treating the data variable as an array of objects, containing the keys you specify. I guess what you would like to do is this:
for(var key in data) {
console.log(key+": "+data[key]);
}
Or what?

How to use a JavaScript to load and parse a static JSON file in the server

I'm just starting to use javascript and json.
I need to read data (getInformation function) from a json file when processing an event in a javascript function. So I need it to be synchronic. I don't know if I am missing something in the code, or if I have to create an Request and handle the callback, or if I need to import additional javascript to use json. Because I don't know how to make it work. It doesn't work because at the end the array is empty. Any help is aprreciated.
The json file:
{"Users": [
{"Name": "Jane",
"Points": 67,
"age": 23},
{
"Name": "Sam",
"Points": 65,
"age": 21}
]}
Option 1 - Function called by another function which is processing an event:
var getInformation = function()
{
var path = "./data/users.json";
var informationArray= [];
console.log("Loading ....");
$.getJSON(path, function(data)
{
$.each(data, function(key, val)
{
informationArray.push(key + '-' + val);
});
});
return informationArray;
}
Option 2 - Function called by another function which is processing an event:
var getInformation = function() {
var path = "./data/users.json";
var informationArray= [];
$.ajax({
url: path,
async: false,
dataType: 'json',
success: function(response) {
$.each(response.items,
function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
return informationArray; }
I have seen the following thread and tried what is there but doens't work for me. I would like to know where is the problem in my code or if require any special configuration.
Thread: Is there a version of $getJSON that doesn't use a call back?
When JavaScript is running in a browser it needs to make an AJAX request to the server to access a JSON file. It is possible to write the AJAX request by hand but that is complex and difficult to make work in all browsers. Instead most people use a library like jQuery. You will need to include jQuery in your web page with something like:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
Then in any script tag lower in the html page you should be able to do something like:
$.ajax({
url: "data/users.json",
dataType: "json",
success: function(response) {
$.each(response.Users, function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
see http://api.jquery.com/jQuery.ajax/
To load a JSON file (and not require a callback) you'd use:
var url = 'http://yoursite.com/data/users.json';
var j = [];
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) { j = data;},
async: false
});
alert(j.Users[0].Name);

Fetching JSON data from a URL in javascript?

I am trying to retrieve data from a URL of the form http://www.xyz.com/abc.json.
I have been trying to achieve this using the $.ajax method in the following manner.
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://www.xyz.com/abc.json.",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
However I am being unable to get this to run. I need to loop through the retrieved data and check for some specific conditions. This could have been achieved easily with the $.getJSon if the json data had a name to it, however the file is of the form:
[{
"name": "abc",
"ID": 46
}]
because of which I have to effectively convert and store it in a Javascript object variable before I can use it. Any suggestions on where I might be going wrong?
It looks like you will want to convert that data response to a json object by wrapping it with { } and then passing that to the json parser.
function (data) {
json = JSON.parse("{\"arr\":"+data+"}").arr;
}
Then to get your data, it would be
json[0].name //"abc"
So your question is how to convert a string to Json object?
If you are using Jquery you can do:
jQuery.parseJSON( jsonString );
So your return should be:
return jQuery.parseJSON( json );
You can read documentation here

Send array with $.post

I'm trying to execute a $.post() function with an array variable that contains the data, but it seams that I'm doing something wrong because it won't go or it's not possible
var parameters = [menu_name, file_name, status, access, parent, classes];
console.log(parameters);
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json'); //Doesn't work
Firebug debug: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument
So, which would be the propper way of doing it (if possible)?
i am using for such kind of issues always the $.ajax form like this:
$.ajax({
url: 'do.php',
data: {
myarray: yourarray
},
dataType: 'json',
traditional: true,
success: function(data) {
alert('Load was performed.');
}
});
the traditional is very important by transfering arrays as data.
Could be the variables in the parameters array
Having ran your code and supplemented the parameters for something like:
var parameters = ['foo','bar'];
It seems to work fine. I think the problem must be in the variables that you are passing as part of the array. i.e. are menu_name, file_name, status, access, parent and classes variables all as you expect them to be? e.g. console log them and see what they are coming out as. One might be an object which doesn't convert to json.
Use JSON.stringify()
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
$.post('do.php', {
OP: 'new_menu',
data: JSON.stringify(parameters)
},
function(result) {
console.log(result);
},
'json'
);
And then, in the server-side use json_decode() to convert to a php array.
http://php.net/manual/es/function.json-decode.php
Ok, so with the help of these StackOverflow fellows I managed to make it work just the way I wanted:
var parameters = {
'name': menu_name.val(),
'file': file_name.val(),
'status': status.val(),
'group': group.val(),
'parent': parent.val(),
'classes': classes.val()
};
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json');

Pass objects in ajax request

I need to pass objects in ajax request in order to "PUT" files or data to my rest service. How can i do it? Thank you.
update
i have this code:
var invoice = {};
invoice.POSWorkstationID = "POS7";
invoice.POSClerkID = "admin";
invoice.CustomerName = "Alice in Wonderland Tours";
invoice.IsFreightOverwrite = true;
should i do this:
parameter = "{BillToCode:"+invoice.CustomerName+",POSWorkstationID:"+invoice.POSWorkstationID+",POSClerkID:"+invoice.POSClerkID+",IsFreightOverwrite:"+invoice.IsFrieghtOverwrite+"}";
and this:
data: JSON.stringify(parameter),
Normally, you can use jquery to do this may be like this:
$.ajax(
{
type: "PUT",
dataType: "json",
data:POSTData,
url: 'www.youurlhere.com/path',
complete: function(xhr, statusText)
{
switch(xhr.status)
{
//here handle the response
}
}
});
POSTData is the data in json format that u supply to the rest, you can turn an object into a json format by simply pushing the attributes but respecting JSON Format syntax
Take a look at jQuery post http://api.jquery.com/jQuery.post/
you have few options there:
$.post("test.php", $("#testform").serialize());
$.post("test.php", { name: "John", time: "2pm" } );
The best way to communicate client and server side is (IMHO) JSON.
You could serialize your object into json format, with this lightweight library =>
http://www.json.org/js.html
Look for stringify method.

Categories

Resources