How to send a correct AJAX JSON? - javascript

I have a form with only 2 inputs. I wanna send a JSON to my POST method. Although, all possibilities give back this error:
415 (Unsupported Media Type)
I tried used this 3 ajax:
console.log($("#idform").serializeArray());
console.log($("#idform").serialize());
var nome = "\"" + $("#idnome").val() + "\"";
var idade = "\"" + $("#ididade").val() + "\"";
var all = "{\n"+"\"name\": "+nome+",\n"+
"\"idade\": "+idade+"\n"+"}";
console.log(all.toString());
$.ajax({
url : 'http://localhost:8080/DBRest/rest/escreve',
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : all
})
$.ajax({
url : 'http://localhost:8080/DBRest/rest/escreve',
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#idform").serializeArray()
})
$.ajax({
url : 'http://localhost:8080/DBRest/rest/escreve',
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#idform").serialize()
})
Here is what I got after printing them on console:
nome=yrt&idade=09 //$("#idform").serialize()
{
"name": "yrt", //all
"idade": "09"
}
And $("#idform").serializeArray() returned [("name","yrt"),("idade","09")]

You need to add the following
contentType: 'application/json'
contentType is what format you are sending to the server
dataType is what format you are expecting back form the server
$.ajax({
url : 'http://localhost:8080/DBRest/rest/escreve',
type : "POST", // type of action POST || GET
contentType : 'application/json', // data type
data : all
})

Related

Jquery ajax call wrong payload

I have some troubles whit jquery ajax call, infact I tried to perform a post call passing like data a string variable:
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: myVar,
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
If I inspect the http call I can see that the payload is:
'Hello': ""
I don't know how it is possible and how fix the problem.
jQuery, by default, will put a Content-Type: application/x-www-form-urlencoded header on data it sends via Ajax.
You, however, are passing a plain text string.
You need to either change the Content-Type to match the data you are sending or the data you are sending to match the Content-Type. (Or you could change both).
The important things are:
The data and content-type need to match
The server needs to be able to handle data in the format you are sending
So you might:
$.ajax({
type: 'POST',
url : 'https://...',
data: myVar,
contentType: 'text/plain'
// ...
})
or, since jQuery will encode objects as URL encoded data:
$.ajax({
type: 'POST',
url : 'https://...',
data: { myVar },
// ...
})
or, if you want multipart data:
const data = new FormData();
data.append('myVar', myVar);
$.ajax({
type: 'POST',
url : 'https://...',
data,
contentType: false // XHR will read the content-type from the FormData object (which it needs to do in order to determine the boundary paramater), putting 'false' here stops jQuery overriding it
// ...
})
or, for JSON
$.ajax({
type: 'POST',
url : 'https://...',
data: JSON.stringify(myVar), // This will be a JSON text representing a string
contentType: 'application/json'
// ...
})
i think you are passing payload in the wrong formate.
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: {
'name':myVar
},
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
On the server side you will get the value in the key 'name' you can fetch the value using 'name' key.

Laravel API url with dynamic data

I'm using ajax to store the data. In that I need to send some dynamic data in URL.
For E.g:
$.ajax({
url: "{{url('api/request/interview/{search_job}/request/users/{user_ids}')}}",
method: 'POST',
dataType: 'json',
success: function(response){
console.log('Result Sent',response);
}
});
In the above code, I dynamically send the data in {search_job} and {user_ids}. In that I'm getting an URL Error.
How can I send the values ?
Update this url type
url: "{{url('api/request/interview/{search_job}/request/users/{user_ids}')}}",
to
url: "{{url('')}}/api/request/interview/"+search_job+"/request/users/"+user_ids",
First, define your data before call the ajax.
var search_job = job_data;
var user_id = user_id_data;
Then, change the url to
'api/request/interview/'+search_job+'/request/users/'+user_ids+',
Here's the full code looks like:
var search_job = job_data;
var user_id = user_id_data;
$.ajax({
url : 'api/request/interview/'+search_job+'/request/users/'+user_ids+',
method : 'POST',
dataType : 'json',
success : function(response){
console.log('Result Sent',response);
}
});

How can I set get request call type to 'document' [duplicate]

What is content-type and datatype in a POST request? Suppose I have this:
$.ajax({
type : "POST",
url : /v1/user,
datatype : "application/json",
contentType: "text/plain",
success : function() {
},
error : function(error) {
},
Is contentType what we send? So what we send in the example above is JSON and what we receive is plain text? I don't really understand.
contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
alert(result.success); // result is an object which is created from the returned JSON
},
});
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
dataType : "html",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
One more - if you want to post:
name=John&age=34
Then don't stringify the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
dataType : "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
data : data,
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the
MIME type of the response
"text": A plain text string.
So you want contentType to be application/json and dataType to be text:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.
They are both used in the request to the server so the server knows what kind of data to receive/send.

How do I get certain part of object as string

I am trying to get data from a server depends on logged in user's name.
I succeed to get correct object, but I failed to get only certain part of it.
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
complete : function(data) {
$("#docDepartment").val(data.responseText);
$("#docDepartment").prev().html(data.responseText);
console.log(data.responseText);
console.log(typeof data.responseText);
}
});
},
That empName gets each logged in users' empNameTrim value in my DB.
The type of data is object and responseText is string.
And its output looks like following:
I want to make the value of docDepartment equals to the value of department which will be SM in this case.
Thank you in advance.
EDIT: I followed Loïc Faure-Lacroix's tips, modified my code like following:
1st
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
complete : function(data) {
var doc = JSON.parse(data.responseText);
$("#docDepartment").val(doc.department);
$("#docDepartment").prev().html(doc.department);
console.log(doc.department);
console.log(typeof doc.department);
}
});
},
2nd
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
complete : function(data) {
$("#docDepartment").val(data.responseJSON.department);
$("#docDepartment").prev().html(data.responseJSON.department);
console.log(data.responseJSON.department);
console.log(typeof data.responseJSON.department);
}
});
},
3rd
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
})
.done(function (data) {
$("#docDepartment").val(data.department);
$("#docDepartment").prev().html(data.department);
console.log(data.department);
console.log(typeof data.department);
})
},
All of them works fine. Choose whatever you like.
If jQuery isn't parsing to JSON, use JSON.parse to do it on the responseText... That said, according to the documentation here, if you go to the data types section, you should read the following:
If json is specified, the response is parsed using jQuery.parseJSON
before being passed, as an object, to the success handler. The parsed
JSON object is made available through the responseJSON property of the
jqXHR object.
So you should be using this:
$("#docDepartment").val(data.responseJSON.department)
But to make your code cleaner, It might be better to use the following form:
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
var request = $.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
})
request.done(function (data) {
$("#docDepartment").val(data.department);
$("#docDepartment").prev().html(data);
console.log(data);
console.log(typeof data);
})
request.fail(function () {
...
})
},
The main difference is that the done callback should be called with the final data. While the complete one is called with a jqXHR object. It will get called only on success while complete is always called even on errors.
If I understand your question correctly, you need to parse the JSON object. I believe jQuery makes your response JSON automagically. So, the following should work for you.
$("#docDepartment").val(data.responseText.department);

dataType 'application/json' vs. 'json' [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
$.ajax - dataType
I am using jQuery 1.8.2, and for some reason 'application/json' does not work, but 'json' works as dataType to a standard jquery ajax call. Is this a glitch? A version related difference? or is there an established difference between the two?
$(document).ready(function() {
$.ajax({
type : "POST",
url : '<c:url value="/url.htm" >',
//dataType : "application/json", <-- does not work
dataType: 'json' // <-- works
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
});
dataType takes json, it means the request expects a json response.
contentType takes application/json, it means the request is sending json data
You can send as well as expect json in a request e.g.
$.ajax({
type : "POST",
url : url,
contentType : "application/json",
dataType: 'json',
data: JSON.stringify({some: 'data'}),
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
here you're sending json and expecting xml
$.ajax({
type : "POST",
url : url,
contentType : "application/json",
dataType: 'xml',
data: JSON.stringify({xmlfile: 'file.xml'}),
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
and here you're sending x-www-form-urlencoded(jQuery automatically sets this for you), and expect json back
$.ajax({
type : "POST",
url : url,
dataType: 'json',
data: {id: '1'},
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
contentType sets the ContentType HTTP request header, telling the server that the body of this request is of the given type.
dataType sets the Accept header to tell the server that this is the type of response we want e.g.
Accept:application/json, text/javascript, */*; q=0.01
but regardless of what type of response the server sends jQuery will still attempt to parse it as whatever type you set in the dataType field.
"application/json" is the correct mime type for json. The jquery dataType field, however, is expecting one of the following strings:
"xml"
"html"
"script"
"json"
"jsonp"
Per the json documentation, the correct dataType is "json".
http://api.jquery.com/jQuery.ajax/
Here are the options supported:
xml
html
script
json
jsonp
text

Categories

Resources