Recieving data sent by ajax.post - javascript

I would like to send data to a Node.js server running on localhost with ajax. To test this, I wanted to send the input of type text to the server and just log it there.
This is my Post-Function (which is called by clicking on a button):
function answer(){
let data = {
name : $('#send').val()
};
console.log(data);
$.ajax({
type: 'POST',
url: 'http://localhost:3456/MyWebApp/Test',
dataType: 'text',
data: data.name,
success: console.log('post was successfull'),
error: function(textStatus, errorTrown){
console.log(textStatus + " " + errorTrown);
}
});
}
On my Server I try to collect the data with the following function:
app.post('/MyWebApp/Test', function(request,response){
console.log(request.body.data);
});
app.listen(3456);
My problem is, that the value on my server (in the above console.log) is always undefined.
I already tried to send the whole json-Object with dataType-Parameter json instead of text, but then I get an error in my server for trying to read a property value of something undefined. How do I have to implement the app.post function, to make the data readable and work with it?
I hope it is possible to understand what I am trying to achieve and what my problem is, I dont really know much about Node.js or Ajax, still I would be thankful for any help.

You're sending one string value data.name so your http request Content-Type would be plain/text
At NodeJS side you're using express library and it doesn't provide post request body by default.
You need to collect post request body using "data" event
request.on("data", callback);

Related

I have issue with retrieving the data received by API call which is GZIP format

I am having issue with extracting the data from the response received by api call
http://open.pkfare.com/apitest/shopping?param="+json_encoded_string
where json_encoded_string is base64 encrypted json data, which is done as per the documentation in http://open.pkfare.com/documents/show
As per the documentation the response received will be in gzip format,
I'm facing issue with retrieving this data to json format. I'd gone through many blogs for the solution but i didn't got the solution and finally end up here
I'm calling this api using ajax call
var fbURL = "http://open.pkfare.com/apitest/shoppingparam=" + json_encoded_string;
$.ajax({
url: fbURL,
type: 'GET',
success: function (resp) {
//---i need code for reading the received gzip data here---
},
error: function (e) {
alert('Error: ' + e);
}
});
As you are using AJAX post to get this, I will recomond to use server-side language to do it. I think this is the best and only way for it to actually work.
Post your AJAX request to a server side language then there call the api and do your other coding to parse the data.

Data is not ready when retrieving session parameter from the server using AJAX

I'm building an application using laravel. I have a controller which returns a session parameter from the server.
I'm retrieving this parameter using an ajax request from a view blade as follow:
var url = CMS_URL + 'GetSystemMode/';
$.ajax({
url: url,
type: 'get',
dataType: 'text',
async: false,
success: function(data) {
console.log("data: " + data);
}
});
The code running on the server side is:
Route::get('/GetSystemMode', function () {
return Session::get('systemMode');
});
In localhost, I'm getting the right "data" and the code works as a charm, but in production, "data" is always empty.
It's like the success method is executed before the data is yet retrieved from the server side.
This issue took to much time from me, and I don't have any idea how to fix it.
Thanks.
Our production environment was at the appEngine, so due to the server restirctions, it wasn't allowed to save the sessions on files as was done on localhost. So the problem was actually that the server is not saving the sessions at all and therefor I'm getting empty data.
I solved it by installing redis and saving the sessions over it.

Can't return any data from jQuery Post

I've been searching for an answer on this one, but none of the answers I found help resolving this issue:
HTTP Post via jQuery is not returning any data.
Here is the javascript code:
$.post(
<ENDPOINT_URL>,
<XYZ DATA SENT>,
function(data){
//THIS IS THE PROBLEM HERE
},
"json")
.fail(function(jqXHR, textStatus, errorThrown){
alert(textStatus);
});
This calls my endpoint API Url fine, which returns code 200 and a JSON response body:
{message: "XYZ"}
So here is what I've done so far:
Because of the asynchronous behavior, I created a function to receive and process the data input. Nothing happens still.
Added the .fail to process failures. According to an article my JSON returned may be incorrectly formatted and placing that .fail to process a failure may let me know what's going on... Is there a way to get the actual error message details?
Validated my JSON. Is it incorrectly formatted or something I'm not realizing?
Replaced the entire code with $ajax instead. Still, getting the same error.
I want to be able to receive that response and process the message "XYZ".
Thank you everyone for your help, much appreciated.
Tutorials/Articles I've followed:
https://api.jquery.com/jquery.post/
How do I return the response from an asynchronous call?
why cant I return data from $.post (jquery)
All, thank you very much for all of the feedback - the issue is now resolved. #Austin French, after reviewing the full method on both the server side and client side javascript, I realized the issue was related to headers.
My apologies for not expanding further on my question and providing further details: I am using Amazon AWS API Gateway to process a backend Lambda function, the client calls out to the function, the function does the job and returns the JSON:
{"message":"xyz"}
I wasn't received this message on the client side using jQuery $.post. The problem came down to how AWS API Gateway processes the request and returns the response.
I needed to include the following headers as part of my Lambda's function response:
"Access-Control-Allow-Origin" : "*"
Here is the full code for the server side response:
//Response
let responseCode = 200;
var responseBody = {
message: responseMessage
};
var response = {
statusCode: responseCode,
headers: {
"Access-Control-Allow-Origin" : "*"
},
body: JSON.stringify(responseBody)
};
Now on the client side, my original function(data){...} receives the response and is able to process it correctly, no errors are being triggered. Client side response handler:
function(data){
alert(JSON.stringify(data));
}
Thanks again everyone for your help!
Try following:
$.post(
ENDPOINT_URL,
myData,
function(data) {
var response = jQuery.parseJSON(data);
console.log(response);
}
);
This is the way I usually use it. It sends data as if sent in an html form and receives json response.
var value1, value2;
$.ajax({
type: "POST",
url: url,
data: {"property1" : value1, "property2" : value2},
success: function(result, status, xhr){
<here you can process the json you get as response in result}
},
error: function(xhr, status, theError){
<here process if ajax fails>
},
dataType: "json"
});
A couple things that won't fit in a comment:
I prefer this format for AJAX:
var myUrl = $(selector).val();
$.post( myUrl, { name: "John", time: "2pm" })
.fail(function (data) { /* code for failure */ }),
.done(function( data ) {
alert( "Data Loaded: " + data );
});
To see what the server is returning however, an easy thing to do is use Chrome's debugger:
Go to the network tab, choose the calling method and then on the right sub pane choose response. You should be able to see not only the response code, but the full contents returned.
A couple additional notes:
the .Done will call the function once the AJAX completes.
Depending on Jquery version you might not have not have a .done but rather .success and vice versa.

Get jQuery $.ajax to send data in body for GET [duplicate]

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

How can i receive data from external url using json?

Recently i am learning json to create apps.I have a doubt in a Json , php based chat system .
In this , the code work fine for same origin policy.But for sending and receiving data from external url, it successfully sends data to external php.But not receiving any data from server.I search in internet to solve this problem , and found jsonp as alternative. I tried jsonp , but i m not sure if am correct because i am new to ajax itself.
Please don't mis understand my question.I want to load a index.html file from localhost , when i send request to external url (anysite.com/xx/ajax.php) .It process and returns the data back to index.html.But the problem is my data is sended finely and processed on the server but it doesn't return to remote file.But it works fine for same server.
$.tzPOST = function(action,data,callback)
{
$.post('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
please help me with a code.
You cant receive JSON from external web by JavaScript, because of the policy.
But you can do AJAX request on your PHP file and there you can get the JSON by file_get_content http://cz2.php.net/file_get_contents function.
For using(working) with jsonp, u can take ready solution jquery-jsonp
from GitHub.
Example of using (by you question):
$.tzGET = function(action,data,callback){
var url = 'http://anysite.com/xx/ajax.php?action='+action;
$.jsonp({
type: 'GET',
url: url,
callbackParameter: callback,
dataType: 'jsonp',
data: data,
timeout: 10000,
success: function(json){
alert('success')
},
error: function(){
alert('error')
}
});

Categories