How do I get certain part of object as string - javascript

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

Related

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 to send a correct AJAX JSON?

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

jQuery ajax request data not send

i am trying some idea on a ajax send,but i can't find why this code can't not send any parameter to jsp and thorw the nullpointerException.
I fix my code here,thanks for reponse.
var dfd = {
resolve : function (res) {
$("#Div123").html(res);
}
};
function getAjaxResponse(page, responseType, dataVar, dataVal, dfd) {
var dataObject = $.parseJSON('{"'+ dataVar +'":"'+ dataVal +'"}');
$.ajax(page, {
type: 'POST',
dataType: responseType,
data: dataObject,
success: function (responseData) {
dfd.resolve(responseData);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
getAjaxResponse("ajaxreponse.jsp", "text", "aa", "yes", dfd);
});
});
Change your data to:
data: { dataVar : dataVal }
and your dataType to
dataType: isJSON ? "JSON" : "text
They both don't accept functions.
data accepts plain object or string and dataType accepts only string

how to set a deferred on ajax with jquery?

let me start with some code:
function sendAjax(data, type)
{
$.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}
$.when(sendAjax(someData, 'url')).then(function(data){
console.log(data); //undefined
});
$.when(sendAjax(someOtherData, 'url')).then(function(data){
console.log(data); //undefined
});
the issue i'm having is that data comes in as undefined
if i use success in the $.ajax the data comes in fine
The main idea here is that i should write the sendAjax() method once and use it through the application, but i don't think i set it up properly
ant ideas?
You need to return the promise return by $.ajax() from sendAjax
function sendAjax(data, type)
{
return $.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}

Jquery Find if response contains element

How do you find if the response contains the element form
$.ajax({
url : $(this).attr('action'),
type : 'POST',
success : function(response){
if($(response).find('form').length)
{
alert("hii");
}
}
});
Form could be the topmost element of the response or somewhere in middle
$.ajax({
url : $(this).attr('action'),
type : 'POST',
dataType: 'html', // you should set it
// if you response send html only
success : function(response){
if($(response).filter('form').length)
{
alert("hii");
}
}
});
According to update:
....
dataType: 'html',
success : function(response){
var container = $('<div/>').append(response);
if($(container).find('form').length)
{
alert("hii");
}
}
$.ajax({
url : $(this).attr('action'),
type : 'POST',
success : function(response){
var hasForm = $("<div></div>").append(response).find("form").length > 0;
if(hasForm)
{
alert("hi");
}
}
});
The dataType : 'html' forces jQuery to treat the response as simply html. I'm using the "has" function which will reduce the matched set of elements to only those that contain a form somewhere in them.
$.ajax({
url : $(this).attr('action'),
type : 'POST',
dataType : 'HTML',
success : function(response){
$(response).has('form').doMoreWorkHere();
}
});
Alternatively, you can write that shorter by
$.post($(this).attr('action'), {}
function(response){
$(response).has('form').doMoreWorkHere();
}, 'html');
Where does 'response' come from? What format is it?
I send my returned vars in json:
success: function(msg){
var obj = jQuery.parseJSON( msg );
alert( obj.VARNAMEHERE );
}
Or you could just examine the entire response as opposed to a particular variable. That would give you an idea as to how to traverse the results to find what you're looking for.

Categories

Resources