Ajax call from client to server in nodejs - javascript

I am trying to make an ajax call from client to server with some data and want to access the data on the server.
Client:
$('#searchName').blur(function(){
$.ajax({
url: "/getcontact",
type:"GET",
dataType:"json",
data: {
name: "Malek"
},
contentType: "application/json",
success: function( result ) {
$( "#mob" ).value=result;
}
});
});
Server:
app.get("/getcontact",function(req,res){
console.log("===="+req.body.data+"====");
})
I am not able to get the value of name in req.body. If I console the req.body it is showing as [object Object] and when consoling req.body.data it is showing as undefined.
I have imported body-parser.

req.body is meant to hold request payload and not query strings.
You should use req.query instead, since you are making a GET request and not a POST/PUT/PATCH request.

Related

C# not getting data from Ajax

I have a problem sending ajax data from my javascript file to my c# controller. I get a "bad request error" in my c# program, and the reason i get that is because the data parameter "result" which i am sending with ajax is not getting received by c# and the c# variable stays null. I know Ajax is routing to the correct controller since it is calling the method, but the variable "result" is not getting received by c# for some reason.
Here is my ajax request.
$.ajax({
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { 'result' : result },
url: "https://localhost:44374/api/task",
cache: false,
success: function (data) {
// Process the received data.
}
});
Here is my c# controller
[HttpPost]
public ActionResult<string> Get(string result)
{
string id = result;
getTaskContent(id);
return id;
}
After changing Ajax to GET, the program works and the output is:
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44374/api/task/1108164994166723?_=1549876832637 application/x-www-form-urlencoded; charset=UTF-8
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 17.8526ms 404
But for some reason the C# Actionresult method is not getting executed.
See that the URL is localhost:44374/api/task/1108164994166723?_=1549876832637, where the result variable is 1108164994166723, what I have no idea about is how the ?_=1549876832637 part is coming. If I alert the result variable in the window it is only 1108164994166723
Solution
The combination of changing to GET instead of POST and the changing URL in Ajax to url: "localhost:44374/api/task?result=" + result, did the job.
Correct Ajax code is:
$.ajax({
type: 'GET',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: "https://localhost:44374/api/task?result=" + result
});
try changing the content-type to "application/json;charset=utf-8" and sending the parameter name in the URL like this:
$.ajax({
type: 'POST',
contentType: "application/json;charset=utf-8",
url: "https://localhost:44374/api/task?result=" + result,
cache: false,
success: function (data) {
// Process the received data.
}
});
Change the GET method in the controller to POST method. Since in your ajax call you are specifying the type as post.
you must changeto HttpPost in Controller and change the result type to JsonResult.
Try to change your type to type:GET -- because your controller action method is a HTTPGET and contentType to: contentType: 'application/json; charset=utf-8
and data to data: JSON.stringify({ result: result })

jQuery AJAX never runs success function

I have a registration form on my website and I use jQuery's AJAX function to send the data into my ASP.NET API.
My AJAX looks like this:
$.ajax({
type: "POST",
url: '[urlHere]',
data: {
'Name': userName,
'LastName': userLastName,
'Email': userEmail,
'Password': userPass
},
dataType: 'application/json',
success: function (response) {
console.log('Success');
},
error: function (err) {
console.log('Error');
}
});
(The values in the data object are values I got from the inputs on my website)
The data I send into the API gets inserted into a SQL Database Table. Running this AJAX function successfully inserts my data into my Database, but it always runs the error function. I have tested the API in apps like Postman, and the API works perfect, but my AJAX always runs error. When I console.log the error that gets returned, it returns the statusCode of OK, which is what I set it to if everything goes successfully in the API.
jQuery tends to call the error function for successful responses when it cannot parse the response to the desired data type. First of all, I don't believe application/json is a proper value for the dataType property. Change it to just json first. If that doesn't work, remove that line completely, log the response and verify whether your response is in fact a proper JSON.
Reference: jQuery Ajax Data Types
Set these codes in your ajax :
contentType: 'application/json; charset=utf-8',
processData: false,

Sending form JSON data to server via AJAX

I want to manually send my form data in JSON format to the server.
I changed my form data to a JSON fomat below.
The data I have in my clients-side javascript is in JSON (ie{"firstname":"john","lastname":"smith"}
$.ajax({
type: 'POST',
url: "http://localhost:3000/UserRegistration",
dataType: 'application/json',
data: JSONData,
success: function(data) {
}
});
I am using body-parser and in my server.js code, I do console.log(req.body) but the data is shown in this format
{ '{"firstname":"john","lastname":"smith"}': '' }
It added more curly braces. Why is that? How can i access the data in the server side
You can just serialize the form and bodyparser will parse it into json for you.
$.post('http://localhost:3000/UserRegistration', form.serialize(), function(data) {
...
});
dataType: 'application/json' will expect json response from server
Set processData : false and contentType : 'application/json'[Ref]
processData: By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false
contentType: When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent)
Please directly parsed your object to json. for example: JSON.Stringfy(obj)

jQuery + node.js express POST request

I'm trying to send a post request to a node server.
This is my client-side code:
function send(userid,message){
$.ajax({
method: "POST",
url: "/chat/messages?id="+userid+'&message='+message
})
clear();
}
This is my server side code:
app.post('/chat/messages',function (req,res){
var query = url.parse(req.url,true).query
insertMessage(query.id,query.message)
})
This works, however I'm not sure getting data in the query string using post is the right way to go.
I tried adding a data field in $ajax parameter:
function send(userid,message){
$.ajax({
method: "POST",
url: "/chat/messages"
data : {'id' : userid, 'message' : message}
})
clear();
}
And using bodyParser() in the server end to parse the body contents:
app.use(bodyParser.json())
app.post('/chat/messages',function (req,res){
console.log(req.body)
})
but when I log the response, the body{ } object is always empty.
Why is that?
Is a <form> tag necessary for POST requests?
I tried editing my ajax request to use json as the dataType and stringifying the data, but the req.body is still empty.
$.ajax({
method: "POST",
url: "/chat/messages",
data : JSON.stringify({'id' : userid, 'message' : message}),
dataType: 'json',
})
When you post data to a server, the data is usually urlencoded and added to the body of the request. In your example, it would look like this:
id=<userid>&message=<message>
Therefore, the bodyparser you need to be able to parse that is bodyparser.urlencoded()
app.use(bodyParser.urlencoded())
Note that it isn't always urlencoded, it all depends on what you are using to send the post. AngularJS for example defaults to sending it as json instead. The good news is you could simply add both bodyparsers and your route won't need to know which method was used since in both cases the data would end up on req.body with key/value pairs.
You should read the express documentation. http://expressjs.com/api.html#req
// For regular html form data
app.use(bodyParser.urlencoded())
app.post('/chat/messages',function (req,res){
console.log(req.body);
console.log(req.query.id);
console.log(req.query.messages);
})
You can also do req.params
app.post('/chat/messages/:id',function (req,res){
console.log(req.body);
console.log(req.query);
console.log(req.params.id)
})

create jquery array for ajax post

How can I convert the output of drp.getDateRange to an array so that I can post it via AJAX?
I have updated this code to represent the advice given below
<script>
var drp;
var myArray = [];
function makedatepicker() {
drp = $("#myDate").datepicker({});
}
function getRange() {
var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
data: data,
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
}
});
}
$(document).ready(function () {
makedatepicker();
});
</script>
Update
Note on JSON. The default encoding will be url form encoded. If you want the request to send the data as JSON, you will need to add..
content-type: "application/json; charset=utf-8",
also if you are returning JSON, you should add ...
datatype : "json",
Not sure which scripting language your using on the back end, but if PHP, you can send back array data like this
echo json_encode($myArray);
I will add the JSON stuff to the sample code below.
End Update
If you use .serialize() you an send it as ajax data and it will show up in your post or get array.
If you are working with an array, you might want to use .serializeArray()
You can view an object or array in your developer tools (F12 in Chrome or FF), by using console.dir(someObject);
var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
datatype : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
beforeSend : function (){
console.log("Before Send: Data looks like..");
console.dir(data);
},
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
console.log("parsing JSON ...");
console.dir($.parseJSON(response));
}
});
Chrome Developer Tools Console, this is where you will see anything that you console.log or console.dir
You can check the JSON that is being sent by clicking the Network tab. Then click the name of the ajax script and it will show you the data being sent. (Also, clicking on the "response" tab will show you what is being sent back by your script.)
In the example below I am sending an ajax request using the above code and it is showing that the data is indeed a JSON object.

Categories