Converting list of objects to a JSON string - javascript

UPDATE: It was a programming error, please don't post answers. This question will be deleted. If you've already posted an answer please delete
I'm trying submit a form using jQuery and ajax. One of the fields is a list of objects, like this:
data = [{"id":1},{"id":2}]
I usually use JSON.stringify(data) but that didn't work this time, the server gets [object Object],[object Object]
When I do alert(JSON.stringify(data)) it works but something is changing it back to objects.
I'm using the jQuery form plugin and appending this data to the data attribute of the options object:
function showRequest(formData, jqForm, options) {
return true; //does nothing
}
var options = {
beforeSubmit: showRequest,
url: '/search.php',
iframe: true,
iframeTarget: '#iframe',
type: 'post'
};
options.data.data = JSON.stringify(data);
$('#myForm').ajaxSubmit(options);
How do I convert this to a JSON string that I can send it to the server?

This can be done using jQuery and without using JSON libray.
example using php on back-end
var data = [{"id":1},{"id":2}];
$.ajax({
type : 'POST',
url : 'test.php',
data: {my_array:data},
success : function(data){
//alert(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//alert("error");
}
});
in php
$my_array= $_REQUEST['my_array'];
print_r($my_array);
it will print
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 2
)
)

Related

Data is empty when passing a variable from JS to PHP with Ajax

I'm trying to pass a simple string variable with an onclick event, the request is successful but I get an empty response on the console, and the xvar variable is no coming through so I get the "NO DATA" p tag. This is my first time using Ajax so I tried to make it very simple to start. Here's my code:
JS
var xvar = 'D';
$('.test').click( () => {
$.ajax({
data: { xvar : xvar },
type: "POST",
url: 'test.php',
success: function(data, textStatus, XMLHttpRequest)
{
console.log('Success: '+data)
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("The request failed."+errorThrown);
}
});
});
test.PHP
$xvar = (isset($_POST['xvar'])) ? $_POST['xvar'] : '<p>NO DATA</p>';
echo $xvar;
I'm using JQuery 3.5.1 that is included with Wordpress. I'll appreciate any feedback.
EDIT
I managed to get the response on test.php as seen
here:
But I when I try to render the value with print_r is not shown.
$res = $_POST;
print_r($res);
On the data of your Ajax, try to add the quotes in the key of the data. Like this:
data: { "xvar" : xvar },

Can not get item of JSON-response

I am trying to create a AJAX call - and I would like to work with the response.
This is my response I see in my browser's network console:
{
"message": "success",
"file": "dump.xml"
}
And this is what I want to do:
onComplete: function onComplete(data) {
var vm = this;
console.log(data.file);
this.$set('upload', data);
this.$set('filename', file);
this.modal.show();
}
Okay. Well - I'm getting a response and if I write data to console.log, I'm getting this:
{"message":"success","file":"dump.xml"}
But if I try to do:
console.log(data.file);
I'm getting undefined. But why?
You are receiving it as a string. You have to parse it first to JSON by:
data = JSON.parse(data);
console.log( data.file )
OTHER OPTION: Or you can define it on request, add dataType: "json" so that you will receive json.
Like:
$.ajax(
{
type: "POST",
dataType: "json",
url: url,
data: {},
success: function( response ) {}
}
I think the problem is that data is a JSON string, so it will be printed in console, but when you call data.file it will be undefined. as string doesn't have a file property.
You need to parse your data object, before accessing file property:
data = JSON.parse(data);
console.log(data.file);
Most probably your data will be a JSON string. You have parse it into an Object like below
onComplete: function onComplete(data) {
data = JSON.parse(data)
var vm = this;
console.log(data.file);
this.$set('upload', data);
this.$set('filename', file);
this.modal.show();
}

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

Sending JSON array to webservice from Google Sheet Script

We have a webservice that returns product information. The service expects a JSON array in the post data... The
A sample script from a simple HTML test web page is as follows (this works as expected):
&ltscript src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// request is array of product IDs e.g. pid:[71,72,74]
// request is array of search terms e.g. find:['apples','oranges','pears']
// request can contain requested fields from products
// fields:['CostPrice','Published','title','Price']
jQuery.ajax({
url : 'http://somewebsite.com/__getProductData',
type: 'POST',
dataType : 'json',
data: { pid:[658,71,6,700], fields:['pid','CostPrice','type','published','title'] },
success:function(data) {
// do something with the response...
});
},
error: function( jqXHR, textStatus, errorThrown) {alert('Error Status:' + textStatus + ' Error:'+errorThrown); }
}
);
});
</script>
The web service, written in PHP, receives this correctly. Dumping (print_r) the data received by the web service from the client results in the following array:
Array (
[pid] => Array ( [0] => 658 [1] => 71 [2] => 6 [3] => 700 )
[fields] => Array ( [0] => pid [1] => CostPrice [2] => type [3] => type [4] => published [5] => title )
Now to the problem.... I'm trying to call the webservice from a Google Sheet Script as follows:
function getProduct( pid,datetime) {
//
var url = 'https://somewebsite.com/__getProductData';
//pid:[658,71,6,700], fields:['pid','CostPrice','type','published','title']
var nids = new Array( 658,71,6,700 );
var fields = ['pid','CostPrice','type','published','title']
var payload =
{
pid : nids,
fields: fields
};
var options =
{
"method": 'POST',
"payload": payload
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
When the PHP web service is called from Google Sheets script the JSON array is not receive correctly:
Array ( [data] => { pid=[Ljava.lang.Object;#1bfbb500} fields=[Ljava.lang.Object;#3ffbb500})
I expect this is something associated with encoding or headers... I've tried most combinations of headers and contentType but to no avail.... e.g.
var headers = { "Accept":"json",
"Content-Type":"application/json",
};
Suggestions anyone?
var options = {
"method": 'POST',
"payload": JSON.stringify(payload)
};
Or stringify each of the values for pid & fields.
Jonathan - your suggested comment is the solution....
This didn't work:
var options =
{
"method": 'POST',
"payload": JSON.stringify(payload)
};
but stringify on the payload array elements worked (note that simple elements worked without stringify e.g. 'text' : "some text here") :
var nids = [658,71,6,700 ];
var fields = ['pid','CostPrice','type','published','title']
var payload =
{
pid : JSON.stringify(nids),
fields: JSON.stringify(fields)
};
var options =
{
"method": 'POST',
"payload": payload
};
I thinkg I have solved the same issue:
How to send a post request with an array in payload by urlfetchapp
the payload has to be prepared in this way! I have found this solution during I was making a workaround PHP script.
var payload =
{
"fields[0]":"firstString",
"fields[1]":"anotherString in array",
}
Not very intuitive, but it worked for me great!

Unable to get value from json object

I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id

Categories

Resources