Sending Json Array in POST request for JavaScript - javascript

I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you

In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }

Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});

The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});

Related

Get Object XmlDocument value

I'm executing an ajax call to a external api (this cannot be modified) to upload an store a file into a folder. This request must return a path (ex. "C:\Doctos\File.pdf" but after a console.log is returning something like this:
#document < string xmlns="http://tempuri.org/">"C:\Doctos\File.pdf"
So my question is, what can I do to get only the text that I want without any change in the api (because I'm not able to do it).
Here is the ajax call that I'm using.
PD. This ajax call is using the provided structure for the dev team that developed the api so things like dataType also cannot be modified
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
var res = data;
//Returns above example
console.log(res);
//Returns something like <p>[object XMLDocument]</p>
$('#MyInput').attr('src', res);
}
});
I would use regular expressions to get the desired string from received data. Put this after success line.
var regex = />\"(.*)\"/;
var matched = regex.exec(data);
var result = matched[1];
console.log(result);
The regex matches the last quoted string in your example.
You can get the data in the xml with jQuery
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
// Get the contents of the xml
var file = $(data).find('string').text();
$('#MyInput').attr('src', file);
}
});

Javascript object properties undefined after ajax request

I've made an ajax call which has returned a json string from a .Net JsonConvert.SerializeObject() call, the json is automatically parsed into an object at the browser but I am currently unable to access the properties without "undefined" being returned.
My current json string being returned is (removed bulk of byte array):
"[{\"filename\":\"\",\"size\":6,\"csize\":\" 5.85 KB\",\"extfile\":\"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA....AAAAAAAAAAAf//Z\"}]"
I've validated this and it's all fine.
My javascript is:
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != null) {
$("#ImgItem").attr("src", "data:image/png;base64,'" + data.extfile + "'");
}
}
});
}
I have made sure it is definitely an object. I've tried accessing as data.extfile, data["extfile"], passing extfile in as a byte array and then accessing that but it is always coming up as "undefined". In desperation I even tried accessing indexes, iterating through the object etc. and still nothing.
I have a feeling that there is an issue in the json string which is preventing it from converting properly but I can't see it as I haven't worked much with json. Could someone point out where I'm going wrong?
Solution
Javascript was parsing the response into an object with a single property "data.d", parsed data.d and that created the object correctly.
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != null && data.d != null) {
let imgData = JSON.parse(data.d);
$("#ImgItem").attr("src", "data:image/png;base64," + imgData[0].extfile);
}
}
});
}
basically if the string that you pasted is the response (data), when using JSON.parse() it converts into an array , so you should use it like that.
const stringResponse = "[{\"filename\":\"\",\"size\":6,\"csize\":\" 5.85 KB\",\"extfile\":\"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA....AAAAAAAAAAAf//Z\"}]"
const parsedResponse = JSON.parse(stringResponse);
console.log(parsedResponse)
const entry = parsedResponse[0];
console.log(entry.extfile)
so basically, you need to do:
data[0].extfile
Since the console.log(data) statement returns:
{d: "[{"filename":"","size":6,"csize":" 5.85 KB",…AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf//Z"}]"}
The data you are actually trying to obtain is contained in a JSON string contained in the d property of the data received. If you were to parse the string and then access the extfile property you would have your data:
var actualData= JSON.parse(data.d);
var extfile = actualData[0].extfile;
Don't know if this will help but here it is:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
http://api.jquery.com/jquery.ajax/
Also the data is an Array, maybe grab the first object in the array data[0].extfile.
I'm thinking it maybe reworked as such:
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8"
}).done(function(data){
if (data != null) {
$("#ImgItem").attr("src", "data:image/png;base64,'" +
data[0].extfile + "'");
}
});
}

Using jquery to parse items from a JSON response

I am using PHP and Ajax to parse some JSON. The PHP is creating the array like this.
$myObj->pid = $_POST["parentid"];
$myObj->comp = $comp;
$myObj->colour = $statuscolour;
$myJSON = json_encode($myObj);
header('Content-Type: application/json');
echo $myJSON;
I use the following jquery code
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var response = jQuery.parseJSON(JSON.stringify(msg));
console.log(response);
pid = response[0].pid;
console.log('id = ' + pid);
});
I can see the output from the first console.log as
Object {pid: "p1", comp: 20, colour: "red"}
However I cannot extract the individual variables, it gives the message
Uncaught TypeError: Cannot read property 'pid'
How can I extract the variable?
You've made this more complicated than it needs to be. msg is already an object, which you then convert to a string and back to an object with stringify and parseJSON. And then you try to use it like an array, when it is an object.
Try this:
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var pid = msg.pid;
console.log('id = ' + pid);
});
You are returning an object, not an array.
Also it makes no sense to stringify the data object and parse that string back to object again
Try
var pid = msg.pid;
console.log('id = ' + pid);
First of all, it can't imagine why it would be neccessary to first stringify, then parse the JSON response.
Second, you are trying to access response[0] as if it were an array, which it isn't. You can simply use
response.pid;
To access the object key.
As you don't need to stringify then parse the response, you can just access msg directly, so it all comes down to
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
console.log(msg.pid);
});

jQuery ajax is not working when send post request

i try to use ajxt to send post request to my restful service
here is my ajax code
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
//xmlhttp.open("GET","http://192.168.1.100:8080/MapDemo/service/add?name=hieugie333&longitude=123&latitude=321",true);
//xmlhttp.send();
//document.getElementById("message").innerHTML=xmlhttp.responseText;
var JSONObject= {"name":name, "longitude":lng,"latitude":lat };
var jsonData = JSON.parse( JSONObject );
var request = $.ajax({
url: "http://192.168.1.100:8080/MapDemo/service/add",
type: "POST",
contentType: "application/json; charset=utf-8",
data: jsonData,
dataType: "json"
});
can anyone help me in this case ?
var JSONObject= {"name":name, "longitude":lng,"latitude":lat };
That is a JavaScript object, not a JSON text.
var jsonData = JSON.parse( JSONObject );
That will error (or return null) because you aren't passing it a string containing a JSON text.
Your later code is expecting a string containing a JSON text though.
You want JSON.stringify not JSON.parse.
You need to change your "JSON.parse" to "JSON.stringify". You called the opposite function that you should have.

How to navigate JSON Object in jQuery?

I made this webservice that handles my database functions, and this is an AJAX call to one of the methods.
$.ajax({
type: "POST",
url: "Service/dataBaseService.asmx/getRMAData",
data: '{"RMAId": 1 }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
console.log(data);
alert(data.RMA_ID);
}
});
this is what is logged:
({d:"[{\"RMA_ID\":1,\"RequestDate\":\"2013-02-28T00:00:00\",\"Company\":1,\"Status\":\"Accepted \",\"Serial\":201764,\"LastChangeDate\":\"2013-02-28T00:00:00\",\"LastChangeBy\":\"Foreign \",\"Price\":null}]"})
However alert(data.RMA_ID) returns undefined aswell as data.d.RMA_ID?
How can I get hold of the values?
The value of data that you've logged is an object with a property named d, that contains a string value. You could probably make adjustments at your server side to make the value of d an object rather than a string, but the way it is currently constructed, you would be able to parse it into an object using JSON.parse.
Once you've done that, the resulting object should be an array, containing one single object. Thus, your access to RMA_ID would be as follows:
var data = JSON.parse(data.d);
alert(data[0].RMA_ID);
Using simple javascript you need to parse JSON response
var resp = eval('(' + data + ')');
or thru jQuery
var resp = jQuery.parseJSON(data);
now you can access the data using '.' and key name
console.log(resp.d[0].RMA_ID)

Categories