Reputation: 47
I'm trying to learn sending/receiving data from Ajax to node.js. I am able to send the data from ajax but not able to receive. Not able to solve the problem. That'd be great if someone can explain where I'm going wrong.
Ajax
$(document).on('submit', '#searchdata', function (e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: location.pathname,
method: 'POST',
type: 'POST',
data: formData,
processData: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var ret = JSON.stringify(data);
console.log('Success: '+JSON.stringify(data))
},
error: function (xhr, status, error) {
console.log('Error: ' + JSON.stringify(error));
},
});
});
node.js
var myData = '';
request.on('data', function (data) {
myData += data.toString();
});
response.writeHead(200, {
'Content-Type': 'text/json',
'Access-Control-Allow-Origin' : '*'});
response.end(myData);
});
Upvotes: 1
Views: 74
Reputation: 434
2 and 3 should return a response, in either case, I would use postman to check. If postman should at the very least return a response. Check the headers and the http status header. If you are getting a 200 response, and no content back there is likely an issue with the route or server configuration
Ajax example $(document).on('submit', '#searchdata', function (e) { e.preventDefault();
//Get form by id
var $form = #("#form_id");
//Form data
var formData = new formData($form);
$.ajax({
url: 'http://localhost:300/edit/11', //path to api
method: 'POST', //Method to use (GET by default)
data: formData, //The data to be posted
dataType: 'json', //Expected reponse format
}).done(function(res){
//Results here can contain an error - this is common for custom error types
//Test for custom error assuming in the format res.error
if( typeof res.error == 'undefined'){
console.log(res)
}else{
//You have an error
}
}).fail(function(err){
console.log(err)
})
Upvotes: 0
Reputation: 2202
I see this statement in the jQuery Ajax documentation:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
I believe you will need to change the code similar to as mentioned above in the documentation.
Upvotes: 1