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.
Related
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);
Here I am using ajax call to get the json object from controller.
<script>
$(document).ready(function(){
$.ajax({
cache: false,
type: "GET",
url: "userid_12345.json",
dataType: 'json',
success: function(data){
somemethod();
},
error:function(){
alert("Sorry!");
}
});
});
</script>
Here, this userid_12345.json file will be in same path.
There will be multiple json files will be there based on the userid like userid_12345.json, userid_22345.json, userid_55345.json.
So, I need to give dynamic URL's to get the .json file from the path.
something like this.. userid_?.json. ? will replace the userid
How to achieve this?
Like this:
<script>
var myDynUrl = "http://wherever/userid_" + dynamicValue + ".json"
$(document).ready(function(){
$.ajax({
cache: false,
type: "GET",
url: myDynUrl,
dataType: 'json',
success: function(data){
somemethod();
},
error:function(){
alert("Sorry!");
}
});
});
</script>
just add a variable (outside the $.ajax request) that cantains the user id
var myUserId = "12345"; than in the url url: "userid_" + myUserId + ".json",
This question already has answers here:
jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]
(3 answers)
Closed 8 years ago.
my web app as the following structure in ajax requests:
$.ajax({
type : "GET",
url: '...',
dataType: "xml",
success: function(xml) {
$.ajax({
type : "GET",
url : "....",
dataType : "xml",
success : function(xml) {
},
error : function(xhr) {
alert(xhr.responseText);
}
});
$.ajax({
type : "GET",
url : "....",
dataType : "xml",
success : function(xml) {
},
error : function(xhr) {
alert(xhr.responseText);
}
});
$.ajax({
type : "GET",
url : "...",
dataType : "xml",
success : function(xml) {
},
error : function(xhr) {
alert(xhr.responseText);
}
});
}
});
I need all the resquests that are beeing made here to finish before i do something else. Because i need them to load content into a div. and then append that to a html element in my code.
And i dont want to use (document).ajaxStop because that will ruin my code later on.
How can i achieve this?
You can use differed($.Deferred) Objects to make your code look more clean,
Every $.ajax request returns you a differed object, and use them with $.when and .done() combination like the following
$.when(req1, req2, req3).done(function (resp1, resp2, resp3) {
//This will be executed on the success of all three requests
})
In your case you can do as follows
var req1 = $.ajax({type:"GET", url: "..."});
req1.done(function (resp1) {
// This will execute after the first request is done
var req2 = $.ajax({type:"GET", url: "..."}),
req3 = $.ajax({type:"GET", url: "..."}),
req4 = $.ajax({type:"GET", url: "..."});
$.when(req2, req3, req4).done(function (resp2, resp3, resp4) {
// when other three request are done
});
// If there are arbitrary number of requests, please consider the following
var requestsArray = [],
numberOfRequests = 10;
for (var i=0; i<numberOfRequests; i++) {
var request = $.ajax({type:"GET", url: "..."});
requestsArray.push(request);
};
$.when.apply(null, requestsArray).done(function () {
// You can collect the responses in the same order from `arguments`
var responses = arguments;
});
});
Deferred objects provide a very nice way to handle callbacks,
To know more on Deferred objects check this out http://api.jquery.com/category/deferred-object/
jQuery's $.ajax returns a promise ($.Deferred) by default. So you don't have to use callbacks and you can use these promises instead. Then using the $.when function you can create a new promise which will wait for these 3 promises to finish and the do all actions you need.
Look at the example in the bottom of the linked page to see how it works.
Edit: If the documentation is right then it should look like this:
$.ajax({
type : "GET",
url: '...',
dataType: "xml"
})
.then(function (xml) {
return $.when(
$.ajax({
type : "GET",
url : "....",
dataType : "xml"
}),
$.ajax({
type : "GET",
url : "....",
dataType : "xml"
}),
$.ajax({
type : "GET",
url : "...",
dataType : "xml"
})
);
})
.then(function (res1, res2, res3) {
var xml1 = res1[0], xml2 = res2[0], xml3 = res3[0];
});
But I didn't test it so I don't know if it's really right.
I think you can use Jquery Deffer, like that.
Serial call
$.ajax('http://echo.jsontest.com/id/1')
.then(function(result){
console.log(JSON.stringify(result));
return $.ajax('http://echo.jsontest.com/id/2')
}).then(function(result){
console.log(JSON.stringify(result));
return $.ajax('http://echo.jsontest.com/id/3')
}).then(function(result){
console.log(JSON.stringify(result));
});
Paralel call
$.when(
$.ajax('http://echo.jsontest.com/id/1'),
$.ajax('http://echo.jsontest.com/id/2'),
$.ajax('http://echo.jsontest.com/id/3')
).then(function(result1, result2, result3){
console.log(JSON.stringify(result1[0]));
console.log(JSON.stringify(result2[0]));
console.log(JSON.stringify(result3[0]));
})
I use $.ajax to send some data to testajax.phpenter code here where data are processing. Result of this proces is link. How to get access to this? I think about sessions or cookies. Set in session $test and get access in another files.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: console.log('success');
data: { json : jsonObj }
});
In testajax.php I have someting like this
echo "PDF: <a href=images/test.pdf>$dir.pdf</a>";
$test = "PDF: <a href=images/test.pdf>$dir.pdf</a>";
How to get the $test or output the echo after call $.ajax
You can use success' function to get request from PHP.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'html',
data: { json : jsonObj }
success: function(data) {
var request = data;
console.log(data);
$('#link_container').html(data);
}
});
Your console now holds PDF: <a href=images/test.pdf>($dir content).pdf</a>.
Also the variable request holds the same result that you can use anywhere in the script.
Result is appended to #link_container.
Use the success() method for display the result.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: function (data){ // <= define handler for manupulate the response
$('#result').html(data);
}
data: { json : jsonObj }
});
Use below code It may help you.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonObj },
onSuccess: successFunc,
onFailure: failureFunc
});
function successFunc(response){
alert(response);
}
function failureFunc(response){
alert("Call is failed" );
alert(response);
}
Can't seem to get the variable getID to work. I'm trying to change the html of the div. I know that the variable has the right value.
$('.cardid').change(function() {
var getID = $(this).attr('value');
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: "id="+getID,
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
});
Write data in $.ajax as data: {id : getID}, instead of data: "id="+getID,
Use val to get the value of an input :
var getID = $(this).val();
As you're making a POST request, you should also use the data argument to let jQuery properly send the value :
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: {id:getID},
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
You can try this:
$('[id="'+getID+'"]').html(data);
and yes you should pass it this way:
data:{id:getID}