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));
}
});
Related
I'm having trouble following an API Guide using AJAX. I have successfully got the session token from the login api as the session token is needed to make requests to GET/POST data.
Code to get the session token:
var sessionToken = null;
$.ajax({
url: '<API-URL>/1/json/user_login/',
data: {
'login_name' : 'USERNAME',
'password' : 'PASSWORD'
},
type: 'GET',
dataType: 'json',
success: function(data) {
sessionToken = data.response.properties.session_token;
$("#result").text("Got the token: " + sessionToken);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
On successful, we get the session token: D67ABD0454EB49508EAB343EE11191CB4389255465
{response: {…}}
response:
properties:
action_name: "user_login"
data: [{…}]
action_value: "0"
description: ""
session_token: "D67ABD0454EB49508EAB343EE11191CB4389255465"
__proto__: Object
__proto__: Object
__proto__: Object
Now that I have a valid session token, I can now make requests to get data. I'm trying to get driver data using the following code:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
According to the documentation, I need to use POST instead of GET in order to get vehicle details in the response and pass the session token as a parameter:
Unfortunately it seems to return blank data when using GET and Permission denied when using POST. I've tried sending the parameters as an array like the documentation but that fails also. I've tried passing the session token as Authorisation but still get no response.
The only help I got from the API support team was: "POST can’t be with parameter query on the end point."
What am I doing wrong?
Any help is appreciated. Thanks!
I don't know what service/api you're trying to call, but from the error message you've posted and the brief documentation it looks like you're structuring your url wrong:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
You're including the action parameter as part of the url by the looks of things when the doc you posted implies it should be part of the data (and the error they sent you of "POST can’t be with parameter query on the end point." also supports this). So try the following: (of course without seeing more of the docs it's difficult to know if your actual base url is correct)
$.ajax({
url: '<API-URL>/1/json/',
data: {
'action': {'name':'api_get_data',
'parameters': [ {'license_nmbr' : vrn }],
'session_token' : sessionToken
}
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
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).
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).
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.
I am making an ajax call below and getting an error I do not understand. The variable response in the success function looks like
{"status": "complete", "username": "test", "error": "0", "message": ""}
however when I call my three alert functions inside the success function, the first one prints out the value above, but the next two print out undefined. I know the error key exists, however the javascript does not recognize it. As a result my window crashes.
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
alert(response); //prints correct response
alert(response.error); //prints undefined
alert(response["error"]); //prints undefined
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});
Can somone explain what is happening and how to fix this?
This is due to a combination of two factors:
The server is sending the JSON with the wrong content type
You've used the wrong capitalization for overriding it
Consequently, jQuery is interpreting the JSON as (probably) plain text (which is why alerting the value gives you the raw JSON and not [Object object]).
You should fix this by making sure the server sends the JSON with:
Content-Type: application/json
Since it looks like you are using PHP, you can do that with:
header("Content-Type: application/json");
You should also either remove datatype: 'json' or change it to dataType: 'json'.
that because response is not parse as JSON object to do that you can do it like this:
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
var data = jQuery.parseJSON(response); // <---- Here parse it as JSON
alert(data.error);
// Todo with data
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});