How to retrieve data from node.js to Ajax? - javascript

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)
})

Related

Ajax POST error (400 BAD REQUEST)

and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"

data is empty from ajax request in whcms

I am trying to send a post request using ajax in whcms, but it seems that the data from the ajax request is null.
This is the ajax request:
function send_request(ticket_or_credit){
if(ticket_or_credit == 'ticket'){
var url = $("#ticket_action").val();
var ticket = $("#ticket_ticket").val();
var solution = $("#ticket_solution").val();
whmcs_data={ request_type:ticket, solution:solution };
jQuery.ajax({
type: 'POST',
url: url,
data: JSON.stringify(whmcs_data),
contentType:"application/json; charset=utf-8",
dataType: 'json',
success: function(results){
console.log(results);
console.log(whmcs_data);
},
error( xhr, ajaxOptions, thrownError ){
console.log( thrownError );
}
});
}
}
and in my php file:
$json = array("result" => "success", "message" => "Method is post", "data" => $_POST);
echo json_encode($json);
The $_POST is null.
Please help me, I haven't solve this problem for how many days :(
I removed the contentType and dataType of the ajax code just to make it default application/x-www-form-urlencoded; charset=UTF-8') and properly serialized whmcs_data variable. The output of your JSON.stringify is not properly serialized so I manually serialized it. for more information on ajax go to this : http://api.jquery.com/jquery.ajax/ and for JSON.stringify - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
try to replace variable whmcs_data declaration and ajax code with this:
whmcs_data = {
"request_type": ticket,
"solution": solution
};
$.ajax({
type: 'POST',
url: url,
data: whmcs_data,
success: function(results){
console.log(results);
console.log(whmcs_data);
},
error( xhr, ajaxOptions, thrownError ){
console.log( thrownError );
}
});

Is there a way to convert an HTML response to JSONP object or another way to have the success event?

I am trying to detect the user's city via this website: http://www.ipaddresslocation.org/my-ip-address.php. Almost all of the free geolocation APIs I've seen so far were not very accurate. When the following code executes, I see all the information I need in the Response tab (in the Network tab in Firefox), but the success event fails and I am not able to access any of that data.
$(document).ready(function(){
getCity();
});
var parameters = {
"Content-Type": "text/html",
'Accept-Encoding': 'gzip, deflate',
};
function getCity() {
$.ajax({
type: "GET",
url: 'http://www.ipaddresslocation.org/ip-address-locator.php',
dataType: 'jsonp',
success: function(data) {
console.log("success");
},
error: function(xhr, status, error) {
console.log("ERROR");
console.log(error.message);
}
});
}
The problem with my code was that I was trying to get the server to respond when I just needed to read the HTML page in my browser. Because of the Same Origin policy, I ended up using the CORS Anywhere node.js proxy to add headers to the proxied request and then doing RegEx to get the city. This link is great at explaining how to make cross-domain requests: Loading cross domain endpoint with jQuery AJAX .
$(document).ready(function() {
$.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
$.get(
'http://www.ipaddresslocation.org/ip-address-locator.php',
function(response) {
//regex to get the desired info
});
});
This happens when third party APIs haven't set things up developer-friendly. You can use the complete callback instead of the success callback and then access the responseText property of the XHR response:
$(document).ready(function(){
getCity();
});
var parameters = {
"Content-Type": "text/html",
'Accept-Encoding': 'gzip, deflate',
};
function getCity() {
$.ajax({
type: "GET",
url: 'http://www.ipaddresslocation.org/ip-address-locator.php',
dataType: 'jsonp',
complete: function(jqXHR, txtStatus) {
var myData = jqXHR.responseText;
},
error: function(xhr, status, error) {
console.log("ERROR");
console.log(error.message);
}
});
}
http://api.jquery.com/jquery.ajax/

Jquery AJAX POST get ID from response URI

This may be a really simple one but I have been searching the net for a few hours and can't find an answer!
I make a POST call to an API and it returns the ID in the URL (for example, the POST goes to /api/user and the response is /api/user/1).
I want to be able to retrieve that 1. Calling this.url in the .done function just returns http://localhost/api/user
Code is as follows:
ajaxHelper(url + '/api/user/', 'POST', user).done(function (item) {
//want to get the ID here
alert(this.url) //Returns the original URL without the ID (i.e. http://localhost/api/user
}
function ajaxHelper(uri, method, data) {
var headers = {};
return $.ajax({
type: method,
url: uri,
headers: headers,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
});
}
If your response is /api/user/1 and you wish to get data from there, you need to use the response that retuns. In your case, item:
.done(function (item) { ... })
item here will contain /api/user/1, and you can use this string to fetch whatever it is you need.

JQuery ajax() done / fail callbacks not returning upon status 200

I'm trying to post a form data using JQuery to a remote servlet.
I can see that the server receives the data and also returns status code 200 and a response string of "{result: 'success'}"
But the ajax call doesn't return with the done or fail functions (if I add an always function than I can see that it is being called)
Here's a code snippet of the client side:
`
var dataParams = 'email='+email+'&password='+password;
var url = 'http://127.0.0.1:8888/signup';
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json",
done: function() {
console.log("done!");
hideSignUp();
showThankYou(); },
fail: function() {
console.log("fail!");
}
});
`
Seems like I'm missing out on something, but can't seem to find what.
Note that I'm using JQuery 1.8.3 so success is deprecated.
Any thoughts?
Try:
var url = "http://127.0.0.1:8888/signup";
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function() {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
Try chaining your callbacks, rather than setting them as object fields:
$.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function (xhrResponse) {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function (xhrResponse, textStatus) {
console.log(textStatus);
}).always( function () {
console.log("I'm done with this.");
});
By chaining your callbacks, you guarantee execution of at least one (complete).

Categories

Resources