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);
});
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.
Have you checked that the server/api you are posting to return a response (use postman)
Have you checked the headers for the request. You may need to add authorization headers(pretty common practice with public apis)
Have you appended a client_id, app_id or api_key onto the request
Have you authenticated your request (basically point 2/3)
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)
})
$.ajax({
url: baseUrl,
type: "post",
contentType: "application/json",
dataType: "json",
success: function (data) {
window.location = ('http://localhost:9000/#/home.html?' + (data.search))
},
data: JSON.stringify(body),
});
return false;
}
};
this is my ajax request, it sends as JSON and it returns an object
ie. search = {firstName: km, lastname: b}
However, ajax isnt setting the content type to JSON for the params in the redirect. It is still sending as an object. JSON stringify does not work. Is there a way to set the content type to JSON inside the success/redirect function?
JSON.stringify just decodes the object into
%7B%22clientName%22:%blah%22,%22em%22:%22mLigDACsBihAL2RETse06351MuCNehZQ%22,%22partnercode%22:%blah%22%7D
You can use $.param:
var qs = $.param(data.search);
window.location = 'http://localhost:9000/#/home.html?' + qs;
This is probably because it trying to send an object to your window.location part.
What you probably need is this:
window.location = ('http://localhost:9000/#/home.html?firstName=' + data.search.firstName + "&lastname=" + data.search.lastname)
I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.
I am trying to make an AJAX call to the server side, using $http from my Angular App.
For sending the parameters, I tried the following:
$http({
method: "post",
url: URL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
console.log(result);
});
This is working, but it is using jQuery as well at $.param. For removing the dependency on jQuery, I tried:
data: {username: $scope.userName, password: $scope.password}
but this seemed to fail. Then I tried params:
params: {username: $scope.userName, password: $scope.password}
but this also seemed to fail. Then I tried JSON.stringify:
data: JSON.stringify({username: $scope.userName, password: $scope.password})
I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong? I am sure, AngularJS would provide this functionality, but how?
I think you need to do is to transform your data from object not to JSON string, but to url params.
From Ben Nadel's blog.
By default, the $http service will transform the outgoing request by
serializing the data as JSON and then posting it with the content-
type, "application/json". When we want to post the value as a FORM
post, we need to change the serialization algorithm and post the data
with the content-type, "application/x-www-form-urlencoded".
Example from here.
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {username: $scope.userName, password: $scope.password}
}).then(function () {});
UPDATE
To use new services added with AngularJS V1.4, see
URL-encoding variables using only AngularJS services
URL-encoding variables using only AngularJS services
With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:
$httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)
$httpParamSerializer - a serializer used by Angular itself for GET requests
Example with $http()
$http({
url: 'some/api/endpoint',
method: 'POST',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}).then(function(response) { /* do something here */ });
See a more verbose Plunker demo
Example with $http.post()
$http.post(
'some/api/endpoint',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}
).then(function
How are $httpParamSerializerJQLike and $httpParamSerializer different
In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.
For example (ignoring percent encoding of brackets):
• Encoding an array
{sites:['google', 'Facebook']} // Object with array property
sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike
sites=google&sites=facebook // Result with $httpParamSerializer
• Encoding an object
{address: {city: 'LA', country: 'USA'}} // Object with object property
address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike
address={"city": "LA", country: "USA"} // Result with $httpParamSerializer
All of these look like overkill (or don't work)... just do this:
$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
`&password=${ encodeURIComponent(password) }` +
'&grant_type=password'
).success(function (data) {
The problem is the JSON string format, You can use a simple URL string in data:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});
Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support application/x-www-form-urlencoded, then throw it away ... hopefully AngularJS does !
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.username+'&password='+$scope.password
}).then(function(response) {
// on success
}, function(response) {
// on error
});
Works like a charm with AngularJS 1.5
People, let give u some advice:
use promises .then(success, error) when dealing with $http, forget about .sucess and .error callbacks (as they are being deprecated)
From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."
If your data model is more complex that just a username and a password, you can still do that (as suggested above)
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: json_formatted_data,
transformRequest: function(data, headers) {
return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
}
}).then(function(response) {
// on succes
}, function(response) {
// on error
});
Document for the encodeURIComponent can be found here
If it is a form try changing the header to:
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
and if it is not a form and a simple json then try this header:
headers[ "Content-type" ] = "application/json";
From the $http docs this should work..
$http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(response) {
// your code...
});
$http({
method: "POST",
url: "/server.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "name='Олег'&age='28'",
}).success(function(data, status) {
console.log(data);
console.log(status);
});
you need to post plain javascript object, nothing else
var request = $http({
method: "post",
url: "process.cfm",
transformRequest: transformRequestAsFormPost,
data: { id: 4, name: "Kim" }
});
request.success(
function( data ) {
$scope.localData = data;
}
);
if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side
Though a late answer, I found angular UrlSearchParams worked very well for me, it takes care of the encoding of parameters as well.
let params = new URLSearchParams();
params.set("abc", "def");
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http
.post(UrlUtil.getOptionSubmitUrl(parentSubcatId), params, options)
.catch();
This worked for me. I use angular for front-end and laravel php for back-end. In my project, angular web sends json data to laravel back-end.
This is my angular controller.
var angularJsApp= angular.module('angularJsApp',[]);
angularJsApp.controller('MainCtrl', function ($scope ,$http) {
$scope.userName ="Victoria";
$scope.password ="password"
$http({
method :'POST',
url:'http://api.mywebsite.com.localhost/httpTest?callback=JSON_CALLBACK',
data: { username : $scope.userName , password: $scope.password},
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
console.log('status',status);
console.log('data',status);
console.log('headers',status);
});
});
This is my php back-end laravel controller.
public function httpTest(){
if (Input::has('username')) {
$user =Input::all();
return Response::json($user)->setCallback(Input::get('callback'));
}
}
This is my laravel routing
Route::post('httpTest','HttpTestController#httpTest');
The result in browser is
status 200
data JSON_CALLBACK({"username":"Victoria","password":"password","callback":"JSON_CALLBACK"});
httpTesting.js:18 headers function (c){a||(a=sc(b));return
c?a[K(c)]||null:a}
There is chrome extension called postman. You can use to test your back-end url whether it is working or not.
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
hopefully, my answer will help you.
I am trying post a string to web service but I am getting this error (Google Chrome Extension Project):
jquery-2.1.1.min.js:4 POST http://localhost:49242/Service.asmx/test
500 (Internal Server Error)
Here is my ajax code:
var data = {};
data.param1 = words[0];
$.ajax({
data: JSON.stringify({ 'data': data.param1 }),
dataType: 'application/json',
url: 'http://localhost:49242/Service.asmx/test',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
My service:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string test(string param1) {
return param1;
}
I am working on this problem about 3 days. Can you help me ?
By the way, I have a question. I am posting json variable to service with ajax(like you see), but service returning xml value. Is there a problem or [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] this code block solving problem?
Your error come from your data parameter. Stringify data object instead of { 'data': data.param1 } :
var data = {};
data.param1 = words[0];
$.ajax({
data: JSON.stringify(data),
dataType: 'application/json',
url: 'http://localhost:49242/Service.asmx/test',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
Your stringifyed data will result in {"param1":"Words"}, then your service should be able to bind the param1 parameter.
I was facing this type of error on AJAX post response. I was spending too much time behind this issue and finally I caught it.
It throws a 500 internal error because the AJAX response has a lot of content from the server so it returns a timeout of execution.
So I just added the line below and it's working fine.
Page.Server.ScriptTimeout = 300;
I've written an application in angular for file download, the application is working fine only for small json string, but comes to large string the download fails. Can anyone please tell me some solution for this.
I'm using REST webservice
var json = _.getJson(); // here json value object be received from a script function
var myURL = 'rest/myMethod?jsonValue=' + JSON.stringify(json);
_.downloadFile(myURL);
The downloadFile method :
downloadFile: function(URL)
{
$.fileDownload(URL).done(function(e, response)
{
console.log('download success');
}).fail(function(e, response)
{
console.log('fail');
});
}
As per the comments, here's how to POST using Angular. I can only give you an example here. Header might depend on the angular version etc etc.
function TestController($scope, $http) {
$http({
url: 'yourwebsite',
method: "POST",
data: json, //this is your json data string
headers: {
'Content-type': 'application/json'
}
}).success(function (data, status, headers, config) {
//upload succesfull. maybe update scope with a message?
}).error(function (data, status, headers, config) {
//upload failed
});
}
I see two potential problems:
The request URL might be too long (see: this discussion)
The stringified JSON contains characters not valid in a URL
If the URL is too long, you'd have to move the jsonValue into the body of your request rather than passing it as a URL parameter.
To address the second problem, you need to URI encode the stringified value:
var myURL = 'rest/myMethod?jsonValue=' + encodeURIComponent( JSON.stringify(json) );
BTW, looking at tha fail parameters should indicate why the request failed in the first place.
Here is an example for using $http of Angular for sending a post request and download a XML file from the server.
$http({
url: '$your_URL_here$', // you should replace $your_URL_here$ by your own url
method: 'POST',
responseType: 'arraybuffer',
data: postJson, //***this is the request json data for post***
headers: {
'Content-type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
}).success(function(data){
var blob = new Blob([data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
saveAs(blob, $fileName$);// you should replace $fileName$ by your own fileName
}
}).error(function(data){
//Some error handling method here
});
Please note that you should import the FileSaver.js to save the file from 'arraybuffer' responseType.