On Ajax Post, getting a bad request(404) - javascript

Using Ajax Post, getting a Bad Request(404).
I tried to google but didn't help me in that.
Note: on using "contentType: 'application/json; charset=utf-8'," on post my request going as a OPTIONS
var data = JSON.stringify(dataArr);
var clientType = $("#clientType").val();
var username = $("#hidUsername").val();
var clientId = $("#clientId").val();
var apiUrl = 'http://localhost.com/WebAPI/client/PostToclient'
$.ajax({
url: apiUrl,
type: 'POST',
//contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify({
'clientData': data,
'username': username,
'Id': clientId,
'clientType': clientType
}),
cache: false,
success: function(response) {
alert(response);
},
complete: function() {
},
error: function(ex) {
}
});

Not knowing your API its fairly hard to tell what going wrong. You will need to provide more information on the server side for this one ;)
One thing looks weird: the id field written in upper case 'Id', which likely to be 'id or 'clientId' if your API follow any kind of logic :p

Thanks all for ur help.
I found the problem why its is not able to call api. Now I am able to post my data using ajax call.
[WebInvoke(UriTemplate = "/client/PostToclient", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped)]
[OperationContract]
public async Task<string> PostToclient(string clientData, string username, string Id, string clientType)
{
// Create / update client data.
}

Make sure that your API is working fine, for that you can test with postman app.
And I observed that you are passing JSON content in a JSON data. i.e client Data, I think it may not work.
Please try to declare client Data properties with primary json format, so that it may solve.

Related

HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

I'm trying to make a post with javascript using ajax to a spring controller
$("#crear").click(function () {
var user = document.getElementById("user").value;
var client = document.getElementById("client").value;
var documents = document.getElementById("documents").value;
if (user==null||client==null||documents==null){
document.getElementById("error").innerHTML='FALTAN COSASsssssssssss';
alert('Rellene todo los campos!')
}
const data={
fecha_inicio:'A',
id:'A',
fecha_entrega:'A',
usuario:{
nombre:user
},
cliente: {
nombre:client
}
}
$.ajax({
url: urlCrearAlta,
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data,
success: function(data) {
// ...
}
});
$.post(urlCrearAlta,JSON.stringify(data),function (data,satus){
console.log('${data} and status is ${status}')
});
document.getElementById("error").innerHTML=user+client+documents;
});
and java code
#RequestMapping("/altas")
#RestController
public class AltaRestController {
private AltaController altaController;
public AltaRestController(AltaController altaController) {
this.altaController = altaController;
}
#PostMapping("/create-alta")
public void createAlta(#RequestBody AltaDTO altaDTO) {
altaController.createAlta(altaDTO);
}
I'm getting the error Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
When i use $.ajax it does not send any request, just when i use $.post it send the request
The problem seems to be how you are using the $.post method. jQuery uses the application/x-www-form-urlencoded;charset=UTF-8 contentType on post by default if you don't specify another contentType. Combined with the #RequestBody annotation at backend (which requires application/json by default) it results in the seen exception and 415 status code.
The solution to this problem should be fairly easy, just add the correct configuration for the .post method, something like this:
$.post({
url: urlCrearAlta,
type: "POST",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(data)
})
.done((data, status) => {
console.log(data, status);
//do whatever you like with data and status
});
Also, as stated in jQuery documentation here, $.post is just a shorthand method for $.ajax, so if $.ajax doesn't work and $.post does, there should be something wrong in how you configure the request or how you handle the callbacks methods. The major suspect for me would be the success function you specify in the $.ajax request, check there is nothing wrong in there, or just use the other callback methods, like .done, .fail and .always

jQuery Post JSON.Stringify() payload is not JSON, Indexing all characters

So, this is driving me nuts and I've never seen this before. I'm using Javascript to post JSON to AWS Lambda. The issue is that the payload is being sent as indexed characters instead of JSON. I can't for the life of me figure out why. I use this same code in another project and don't have this issue with posting JSON. This is what is being sent:
0=%7B&1=%22&2=C&3=o&4=m&5=p&6=a&7=n&8=y&9=N&10=a&11=m&12=e&13=%22&14=%3A&15=%22&16=R&17=T&18=S&19=%22&20=%2C&21=%22&22=F&23=i&24=r&25=s&26=t&27=N&28=a&29=m&30=e.....
As you can see it's indexing every single character of the data.
Here's my function:
$.ajax({
url: serviceUrl + "UpdateCompany",
type: "POST",
data: JSON.stringify(company),
contentType: 'application/json',
dataType: "json",
success: function success(res) {
if (res.status == "ok") {
utils.notify("Company updated successfully");
callback(res.data);
}
else {
utils.notify(res.message);
}
},
error: function error(res) {
alert("Could not complete action. Please refresh the page and try again.");
}
})
My "company" object is created like this:
var company = {};
company["CompanyName"] = $("#txtCompany").val();
company["FirstName"] = $("#txtFirstName").val();
When I debug it and run JSON.stringify(company), it displays the data correctly in JSON format, but when it's sent through the POST, it's not JSON format and indexing the characters like above.

Jquery Ajax not sending data to php server

This will be an easy one for you, but after ages of looking online I can't find a solution, or at least one I'm understanding.
result and users variables both alert correctly.
The data contents shows empty - why?
How should I be inserting these two variables into data ?
(also if it is right - how do I view the data content without going into server side)
Thank you in advance.
var result = result.text;
var users = localStorage.getItem('user');
alert("1");
$.ajax({
url:'********',
method: 'POST',
data: {user: users, serial: result},
dataType: "text",
contentType: "application/json",
success: function(data){
alert (data);
alert(users);
alert(result);
In your code alert(data) will refer to the data returned by the server. Not the data of your ajax request.
$.ajax() takes a settings object as its parameter. It's a set of key/value pairs that configure the Ajax request. data is just one of the keys of the object you are passing to the $.ajax() method.
To simplify your code, this is what is happening:
// this is what you're sending to the server
var dataSentToTheServer = {
user: users,
serial: result
}
// creating an object where data, url, success etc are keys.
var settings = {
url:'api/method',
method: 'POST',
data: dataSentToTheServer,
dataType: "text",
success: function (dataSentFromTheServer) {
alert(dataSentFromTheServer); // this argument will have the data returned by your server
alert(dataSentToTheServer); // data which was sent *to* the server
alert(data); // doesn't exist
}
....
}
$.ajax(settings);

Prevent encoding of Cypher query POSTed via JQuery

I have a Cypher query for Neo4j which looks like this:
var query = "MATCH (t:Person {name: 'Darth Vader'})-[:CHILD_OF*0..1]-child RETURN <a bunch of node properties>"
$.ajax({
url: '/wdc/query',
type: 'post',
data: query,
contentType: 'text/csv; charset=UTF-8',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
Said query is POSTed to a route in a node.js app where it is executed against Neo4j. The body of the POST which I received is handled like so:
app.post('/wdc/query', function(req,res) {
console.log(req.body);
}
I can't seem to pick the correct contentType in order to avoid my string from getting heavily munged:
//contentType: "application/x-www-form-urlencoded; charset=UTF-8"
{ 'MATCH (t:Person {name: \'Darth Vader\'})-': { ':CHILD_OF*0..1': '' } }
//contentType: 'text/csv; charset=UTF-8'"
{}
//contentType: 'text/x-java-source,java; charset=UTF-8'
{}
//contentType: 'application/json; charset=utf-8'
Error: invalid json
I'm clearly shooting blanks here. Can anyone give me a push in the right direction? Do I just need to encode this whole damn string and be done with it? (unfortunately, some of the methods I see to do this don't handle characters like '[')
Thanks.
Edit
Never Mind Just used JSON to wrap the query and then passed that as JSON/application. Works well - only thing that happens is we escape the single quotes around "Darth Vader", which is expected:
var jsonObj={};
jsonObj["statement"] = match + returnClause;
query = JSON.stringify(jsonObj)

passing db url as ajax parameter

I have a controller written in python cherrypy that should check if a db url is valid by attepting to make a connection. I'm having problems however passing the parameter to the method. My ajax call is:
$.ajax({ async : false,
type: 'POST',
url: "/settings/check_db_url/"+db_url ,
success: function(r) { alert(r) },
error: function(r) { alert('failure') }
});
Now the problem the urls that I need to test are in the form of:
'sqlite':'sqlite:///Users/Home/tvb-database.db' or
'postgresql+psycopg2://postgres:root#127.0.0.1:5432/tvb?user=postgres&password=postgres'
For the sqlite part I managed to pass it if I do something like:
db_url = db_url.split('/').join('__')
db_url = db_url.split(':').join('x_xxx_x')
And then replace back in python. But this seems so hacky to me and for the postgress part I guess I'll have to replace some more. So what is the correct way to handle this?
Send it as part of a POST parameter and not as part of the url using the data option:
$.ajax({
async : false,
type: 'POST',
url: '/settings/check_db_url',
data: { db_url: db_url },
success: function(r) { alert(r) },
error: function(r) { alert('failure') }
});
And in your server read the db_url POST parameter.

Categories