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.
Related
I am trying to make a GET request using jQuery. Instead of jquery appending my data name/vale pairs to the end of my url, it is appending [object%20object].
I am using both the $.ajax and $.get functions. See $.ajax and $.get
In researching this issue, I have found suggestions to add processData: false and contentType: false to my settings object (which shouldn't matter), but these options do not fix my problem.
Can someone confirm that this is a bug? Could my endpoint be blocking my request? But if so, why would that affect the url params?
here is my code that I am trying.
HTML
<input name='email'/> <button class='btn-submit'>Submit</button>
JS
$('.btn-submit').click(function(e) {
e.preventDefault();
var email = $('[name=email]').val();
var data = {
"apitoken": 'MYTOKEN',
"listid": 1111,
"email": email
};
var endpoint = "https://myendpoint.com/";
$.ajax({
url: endpoint,
method: 'GET',
processData: false,
contentType: false,
data: data,
success: function (data, status, jqxhr) {
console.log('success', data, status);
},
error: function(jqxhr, status) {
console.log('error', jqxhr, status);
}
});
// THIS IS THE GET METHOD
$.get(endpoint, data, function(data, status, jqxhr) { console.log('success', data, status); });
I don't know what I'm missing.
Everything works when passing complex custom objects, but when I try to pass a simple int or string I get null
Here is the ajax call on client side:
var id = 1;
$.ajax({
type: "GET",
url: "/api/APICalls/MethodName",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(id), // or JSON.stringify({id: id}) or just id
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (data) {
alert(data.responseText);
}
});
On server side the method is as follows:
[HttpGet]
public void MethodName([FromBody] string id)
{
// Do something with id... Doesn't matter... It is `null`!
}
The reason why you are getting null value for id parameter is [FromBody]. Technically when you send GET request to the server with jQuery the data is presented in the query parameters and not in the request body.
What you need to do on backend side is just to remove [FromBody] as follows:
[HttpGet]
public void MethodName(string id)
{
// Now you should be able to access the value of id
}
Sending data from client side as the following:
var id = 1;
$.ajax({
url: '/api/APICalls/MethodName',
type: 'GET',
data: {id: id},
success: function (data) {
console.log(data);
},
error: function (err) {
console.error(err);
}
});
From the documentation for [FormBody] you can read the following:
To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.
Your data was presented in the query string, checking the network tab in Chrome:
I hope this helps!
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)
})
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/"
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).