Ajax inside ajax not working - ajax

I have a function that calls an ajax, inside that ajax another ajax needs to be executed. In the below code I gave my full function. Just to ensure that everything but the 2nd ajax works perfectly, I should point you out that before the 2nd ajax call there is an alert() function which works. That means everything works if I comment the 2nd ajax call. If I uncomment it then after the first alert a second alert should appear saying 'inside 2nd call', but nothing happens. Got any suggestions?
function get_employee_list(Parameter){
$.ajax({
url: 'resource/php/search_profile.php',
type: 'POST',
data: { var1 : Parameter},
async: false,
success: function (response) {
//alert(response);
reset_search_table();
$(response).find('employee').each(function() {
var ebasp_id = $(this).find('ebasp_id').text();
var ebasp_name = $(this).find('ebasp_name').text();
var ebasp_gender = $(this).find('ebasp_gender').text();
var ebasp_category = $(this).find('ebasp_category').text();
//var ebasp_region_type = $(this).find('ebasp_region_type').text();
//var ebasp_region_name = $(this).find('ebasp_region_name').text();
var code_sub_region = $(this).find('ebasp_sub_region').text();
var code_location = $(this).find('ebasp_location').text();
var code_office = '';
if (code_location === '0')
code_office = code_sub_region;
else
code_office = code_location;
var office = '';
//alert('before 2nd call -- '+code_office);
$.ajax({
url: 'resource/php/show_cost_center_name.php',
type: POST,
data: { var1 : code_office},
success: function(response){
office = response;
alert('inside 2nd call');
}
});
var ebasp_designation = $(this).find('ebasp_designation').text();
var ebasp_date_of_joining = $(this).find('ebasp_date_of_joining').text();
var ebasp_grade = $(this).find('ebasp_grade').text();
var ebasp_slab = $(this).find('ebasp_slab').text();
var ebasp_basic = $(this).find('ebasp_basic').text();
var ebasp_photo_upload = $(this).find('ebasp_photo_upload').text();
var ebasp_created_on = $(this).find('ebasp_created_on').text();
var ebasp_created_by = $(this).find('ebasp_created_by').text();
$("#search_table").show();
$('<tr></tr>').html('<td>'+ebasp_id+'</td>'+
'<td>'+ebasp_name+'</td>'+
'<td>'+ebasp_gender+'</td>'+
'<td>'+ebasp_category+'</td>'+
'<td>'+office+'</td>'+
'<td>'+ebasp_designation+'</td>'+
'<td>'+ebasp_date_of_joining+'</td>'+
'<td>'+ebasp_grade+'</td>'+
'<td>'+ebasp_slab+'</td>'+
'<td>'+ebasp_basic+'</td>'+
'<td>'+ebasp_created_on+'</td>'+
'<td>'+ebasp_created_by+'</td>').appendTo("#search_table");
});
},
cache: false,
});return false;
}

Related

Is there a way to show "Loading data.." option in Rally Grid(ext JS) while making the Ajax request to load the data?

I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);

Pass image through ajax using cordova

I am developing my mobile application using ionic framework and I want it to connect to my API through ajax. Currenty, in the mobile side, which is I am using Ionic Framework, I want to upload an image and pass it to my api through ajax. I am using Cordova for the upload but it seems it doesn't found the URL I indicated.
Here's the HTML
<ion-footer-bar class="bar bar-positive">
<div class="button-bar">
<button class="button icon-left ion-upload" ng-click="uploadImage()" ng-disabled="image === null">Upload</button>
</div>
</ion-footer-bar>
Here's the uploadImage() function in the controller (Just copied the code in a site. Forgot where) EDIT: added targetPath
$scope.uploadImage = function() {
// Destination URL
var url = "http://192.168.0.19/identificare_api/public/api/plants/image";
var targetPath = $scope.pathForImage($scope.image);
// File name only
var filename = $scope.image;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
var jsonparse = JSON.parse(result);
$scope.showAlert(jsonparse);
}
But in the upload part, I want to do it in ajax to indicate the method for the URL but the problem I don't know what put in data.
$.ajax({
url: "http://192.168.0.19/identificare_api/public/api/plants/image",
type: 'POST',
data:
success:function(json){
var jsonparse = JSON.parse(json);
alert(jsonparse);
},
error:function(){
alert("Error");
}
});
Can someone help me with this issue?
UPDATE: Applied here #Blauharley's comment below
I had another issue here. I returned the $_FILES['image']['tmp_name'] in the API side but it returns nothing but when I returned the $_FILES['image']['name'], it returned my_image.jpg. Why it doesn't have tmp_name?
$scope.uploadImage = function() {
// File for Upload
var targetPath = $scope.pathForImage($scope.image);
$scope.getBase64ImageByURL(targetPath).then(function(base64Image){
var blob = $scope.base64ToBlob(base64Image,'image/jpeg');
var fd = new FormData();
fd.append('image', blob, "my_image.jpg");
fd.append('user_token', "rLUrh37rfTozuBxmemHtlKMgH");
$.ajax({
url: 'http://192.168.0.19/identificare_api/public/api/plants/image',
type: 'POST',
data: fd,
contentType: false,
processData: false,
success:function(res){
alert(res);
},
error:function(err){
alert("Something's wrong with your api. Come on fix it!");
}
});
});
};
$scope.getBase64ImageByURL = function(url) {
var dfd = new $.Deferred();
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
dfd.resolve(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
return dfd.promise();
};
$scope.base64ToBlob = function(base64Image,toMimeType) {
var byteCharacters = atob(base64Image.replace('data:'+toMimeType+';base64,',''));
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: toMimeType
});
return blob;
};
ADDED: API side
public function image(){
echo json_encode($_FILES['image']['tmp_name']);
}

Ajax Post method issue with passing huge data

folks
we are facing a strange issue with jquery ( 1.8.3) and we are using cakePHP
as per the image
Our assumption is we are sending the data( about 500 +) with ajax call in POST method.
we are having this issue in all the major browsers.
as above( in chrome) , we are getting this error in console we passed 618 destinations in ajax call.
let us know the work around to solve this problem.
My ajax call is as below
function validate_test() {
$("#btn1").empty();
var ele = document.getElementById('frm_searchDateFrom').value;
var ele2 = document.getElementById('frm_searchDateTo').value;
var sub_url = '<?php echo $this->Html->url('/', true); ?>';
var url = sub_url + "admin/reports/check_originator/" + ele +"/"+ ele2 +"/"+ $("#destination").val();
alert(url);
jQuery.ajax({
type: "POST",
datatype: "json",
url: url,
success: function(data)
{
var el = $("select#btn1").multiselect();
var d;
var results=data.split(",");
for(d=0;d<results.length;d++) {
var d;
var v = results[d], opt = $('<option />', {
value: v,
text: v
});
opt.appendTo( el );
el.multiselect('refresh');
}
}
})
}
In your JQuery Ajax method instead of posting all those details as url query para meter send by wrapping those details in a object.
function validate_test() {
$("#btn1").empty();
var ele = document.getElementById('frm_searchDateFrom').value;
var ele2 = document.getElementById('frm_searchDateTo').value;
var sub_url = '<?php echo $this->Html->url('/', true); ?>';
var url = sub_url + "admin/reports/check_originator/";
var formdata=ele +"/"+ ele2 +"/"+ $("#destination").val();//put form data's in an object
alert(url);
jQuery.ajax({
type: "POST",
datatype: "json",
data:formdata,//send the form data object in post
url: url,
success: function(data)
{
var el = $("select#btn1").multiselect();
var d;
var results=data.split(",");
for(d=0;d<results.length;d++) {
var d;
var v = results[d], opt = $('<option />', {
value: v,
text: v
});
opt.appendTo( el );
el.multiselect('refresh');
}
}
})
}
Also refer this fiddle(not mine):
http://jsfiddle.net/clickthelink/Uwcuz/1/

css Property for jquery ajax success function

I'm working with MVC3, using the following jQuery AJAX call:
function Displaymaingrid () {
var Geo = $('#ddlGeo').val();
var Vertical = $('#ddlVertical').val();
var Month = $('#ddlMonth').val();
if(Vertical == "All")
{
var Flag = 1;
}
else
{
var Flag = 2;
}
$.ajax({
url: "#Url.Action("TRUnutilizedOwnershipChange", "TravelReady")",
datatype: "html",
type: "post",
data: {strGeo:Geo, strVertical:Vertical, intMonth:Month, intFlag:Flag},
error: function(){},
success: function(data){
$('.travTableContent').empty();
var text3 = data.data.lstunutilizedownershipentities;
for( var item in text3)
{
$('<tr />').html(text3[item]).appendTo('.travTableContent');
$('<td />').html(text3[item].CurrentOwnership).appendTo('.travTableContent');
$('<td />').html('' + text3[item].cnt + '').appendTo('.travTableContent');
}
}
});
}
I want to set the CSS property for success function:
$('<tr />').html(text3[item]).appendTo('.travTableContent');
I want to add the following CSS property in the above line:
("tr:odd").css("background-color", "#d0d1e2")
Where do I need to insert this line?
Add it after the "for" statement.
for( var item in text3){
$('<tr />').html(text3[item]).appendTo('.travTableContent');
$('<td />').html(text3[item].CurrentOwnership).appendTo('.travTableContent');
$('<td />').html('' + text3[item].cnt + '').appendTo('.travTableContent');
}
$("tr:odd").css("background-color", "#d0d1e2");

Ajax response and anonymous function scope

In the following code
var entryTemplate = document.getElementById('entryTemplate');
entryTemplate = entryTemplate.firstChild;
for (var ipost in posts)
{
var post = posts[ipost];
var clone = entryTemplate.cloneNode(true);
clone = $(clone);
if (post.imageURL)
{
var imgElement = document.createElement('img');
var largeImageURL = post.largeImageURL ? post.largeImageURL : post.imageURL;
imgElement.src = post.thumbPresent ? POST_THUMB_URL + '/' + post.postID : largeImageURL;
imgElement.alt = '';
clone.find('div.BlogImageURL a').attr('href', largeImageURL).text(largeImageURL);
clone.find('div.BlogImage a').attr('href', imgElement.src).append(imgElement);
// get bytesize
var postdata = 'inline_image_url=' + encodeURIComponent(post.imageURL);
postdata += '&linked_image_url=' + encodeURIComponent(post.largeImageURL);
$.ajax({
type: 'POST',
url: ASYNC_GET_BYTESIZE_URL,
data: postdata,
success: function(bytesize) {
clone.find('.BlogImageBytesize').html(bytesize);
}
});
}
else
{
clone.find('div.BlogImageURL').text('(This post contains no images)');
clone.find('div.BlogImage').remove();
}
$('#outputDiv').append(clone);
}
clone.find('.BlogImageBytesize').html(bytesize);
All ajax responses (bold line) modify the last clone, probably because the loop is finished when the first response arrives and clone points to the last clone.
How can I fix this?
Thanks.
Perhaps you could set clone as the context of your ajax call. (See docs here.) Then, I think it would work something like this:
$.ajax({
type: 'POST',
url: ASYNC_GET_BYTESIZE_URL,
data: postdata,
context: clone,
success: function(bytesize) {
$(this).find('.BlogImageBytesize').html(bytesize);
}
});
I don't know for sure if the context has to be a plain DOM element or if it can be a jQuery object, but hopefully this gets you on the right track.

Resources