how to make two dependent ajax requests on one buttonclick - javascript

I want insert two forms as two table rows in db using a button click event.I have used ajax request to insert in database and done for one form, while making another ajax request depending on first form it is not working
here is my java script using jquery.
var transportid = 2;
$.ajax({
url : '/TransportJob/create',
type : 'POST',
data : $('form[action="/TransportJob/Create"]').serialize(),
success : function sfn(data, textStatus, jqXHR) { // **success spelling mistake**
transportid = parseInt(data);
alert('inserted id :' + data);
$('#TransportJobId').val((transportid));
$.ajax({
url : '/TransportJobAddress/create',
type : 'POST',
//beforeSend: function myintserver(xhr){
// $('#addAddress').html('<div id="temp_load" style="text-align:center">please wait ...</div>');
//},
data : $('form[action="/TransportJobAddress/Create"]').serialize(),
success : function poste(data, textStatus, jqXHR) {
$('#addAddress').html(data);
},
error : function err(jqXHR, textStatus, errorThrown) {
alert('error at address :' + errorThrown);
}
});
},
error : function myfunction(jqXHR, textStatus, errorThrown) {
alert("error at transport :" + jqXHR.textStatus);
},
complete : function completefunc() {
alert('ajax completed all requests');
}
});
return false;
});

The first ajax sucess spelling problem make correction success then it will work

In your first ajax call, changesucess to success ?

I have modify your code first ajax request success portion spelling mistake.
sucess : function sfn(data, textStatus, jqXHR) {
Change to
success : function sfn(data, textStatus, jqXHR) {
Second error at end of request is
Remove extra code
return false;
});
and Put return false; after closing complete method.
e.g.
complete : function completefunc() {
alert('ajax completed all requests');
}
return false;
});

Related

Eror 500 with ajax and codeigniter

I have a problem with calling ajax on my view on codeigniter website. Ajax is calling method in controller on same project.
I have ajax search, which is work correctly. When I chose one of results, he open a new tab and show me a detail information from database. In some cases when I click on some results(I didn't find rule when it will be happening), ajax return me a 500 error, without go into controller method, but when I refresh the page (F5) he shows me a correct result. Did someone have a same problem, or can help me to fix it?
Here is my ajax call:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '<?=site_url('index/ajax_read_details')?>',
dataType: 'json',
cache: false,
async:true,
data: {'param':'<?=$selected?>'},
beforeSend: function (xhr) {
$('#loading').show();
},
success: function (data) {
$('#loading').hide();
var details = '<tr>' +
'<td>'+data['title']+'</td> '+
'<td>'+data['code']+'</td>' +
'</tr>';
$('#data >tbody').append(details);
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: '+ errorThrown);
}
});
});
</script>
I know now that he didn't go into controller method "ajax_read_details" in index controller in case when it give me an 500 error.But when I refresh, he go into that method and do it correctly job. In both cases, he send a same values but in first he didn't return values, after refresh page he give me a values :(
Short controller method is:
public function ajax_read_details()
{
$param = $this->input->post('param');
echo json_encode(array('title' => $param, 'code'=>param));
}

how to check image exist or not in my local system using ajax

We have image in D:\img\need.png. We need to know image exist or not.We tried like this:-- It's call error method always
$.ajax({
url:'http://www.himansuit.com//modiyojana.jpg',
type:'HEAD',
error: function(jqXHR, textStatus, errorThrown)
{
alert("file does not exist");
console.log(textStatus);
console.log(jqXHR);
console.log(errorThrown);
},
success: function()
{
alert("file exists do something here");//file exists do something here
}
});
Please guide me .What wrong in my code .How check file exist or not in my system using ajax call
We got Error this
In server side use script like this.
<?php $filename = '/path/to/foo.txt'; if (file_exists($filename)) {echo "1";//existed
}else { echo "0";//not}?>
In front end script do ,
$.ajax({
url:'checkfileexists.php',
type:'post',
error: function(jqXHR, textStatus, errorThrown)
{
alert("file does not exist");
console.log(textStatus);
console.log(jqXHR);
console.log(errorThrown);
},
success: function(data)
{
if(data==1)
alert("file exists do something here");//file exists do something
else
alert("not");
}
});
As told in comments, you first have to set up a web server on your local OS. For example Apache, or even a node web server. Installation depends on your system.
Then, you have to write a script which receives a file path and check if there is a file here.
So, your ajax call will looks like that:
$.ajax({
url: 'http://localhost/script_path/script.php' //or script.js, or...
+'?path=D:/img/need.png',
type:'GET',
error: function(jqXHR, textStatus, errorThrown)
{
console.log(textStatus);
console.log(jqXHR);
console.log(errorThrown);
},
success: function( response )
{
if( response )
alert("file exists do something here");//file exists do something here
else
alert("file does not exist");
}
});
edit
To check if a file exists, hosted on a different domain, without having a CORS restriction:
function checkFileExists( url ){
var img= document.createElement('img');
img.style.display= "none";
img.onload= function(){ alert( url + " exists")};
img.onerror= function(){ alert( url + " does not exists")};
img.src= url;
}
checkFileExists("http://www.himansuit.com/modiyojana.jpg");
checkFileExists("http://www.fakedomain.com/modiyojana.jpg");

About Form , Ajax

I have a HTML form with ID hello
and i have ajax like this
jQuery(document).ready(function($) {
$("#hello").submit(function(){
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "/blog/ajaxphp/registration_check.php",
type: "post",
data: {formData:serializedData},
datetype: "JSON"
});
request.done(function (response, textStatus, jqXHR){
console.log("hellosss");
if(jQuery.parseJSON(response).success==undefined){
$form.unbind('submit').submit();
}else{
return false;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("error");
});
return false;
});
});
But Submit button is not working . i mean it is working if i pressit two times ..
It logs this
Uncaught TypeError: object is not a function in this line $form.unbind('submit').submit();
Question :
How do i make form enable submit when jQuery.parseJSON(response).success==undefined is true otherwise disable form to submit .
How do i disable ajax button while ajax process is being performed.
$("#hello").submit(function(){
return false; <-- You are exiting the function right away
//nothing runs here
Use evt.preventDefault();
$("#hello").submit(function(evt){
evt.preventDefault();
or if you really want to use return, but it at the BOTTOM.
Also the return false in an asynchronous Ajax call does nothing. It is impossible to return anything from an asynchronous call.
EDIT
and you have a typo
if(jQuery.parseJSON(response).sucess==undefined){ <-- that is not how you spell `success`
Double Edit, see if breaking it up into two parts work.
$form.unbind('submit');
$form.submit();

Chaining AJAX handlers with jQuery Deferred

I just can't seem to get a handle on jQuery's $.Deferred handling of AJAX calls.
What I want to do is execute three AJAX calls, each of which performs some processing on the returned data. The success call of the third AJAX call requires that the processing from the first two calls be complete, but the order of the first two calls does not matter.
Here is my code, and a jsFiddle:
var firstAjax = $.getJSON('/echo/json/')
.done(
function(data, textStatus, jqXHR){
//do some initialization here based on the data
alert(1);
return jqXHR.promise();
}
);
var secondAjax = $.getJSON('/echo/json/')
.done(
function(data, textStatus, jqXHR){
//do some initialization here based on the data
alert(2);
return jqXHR.promise();
}
);
$.when(firstAjax, secondAjax)
.done(
$.getJSON('/echo/json/')
.done(
function(data, textStatus, jqXHR){
//do some initialization here that relies on the initialization of the first and second calls being complete
alert(3);
}
)
);
Sometimes, but not always, "3" is alerted before "1" and "2". I have no problem with performing the third AJAX call immediately but its done handler needs to execute last.
you can do
var firstAjax = $.getJSON('/echo/json/').done(
function(data, textStatus, jqXHR){
//do some initialization here based on the data
alert(1);
return jqXHR.promise();
}
);
var secondAjax = $.getJSON('/echo/json/')
.done(
function(data, textStatus, jqXHR){
//do some initialization here based on the data
alert(2);
return jqXHR.promise();
}
);
$.when(firstAjax, secondAjax)
.done(function(){
$.getJSON('/echo/json/')
.done(
function(data, textStatus, jqXHR){
//do some initialization here that relies on the initialization of the first and second calls being complete
alert(3);
}
)
});
you miss the "function(){" on this line $.when(firstAjax, secondAjax).done(function(){
http://jsfiddle.net/ACBJs/1/

check if ajaxcall has been made in ie7

I have an ajax call in my document ready function. But in about 1 out of 10 times in ie7, the ajax function doesnt get called at all.
Is there a way to check if the ajax call has been made, otherwise run it again until it either runs in to the error or success functions? The problem only occurs when i run the page in ietester -> ie7 mode. Thanks
code: http://jsfiddle.net/jxEj5/
You could setup a variable as a monitor, and a timer to issue an ajax call every 5 seconds until the ajaxCall is finished.
The monitor is set through var gotAjax = false and when the Ajax is succeeded, it is set to true gotAjax = true.
Instead of call the $ajax directly, you set a time clock through setTimeout(ajaxCall, 5000). With in the timer, if the ajaxCall is set, you clear the timer through clearTimeout(ajaxCall)
$(function() {
var gotAjax = false;
var ajaxCall = function () {
if (!gotAjax) {
$.ajax({
url: '../SentinelOperationsUI/GenericHandler.ashx',
dataType: 'json',
data: {
'FunctionName': 'GetActivity',
'SearchType': 'Single',
'postedData': JSON.stringify($('#content').data('postedData'))
},
success: function(data) {
gotAjax = true;
$('#content').data('activityKey', data.SENTINEL_OPERATION_ACTIVITY_KEY);
$.ajax({
url: '../SentinelOperationsUI/ajax/activityviews/' + data.ACTIVITY_VIEW,
dataType: 'html',
success: function(data) {
$('#content').hide().html(data).fadeIn(200);
$('#parenttabs, #tabs, #tabs2, #parenttab-1, #parenttab-2').tabs();
}
});
}
});
}
else {
clearTimeout(ajaxCall);
}
};
setTimeout(ajaxCall, 5000);
});
This is an example in jQuery that should help you debug it
If you're not using jQuery, i will need to see your code :)
The error function will occur in case a 404 or similar error occurred, and in case the ajax DID occur but some unexpected response was returned and your javascript bugged, the try .. catch will help you detect the error more easily :)
$.ajax({
url: "file.php",
type : "POST",
contentType : "application/x-www-form-urlencoded",
success: function(response){
try{
// Success code
}catch(e){
// Possibly you have an error in your JS, this should alert it to you
alert(e.message);
}
},
error : function(jqXHR, textStatus, errorThrown){
// Error occured, lets see what's wrong
alert("error " + textStatus + ": " + errorThrown);
}
});

Categories

Resources