Format of JSON received at node/express server - ajax

I am sending data from the client to the server.
// client
var messageObj = {};
messageObj.fromUserId = 1;
messageObj.messageContent = "print this";
$.ajax({
url: "/sendMessage",
type: "POST",
data: JSON.stringify(messageObj)
})
// server
app.post('/sendMessage', function (req, res, next) {
console.log(req.body);
return res.status(200);
});
Why is the console.log output, this:
{ '{"fromUserId":1,"messageContent":"print this"}': '' }
and not this ? (and how can I get it to this ?)
{"fromUserId":1,"messageContent":"print this"}

The default, unless you specify something else, is to send the data URI-encoded and to tell the server that's how it's being sent. If you're going to send JSON, you need to tell both the browser (and jQuery) and the server that by specifying contentType:
$.ajax({
url: "/sendMessage",
type: "POST",
contentType: "application/json",
data: JSON.stringify(messageObj)
})

Related

WordPress - Get server time using ajax and admin-ajax.php

I am new to using Ajax to get WordPress data.
The following code should return the server time but the response always is "400 Bad Request".
$.ajax({
url: obj + "?action=wps_get_time&format=U",
success: function(data) {
console.log(data);
}
});
Also tried it as POST and it was the same.
$.ajax({
url: obj,
method: "post",
data: { action: "wps_get_time", format: "U" },
success: function(data) {
console.log(data);
}
});
Any suggestions what's wrong please? Can't figure.
I always thought there are actions I can use always such as wps_get_time, without using a plugin. Am I wrong?
Ist there any easy way to get the server time by ajax?
Thank you all in advance.
The code below will return server time in Indochina and log it to console.
$.ajax({
type: 'GET',
cache: false,
url: location.href,
complete: function (req, textStatus) {
var dateString = req.getResponseHeader('Date');
if (dateString.indexOf('GMT') === -1) {
dateString += ' GMT';
}
var date = new Date(dateString);
console.log(date);
}
});```

Ajax post request can't get data with express router

I'm using express.Router() to manage my routes.
then using Ajax post request send some data to it. but I can't get the data.
ajax code :
$.ajax({
url: '/custom',
type: 'POST',
contentType: 'application/json; charset-utf-8',
dataType: 'json',
processData: false,
data: JSON.stringify({ "key": "values" }),
success: function(data) {
console.log(data.toString());
}
})
express code:
var express = require('express');
var router = express.Router();
router.post('/custom', function(req, res) {
console.log(req.body);
console.log(req.params);
console.log(req.query);
res.write(JSON.stringify());
res.end();
});
but all the logs are empty.
The issue is because the content-type header in your ajax is malformed.
Instead of
contentType: 'application/json; charset-utf-8' it should be contentType: 'application/json; charset=utf-8'.
Assuming you are using the bodyParser.json() middleware, this would cause the body to not be parsed, which would print an empty body. When you sent the requests with Postman the proper headers were sent, which is why it worked there but not from the ajax request.

Receive data at node.js server from Ajax call in Object format

I am using Ajax call to post data from client side to node server and trying to receive data at server end, manipulate it(do some db query) and then return the response.
client side code :
$.ajax({
type: "post",
url: "http://localhost:8888/ajaxRequest",
dataType: "json",
data: {name: "Manish", address: {city: "BBSR", country: "IN"}}
}).done(function ( data ) {
console.log("ajax callback response:" + data);
});
server side :
var port = 8888;
var server = http.createServer();
server.on('request', request);
server.listen(port);
function request(request, response) {
var store = '';
response.writeHead(200, {"Content-Type": "text/json"});
request.on('data', function(data) {
store += data;
});
request.on('end', function() {
console.log(store);
response.end(store);
});
}
Problem : when I am consoling "store" variable in request end function I am getting something like this:
name=Manish&address%5Bcity%5D=BBSR&address%5Bcountry%5D=IN
I just want the same data at the server side what I sent in the Ajax 'data' parameter. I also tried, queryString.parse, JSON.parse() but no help. I just want my output as :
{name: "Manish", address: {city: "BBSR", country: "IN"}}
You need to tell jQuery that this is an JSON request:
$.ajax({
type: "post",
url: "http://localhost:8888/ajaxRequest",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({name: "Manish", address: {city: "BBSR", country: "IN"}})
}).done(function ( data ) {
console.log("ajax callback response:" + data);
});
This way, your request body will reach the server with the stringified JSON, so you'll be able to do the following:
request.on('end', function() {
store = JSON.parse(store);
console.log(store); // ta-daaa, Object!
response.end(store);
});
Have you tried something like:
...
response.end(JSON.stringify(store));

jquery ajax return with html result

I am using jquery ajax to post username and password and return with a result it with working perfectly with GET method but using the post method it send the data but not return with the html result
here is my code:
$.ajax({
type: "POST",
url: "panel.aspx",
data: username + ";" + pw,
success: function (result) {
$("#midiv").html(result);
}
});
Try;
$.ajax({
type: 'POST',
url: 'panel.aspx',
data: {
'username=' + uname "&password=" + pword,
//Note:- uname and pword are variables and not text
},
success: function (result) {
$("#midiv").html(result);
}
});
in your aspx, you may catch data something like;
Dim uname, pword
uname = Request.Form("username")
pword = Request.Form("password")
Hope this helps...
Try this:
$.ajax({
type: "POST",
url: "panel.aspx",
data: {
username: "foo",
pw: "bar"
},
success: function (result) {
$("#midiv").html(result);
}
});
The way you are doing you are sending the variables in the GET request URL. To send data via post, define an object in the data config which the keys represent the parameters that you want to send.
You are not sending the data correctly, try:
$.ajax({
type: "POST",
url: "panel.aspx",
data: 'username=' + username + "&password=" + pw,
success: function (result) {
$("#midiv").html(result);
}
});
$.ajax({
type: "POST",
url: "panel.aspx",
data: {username: username, password: pw}
}).done(function(result) {
$("#midiv").html(result);
});
You'll also need to change your serverside scripts to listen for POST requests and not GET requests, for instance in PHP it would be:
$user = $_POST['username'];
$pw = $_POST['password'];
Not really sure how to do it in aspx, but I'm guessing you'll figure that out ?

jQuery.ajax returns 400 Bad Request

This works fine:
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
This returns 400 Bad Request (Just a reformulation of the above jQuery using .ajax to support error handling).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
I think you just need to add 2 more options (contentType and dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
===============
and for post
$.ajax({
type: 'post',
must be met with
app.post('/', function(req, res) {
I was getting the 400 Bad Request error, even after setting:
contentType: "application/json",
dataType: "json"
The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.
This was my initial code:
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
Now after making the request, I checked the console tab in the browser development tool.
It looked like this:
responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.
Changing the data object creation like below fixed the issue for me:
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
I assume other possible errors could also be identified by logging and inspecting the error object.
Your AJAX call is not completed with the following two params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType is the type of data you're sending
dataType is what you're expecting back from the server
In addition try to use JSON.stringify() method. It is used to turn a javascript object into json string.

Resources