jQuery Post JSON.Stringify() payload is not JSON, Indexing all characters - javascript

So, this is driving me nuts and I've never seen this before. I'm using Javascript to post JSON to AWS Lambda. The issue is that the payload is being sent as indexed characters instead of JSON. I can't for the life of me figure out why. I use this same code in another project and don't have this issue with posting JSON. This is what is being sent:
0=%7B&1=%22&2=C&3=o&4=m&5=p&6=a&7=n&8=y&9=N&10=a&11=m&12=e&13=%22&14=%3A&15=%22&16=R&17=T&18=S&19=%22&20=%2C&21=%22&22=F&23=i&24=r&25=s&26=t&27=N&28=a&29=m&30=e.....
As you can see it's indexing every single character of the data.
Here's my function:
$.ajax({
url: serviceUrl + "UpdateCompany",
type: "POST",
data: JSON.stringify(company),
contentType: 'application/json',
dataType: "json",
success: function success(res) {
if (res.status == "ok") {
utils.notify("Company updated successfully");
callback(res.data);
}
else {
utils.notify(res.message);
}
},
error: function error(res) {
alert("Could not complete action. Please refresh the page and try again.");
}
})
My "company" object is created like this:
var company = {};
company["CompanyName"] = $("#txtCompany").val();
company["FirstName"] = $("#txtFirstName").val();
When I debug it and run JSON.stringify(company), it displays the data correctly in JSON format, but when it's sent through the POST, it's not JSON format and indexing the characters like above.

Related

On Ajax Post, getting a bad request(404)

Using Ajax Post, getting a Bad Request(404).
I tried to google but didn't help me in that.
Note: on using "contentType: 'application/json; charset=utf-8'," on post my request going as a OPTIONS
var data = JSON.stringify(dataArr);
var clientType = $("#clientType").val();
var username = $("#hidUsername").val();
var clientId = $("#clientId").val();
var apiUrl = 'http://localhost.com/WebAPI/client/PostToclient'
$.ajax({
url: apiUrl,
type: 'POST',
//contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify({
'clientData': data,
'username': username,
'Id': clientId,
'clientType': clientType
}),
cache: false,
success: function(response) {
alert(response);
},
complete: function() {
},
error: function(ex) {
}
});
Not knowing your API its fairly hard to tell what going wrong. You will need to provide more information on the server side for this one ;)
One thing looks weird: the id field written in upper case 'Id', which likely to be 'id or 'clientId' if your API follow any kind of logic :p
Thanks all for ur help.
I found the problem why its is not able to call api. Now I am able to post my data using ajax call.
[WebInvoke(UriTemplate = "/client/PostToclient", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped)]
[OperationContract]
public async Task<string> PostToclient(string clientData, string username, string Id, string clientType)
{
// Create / update client data.
}
Make sure that your API is working fine, for that you can test with postman app.
And I observed that you are passing JSON content in a JSON data. i.e client Data, I think it may not work.
Please try to declare client Data properties with primary json format, so that it may solve.

Jquery Ajax not sending data to php server

This will be an easy one for you, but after ages of looking online I can't find a solution, or at least one I'm understanding.
result and users variables both alert correctly.
The data contents shows empty - why?
How should I be inserting these two variables into data ?
(also if it is right - how do I view the data content without going into server side)
Thank you in advance.
var result = result.text;
var users = localStorage.getItem('user');
alert("1");
$.ajax({
url:'********',
method: 'POST',
data: {user: users, serial: result},
dataType: "text",
contentType: "application/json",
success: function(data){
alert (data);
alert(users);
alert(result);
In your code alert(data) will refer to the data returned by the server. Not the data of your ajax request.
$.ajax() takes a settings object as its parameter. It's a set of key/value pairs that configure the Ajax request. data is just one of the keys of the object you are passing to the $.ajax() method.
To simplify your code, this is what is happening:
// this is what you're sending to the server
var dataSentToTheServer = {
user: users,
serial: result
}
// creating an object where data, url, success etc are keys.
var settings = {
url:'api/method',
method: 'POST',
data: dataSentToTheServer,
dataType: "text",
success: function (dataSentFromTheServer) {
alert(dataSentFromTheServer); // this argument will have the data returned by your server
alert(dataSentToTheServer); // data which was sent *to* the server
alert(data); // doesn't exist
}
....
}
$.ajax(settings);

PHP $_POST empty during AJAX post request

Goal: Serialize data, send them in HTTP POST request using AJAX, proceed data in PHP (and answer)
Problem: PHP $_POST variable seems to be empty
JS/AJAX
var postData = [cmd, data];
alert(postData = JSON.stringify(postData));
$.ajax({
url: "./backendTag.php",
type: "post",
data: postData,
dataType: 'json',
success: function (response) {
alert(response); // Empty
//logToServerConsole(JSON.parse(response));
},
error: function(jqXHR, textStatus, errorThrown) {
logToServerConsole("E3"); // Communication Error
console.log(textStatus, errorThrown);
}
});
PHP
<?php echo json_encode($_POST);
The reason for the same is probably because you are not posting properly in javascript. Before i add the codes, let me add a couple of tips on how to debug in these situations.
First is, you check if the request is properly formed. Inspect the network in browser dev tools.
Second method could be to use var_dump on $_POST to list out all the post parameters and check if they have been recieved in PHP
Now as far as the code goes
here is the javascript
$.ajax({
method: "POST",
url: "url.php",
data: { name: "John Doe", age: "19" }
}).done(function( msg ) {
alert(msg);
});
and in php you can simply check using
<?php
print $_POST["name"];
?>
which would work perfectly. Notice how the data in javascript is a list, while from what you wrote seems to be json string
Apparently we can't pass an array directly after serializing him. The following code resolved the problem. (Split array)
data = JSON.stringify(data);
var JSONdata = {"cmd" : cmd, "data" : data};
$.ajax({
url: "./backendTag.php",
type: "post",
data: JSONata,
dataType: 'json',
/* Handlers hidden*/
});
JSON content won't be parsed to the $_POST globals. If you want to reach them, try to get from php://input with:
file_get_contents('php://input')
And I suggest giving the content-type during the ajax request:
contentType: 'application/json',
If it's not working, try to set the data as a string, with JSON.Stringify, like the following:
data: JSON.stringify(postData)

Send stored procedure in ajax data

I need send stored procedure with parameter in ajax data.
Below is my example, after send get this error
Apostrophes real problem,any solution?
function sendData(userNameVal, procedureNameVal, jsonCallBackFunc) {
var stringVal = "wsInsertData N'EXECUTE carInsert N''160655'',N''data:image/png;base64,AAAAAAAAAAAA'',N''18602''', N'18602'";
$.ajax({
type: "POST",
url: 'helloService.asmx/myService',
data: "{userName:\"" + userNameVal + "\",procedureName:\"" + stringVal + "\",callback:\"" + jsonCallBackFunc + "\",}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblError').html(JSON.stringify(response));
},
error: function (error) {
console.log(error);
}
});
}
Security! All it takes is a user to edit the JSON response to the server and add their own SQL, and they can make your SQL server do anything they want. Pass whatever parameters you need, and have the server construct the Stored Proc after sanitizing possible crazy inputs from the client.
Before 'callback' you add a single quote ', which is not terminated.

jquery not properly serializing json in ajax call

Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.
Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});
2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});

Categories