POST request - String parameter is not present - javascript

I am using AJAX to send data to server. It works if I put all data to URL, so everything is OK. But when I put all data to "data" in AJAX, server writes - required String parameter is not present. Eventhough I can see all data in requests body (in browser). What might be wrong?
const data = {
firstName: name,
surname: surname,
email: email,
password: pass1,
roles: roles
};
state.search.method("POST", "users", JSON.stringify(data));
method(type_, url_, data_){
$.ajax({
url: proxy + url_,
type: type_,
contentType: "x-www-form-urlencoded",
dataType: "json",
headers: {
'Authorization': 'bearer ' + localStorage.access_token
},
data: data_,
success: function(result){
alert("OK METHOD");
},
error(XMLHttpRequest, textStatus, errorThrown){
alert('Error: ' + errorThrown + ", " + textStatus);
console.log(XMLHttpRequest.status + ' ' +
XMLHttpRequest.statusText);
}
});
}

Maybe the server is trying to read information through query string only, which means you should use GET method instead of a POST submission.
Try changing your method() function like this:
method(type_, url_, data_){
$.ajax({
url: proxy + url_,
type: "get", //Send using GET method
headers: {
'Authorization': 'bearer ' + localStorage.access_token
},
data: data_,
success: function(result){
alert("OK METHOD");
},
error(XMLHttpRequest, textStatus, errorThrown){
alert('Error: ' + errorThrown + ", " + textStatus);
console.log(XMLHttpRequest.status + ' ' +
XMLHttpRequest.statusText);
}
});
}
And then, you call it without the json stringfy like this:
state.search.method("POST", "users", data);

Can't say i am 100% on this answer but i have assumed 2 things here
That you are actually wanting to perform a 'GET' request here instead of post, as you have said you have tried the URL in the browser and then i assume what you mean is you have keyed this into the address bar then that would be a 'GET' request.
What you can use in JQuery is the $.params function to build your query. so then your code may look something like this.
Your Data object
const data = {
firstName: 'name',
surname: 'surname',
email: 'email',
password: 'pass1',
roles: 'roles'
}
Ajax method
let queryString = $.param(data)
let url = 'https://your base url';
$.ajax({
url:url+'?'+queryString, //Building your url for getting the data
method: 'GET',
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus) // You can console.log the other values for debugging
}
});
I think there will be a little work to do to map your values form where you are gettin them into your object and then also into the ajax method.
if you can give me more details about how these are pull together then i can happoly provide an update with more specific information
Hope this helps
NOTE if it is a POST of the data just need to understand what the payload would need to be like.

You are posting JSON:
state.search.method("POST", "users", JSON.stringify(data));
You claim you are posting x-www-form-urlencoded data
contentType: "x-www-form-urlencoded",
If you are trying to post JSON, then send it with the correct Content-Type: application/json
If you are trying to post URL encoded data then:
Send it with the correct Content-Type (it's the default for jQuery so omit the contentType parameter entirely, or get it correct (application/x-www-form-urlencoded).
Send data in that format: state.search.method("POST", "users", data); (jQuery will encode an object in that format by default).
It works if I put all data to URL
If you want to post all the data in the URL, then you should be making a GET request and encoding it properly.
So:
Specify GET and, again, pass an object not a sting of JSON: state.search.method("GET", "users", data); (and jQuery will properly encode the data in the query string).

Related

Error: Invalid data; couldn't passe JSON object, array, or value

I am having a problem when trying to make POST or PUT requests to Firebase RESTful API...
To make the request I am using Valve's Panorama JavaScript which execution is handled by Google V8 engine.
A GET request (which works without problems) looks like this:
$.AsyncWebRequest("https://<project>.firebaseio.com/-KrFV19WfaC7tfY6qys6.json",
{
type: "GET",
complete: function (data){
$.Msg("WOW: " + JSON.stringify(data));
},
error: function (err){
$.Msg("Error: " + JSON.stringify(err));
},
});
And I get the response:
WOW: {"statusText":"success","responseText":"{\"a\":\"1\"}\u0000","status":200}
But when I try to do a PUT or POST request which code looks like this:
$.AsyncWebRequest("https://<project>.firebaseio.com/game.json",
{
type: "POST",
data: {"A":"B"},
success: function (data){
$.Msg("WOW: " + JSON.stringify(data));
},
error: function (err){
$.Msg("Error: " + JSON.stringify(err));
},
});
I get the next response:
Error: {"statusText":"error",
"responseText":"{\n \"error\" : \"Invalid data; couldn't parse JSON object, array, or value.\"\n}\n\u0000",
"status":400}
Can somebody help me understand what could be the problem?
Update
According to this piece of code
you have to wrap your object in a payload property:
data: {payload: JSON.stringify({ "A": "B" })},
Have to tried to use JSON.stringify() around your request data object?
Like:
$.AsyncWebRequest("https://<project>.firebaseio.com/game.json",
{
type: "POST",
data: JSON.stringify({"A":"B"}),
success: function (data){
$.Msg("WOW: " + JSON.stringify(data));
},
error: function (err){
$.Msg("Error: " + JSON.stringify(err));
},
});
Also, is there a contentType property in AsyncWebRequest?
So maybe you have to add
contentType: "application/json; charset=utf-8",
to the request object (after the type property for example).

Posting and getting from server

Just a fast question.
I'm using ajax POST and GET to send json data to a server and retrieve that data back. However, what I'm confused about is getting json info from the GET call.
getMessage = function(){
$.ajax({
url:'/get_messages',
dataType: 'json',
type: 'GET',
success: function(msg){
console.log("got eeeem " + msg );
}
});
};
What i've seen so far implies what i'm getting from the server should be displayed in msg. However in the console log, msg is displayed as "got eeeem [object Object]".
So I'm confused as to how to pull the necessary information out of the msg.
My post looks like this:
var packet = {
'username': 'Name',
'message': innerText,
'date': new Date().toUTCString()
};
$.ajax({
url:'/receive_message',
data: JSON.stringify(packet),
type: 'POST',
success: function(msg){
console.log("EUREKA " + msg);
}
});
Specifically from the GET call, I want to retrieve the innerText variable from the json. Any help is much appreciated
Your are receiving Json object from server in ajax success.You need to convert that object to string
Use like this JSON.stringify(msg);
var packet = {
'username': 'Name',
'message': innerText,
'date': new Date().toUTCString()
};
$.ajax({
url:'/receive_message',
data: JSON.stringify(packet),
type: 'POST',
dataType:'application/json',
success: function(msg){
console.log("EUREKA " + JSON.stringify(msg));
}
});

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.

Access array in Javascript

I cannot seem to understand why I cannot access an array I get send back by PHP.
I send this back when AJAX makes a call: $response['success'] = true;
I do this by echo json_encode($response); in my PHP file.
Now I want to access it in Javascript, but response.success doesnt work, it logs 'undefined' in the console. Now I check the response, and that is this: {"success":false}
But if I check for if(response.success) it always sends back false, because response.success is undefined. Does anyone know what I mean and what is causing this issue?
This is my AJAX call:
$$.ajax({
type: 'POST',
url: url + "applogin.php",
crossDomain: true,
data: {
username: e,
password: p
},
//dataType: 'json',
success: function(response) {
console.log(response);
if (response["success"]) {
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
mainView.router.loadPage('beurslist.html');
} else {
console.log("Your login failed");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
},
});
The answer by #SZenC is fine, there's a point though about best practices:
The reason jQuery didn't recognize the response as JSON is because the server probably didn't send a Content-type header, so just add to your server-side code a call to -
header('Content-type: text/json');
You won't need the explicit call to JSON.parse in each API call, you'll get better integration with test tools, and your app will be better self-documented for other folks who use/will-use this code (including yourself should your code need some future maintenance).
In any case it is advised also to document the expected input on the client side by either explicitly specifying dataType as json or by making the API call using a shortcut method such as $.getJSON().
Your ajax-call will return a string, you need to decode it with JSON.parse. You'd get something like this then.
$$.ajax({
type: 'POST',
url: url + "applogin.php",
crossDomain: true,
data: {
username: e,
password: p
},
//dataType: 'json',
success: function(r) {
var response=JSON.parse(r)
console.log(response);
if (response["success"]) {
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
mainView.router.loadPage('beurslist.html');
} else {
console.log("Your login failed");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
}
});

how to parse json result from sharepoint to show list names

This is the first time I work with JSon, so pls dont be rude with me :)
I have this website.
http://msdn.microsoft.com/en-us/library/jj164022(v=office.15).aspx
and this javascript sample:
jQuery.ajax({
url: http:// site url/_api/web/lists,
type: "GET",
headers: {
"ACCEPT","application/json;odata=verbose",
"Authorization", "Bearer " + accessToken
},
})
The thing is I have a div called results and I would like to show the list names that the rest service returns me.
See jQuery official documentation:
http://api.jquery.com/jQuery.ajax/
There are a lot of examples.
EDIT
If your call return one serializable object you can do something like this:
$.ajax({
url: http:// site url/_api/web/lists,
type: "GET",
headers: {
"ACCEPT","application/json;odata=verbose",
"Authorization", "Bearer " + accessToken
},
success: function(data) {
$.each(data, function(index, elem){
//... do some work where ...
alert(elem);
});
}
});
It's hard to say exactly how to show the list in your div without knowing how the returned JSON is formatted. But the main idea is that you'll need to add a success callback function to your jQuery.ajax() call in which you parse the returned data and insert it into your div. For example:
jQuery.ajax({
url: "http://siteurl/_api/web/lists",
type: "GET",
headers: {
"ACCEPT","application/json;odata=verbose",
"Authorization", "Bearer " + accessToken
},
success: function(data) {
var listTitle = data.title; // just an example; not sure if this property exists in your data
$("$myDiv").append('<p>' + listTitle + '</p>');
}
});

Categories