I have an onclick function btn-book, and inside it is a for loop for the data of Ajax. I'm sure that data have values but i dont get it why i always get null. here is the code of the onclick.
$('#mapContainer').on('click', '.btn-book', function(e){
e.preventDefault();
var id = e.currentTarget.id;
var routeOrigin = route_Search.origin;
routeOrigin = routeOrigin.filter(function(e){return e});
var url = base_url;
for(var i = 1; i <= desNo; i++){
$.ajax({
type: "POST",
url: url,
data: {
id: id,
origin: $('#route-origin'+i).val(),
origin_contactperson: $('#origin-contactperson'+i).val(),
origin_company: $('#origin-company'+i).val(),
origin_phonenumber: $('#origin-phonenumber'+i).val(),
origin_notes: $('#origin-notes'+i).val(),
origin_Lng: routeOrigin[i-1].lng(),
origin_Lat: routeOrigin[i-1].lat(),
},
success: function(msg)
{
console.log(msg);
},
error: function()
{
alert("An error occured while updating. Try again in a while");
}
})
}
});
use like this.
$('#mapContainer').on('click', '.btn-book', function(e){
e.preventDefault();
var id = e.currentTarget.id;
var routeOrigin = route_Search.origin;
routeOrigin = routeOrigin.filter(function(e){return e});
var url = base_url;
var origin = [], origin_contactperson = []
for(var i = 1; i <= desNo; i++){
origin.push($('#route-origin'+i).val());
origin_contactperson.push($('#origin-contactperson'+i).val());
.....
}
$.ajax({
type: "POST",
url: url,
data: {
id: id,
origin: origin,
origin_contactperson: origin_contactperson,
origin_company: origin_company,
origin_phonenumber: origin_phonenumber,
origin_notes: origin_notes,
origin_Lng: origin_Lng,
origin_Lat: origin_Lat
},
success: function(msg)
{
console.log(msg);
},
error: function()
{
alert("An error occured while updating. Try again in a while");
}
})
});
Related
I have two javascript function which populate some data using jquery json. Both working fine but problem is that second function getting called before first one execute. My code is :
$(document).ready(function () {
loadSubject();
getTopic();
});
function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
alert('22222');
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
success: function (data) {
var subjectDivs = "";
var divs = "";
var i = 1;
$.each(data, function (index, value) {
divs = "";
// Some code here
i = i + 1;
});
subjectDivs = subjectDivs + divs;
alert('11111');
$('#cCount').val(i);
document.getElementById('accordion').innerHTML = subjectDivs;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
function getTopic() {
var c = $('#cCount').val();
alert(c);
for (var i = 1; i <= c; i++) {
var subId = $('#hdn_' + i).val();
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Topic', UserRecId: 0, ParentId: subId },
dataType: 'json',
success: function (data) {
var topicDivs = "";
var divs = "";
tDivs = '';
$.each(data, function (index, value) {
divs = '';
divs = '<div class="row">';
divs = divs + '<div class="subject">' + value.Name + '</div>';
divs = divs + "</div>";
topicDivs = topicDivs + divs;
});
$('#sDiv_' + i).html(topicDivs);
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
}
This is not the way how ajax get executes. If you put two jquery ajax requests one by one then they will execute in sequence by it is not necessary that second request will be executed after first request completes or response of first request is received.
If you want this to happen then there are two ways
1. Use async:'false'
This makes a request to wait until response is recieved before executing next statement in javascript.
What does "async: false" do in jQuery.ajax()?
2. Use callbacks
Write the second function which you want to execute in success or complete callback of your first ajax request.
jQuery ajax success callback function definition
Try adding return statement before $.ajax({}) within both loadSubject and getTopic , to return jQuery promise object , which can be handled at deferred.then
function loadSubject() {
return $.ajax()
}
function getTopic() {
return $.ajax()
}
loadSubject().then(getTopic);
function a() {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.resolve(1)
}, 2000)
}).promise().then(function(data) {
console.log(data)
})
}
function b() {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.resolve(2)
}, 2000)
}).promise().then(function(data) {
console.log(data)
})
}
a().then(b)
You have to add async:false in your first ajax request, it stop next execution till first ajax request will complete its execution.
So your first function like this
function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
async:false,
success: function (data) {
var subjectDivs = "";
var divs = "";
var i = 1;
$.each(data, function (index, value) {
divs = "";
// Some code here
i = i + 1;
});
subjectDivs = subjectDivs + divs;
alert('11111');
$('#cCount').val(i);
document.getElementById('accordion').innerHTML = subjectDivs;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
Call second function from first ajax success function
$(document).ready(function () {
loadSubject();
});
function loadSubject() {
// code here
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
success: function (data) {
//code here
getTopic(); // Second function calling
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
Now when first function is executed successfully then second function will be called.
I want to find a way,give a dom as parameter and get data, from image_preview.
and separate image_preview.model() and image_preivew.on_chage() is event handler
make image_preview reusable not hardcode inside
I espect I will call image_preview pass dom in parameter, and return src as response , then I can use repsponse do something like append ...
var image_preview = {
on_change: function(wrap_dom, input_dom) {
$(wrap_dom).on('change', input_dom, function(event) { // I have to use on change because there are possible the `input dom` is new append...
var el_obj = $(this)[0];
var form_data = new FormData();
var file_length = el_obj.files.length;
for (var i = 0; i < file_length; i++) {
form_data.append("file[]", el_obj.files[i]);
}
image_preview.model(form_data).done(function(response) {
// console.log(response); // this is work
return response;
});
});
},
model: function(form_data) {
return $.ajax({
url: uri_public+'/admin/ajax/preview_file',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
// async: false
});
}
}
var app_thumbnail = {
preview_controller: function() {
var wrap_dom = '.thumbnail';
var input_dom = '.upload-form input';
var result = image_preview.on_change(wrap_dom, input_dom);
// pass result to render view like append dom....
},
render: function() {
},
}
app_thumbnail.preview_controller();
Here is the easiest thing you can do:
var image_preview = {
on_change: function(wrap_dom, input_dom) {
$(wrap_dom).on('change', input_dom, function(event) {
var el_obj = $(this)[0];
var form_data = new FormData();
var file_length = el_obj.files.length;
for (var i = 0; i < file_length; i++) {
form_data.append("file[]", el_obj.files[i]);
}
image_preview.model(form_data).done(function(response) {
app_thumbnail.preview_controller(response);
});
});
},
model: function(form_data) {
return $.ajax({
url: uri_public+'/admin/ajax/preview_file',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
// async: false
});
}
}
var app_thumbnail = {
preview_controller: function(response) {
var wrap_dom = '.thumbnail';
var input_dom = '.upload-form input';
var result = response;
}
}
// If you want to initialize it.
// image_preview.on_change(..., ...);
I have the following:
var q = new app.models.OverwriteLineItemsProcess();
q.set('id', $("#process_id").val());
q.saveSource($("#source_quote").val());
q.lockSource();
saveSource is sending data to the backend using ajax. So is lockSource.
I want to execute in this SEQUENTIAL manner: saveSource >> lockSource.
How do I write the q.js to make it work?
By q.js, I mean https://github.com/kriskowal/q
UPDATE: added saveSource and lockSource
saveSource: function (quotation_id) {;
var type = "PUT";
var verb = "Updated";
var headers = {
'X-HTTP-Method-Override': type
};
var url = app.base_url + "/overwrite_line_items/" + this.id;
this.set('source_quote', quotation_id);
var data = this.toFormData();
var result = false;
var currentModel = this;
var settings = {
headers: headers,
type: type,
url: url,
data: data,
success: function(json) {
response = JSON && JSON.parse(json) || $.parseJSON(json);
console.log(response);
currentModel.lockSource();
$("#facebox-source-quote-status").html('<font color="green">SELECTED</font>');
},
error: function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
},
dataType: 'json'
};
$.ajax(settings).done(function() {
});
},
lockSource: function () {
var type = "PUT";
var verb = "Updated";
var headers = {
'X-HTTP-Method-Override': type
};
var url = app.base_url + "/quotations/is_editable/" + this.attributes.source_quote;
var data = this.toFormData();
var result = false;
var currentModel = this;
var settings = {
headers: headers,
type: type,
url: url,
data: data,
success: function(response) {
console.log(response);
},
error: function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
},
dataType: 'json'
};
$.ajax(settings).done(function() {
});
},
The jQuery.ajax function which you're using already returns a promise for its result. You just need to return that from your functions:
saveSource: function (quotation_id) {;
…
var settings = {
headers: headers,
type: type,
dataType: 'json', // jQuery will automatically parse it for you
url: url,
data: data
};
return $.ajax(settings).done(function() {
// ^^^^^^
$("#facebox-source-quote-status").html('<font color="green">SELECTED</font>');
// notice I did remove the currentModel.lockSource(); call from the callback
}, function() {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
});
},
lockSource: function () {
…
var settings = // analoguous, no callbacks here
return $.ajax(settings).fail(function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
});
}
Now you can easily chain them:
var q = new app.models.OverwriteLineItemsProcess();
q.set('id', $("#process_id").val());
q.saveSource($("#source_quote").val()).then(function(saveResponse) {
console.log(saveResponse);
return q.lockSource();
}).done(function(lockResponse) {
console.log(lockResponse);
});
You don't even need Q for that. If you want to use it, wrap the $.ajax() calls in a Q() invocation, as explained in the Converting JQuery Promises to Q section of the docs.
I have the following javascript:
$('#edit_category').on('click','#btn_save_category_name',function(){
currently_edit.text($('#txt_edit_category').val());
edit_category_name(currently_edit,current_category_id);
$('#edit_category').modal('hide')
})
function edit_category_name(name, id){
$.ajax({
type: 'POST',
url: '/Category/edit_team_category',
dataType: 'json',
data: {
request: 'ajax',
name: name,
id: id
},
success: function (data) {
}
});
}
Now when i attempt this i get the following error: called 'click' called on an object that does not implement interface HTMLElement.
But if i comment the function line out aka : edit_category_name(currently_edit,current_category_id);
everything works fine.
Can anyone tell me why this is happening?
Update my full script
var mode = 'team';
var currently_edit = '';
var current_team_id = 0;
var current_category_id = 0;
jQuery(document).ready(function(){
//Main click function for Team (selection of team)
$('#team_wrapper').on('click', '.panel-heading', function () {
if(mode === 'team'){
current_team_id = $(this).siblings('small').text()
title = $(this).find('.text-white').text();
var i = 100;
$('#span_search').hide();
$('#btn_new_team').fadeOut();
$('.col-lg-3').each(function(){
$('.alt').toggle('slow');
$(this).fadeOut(300,function(){
$(this).remove();
});
});
$('#team_title').text('Select Category');
$('#btn_new_category').delay(500).fadeIn();
$('#selected_team_name').text(title);
$('#selected').delay(695).fadeIn();
$('#span_search').delay(500).fadeIn();
$('#back').delay(500).fadeIn();
generate_categories();
mode = 'category';
}else{
$(this).next('div').find('a')[0].click();
}
})
$('#team_wrapper').on('click', '.btn_administrate', function(){
current_team_id = $(this).next('.team_id').text();
load_team_members(current_team_id);
});
//Modal category:
//create
$('#btn_create_category').click(function(){
add_category($('#txt_create_category').val());
$('#group-form').modal('hide');
$('#txt_create_category').val('');
})
// edit
$('#team_wrapper').on('click','.team_category_edit',function(){
current_category_id= $(this).next('input').val()
edit_mode('txt_edit_category',$(this).closest("div").prev().find("h3"));
})
$('#edit_category').on('click','#btn_save_category_name',function(){
currently_edit.text($('#txt_edit_category').val());
edit_category_name(currently_edit,current_category_id);
$('#edit_category').modal('hide')
})
});
function edit_category_name(name, id){
$.ajax({
type: 'POST',
url: '/Category/edit_team_category',
dataType: 'json',
data: {
request: 'ajax',
name: name,
id: id
},
success: function (data) {
}
});
}
in this example:
var current_team_id = 1;
var current_category_id = 2;
What is the value of currently_edit? I am assuming this is a jQuery object not a text value. Try the following instead.
edit_category_name(currently_edit.text(),current_category_id);
Update
As Barmar mentioned, currently_edit.text(...) is invalid based on what you have shared. perhaps what you meant to do was:
currently_edit = $('#txt_edit_category').val();
Try changing this line currently_edit.text($('#txt_edit_category').val());
with this : currently_edit = $('#txt_edit_category').val();
I am trying to get a Twitter access token from their oauth api. The plugin I am using is this https://code.google.com/p/oauth/source/browse/#svn%2Fcode%2Fjavascript. So far I only get "401 failed to validate signature and token".
Strange thing is that my ajax call becomes 'GET' request even though I set type:'POST'. Seems like jquery is changing the type from POST to GET. I don't know why it does that. I am running it on my Mac. I appreciate your help/hints/suggestions/advises. Thanks!
$(function() {
function myCallback(resp) {
console.log(resp);
}
var TwitterAPI;
TwitterAPI = (function() {
var consumer_key = null;
var consumer_secret = null;
function TwitterAPI(cons_key, cons_secret) {
this.consumer_key = cons_key;
this.consumer_secret = cons_secret;
}
TwitterAPI.prototype._url = function (data) {
if (typeof data == 'array') {
return array_map([ // TODO
this, '_url'], data);
} else if ((/boolean|number|string/).test(typeof data)) {
return encodeURIComponent(data).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
} else {
return '';
}
}
TwitterAPI.prototype.myCallback = function(resp) {
console.log(resp);
}
TwitterAPI.prototype.getRequestToken = function() {
var accessor = {
consumerSecret: this.consumer_secret, //this.consumer.consumerSecret,
tokenSecret: ''
};
var message = {
method: "POST",
action: "https://api.twitter.com/oauth/request_token",
parameters: {
oauth_signature_method: "HMAC-SHA1",
oauth_consumer_key: this.consumer_key, //this.consumer.consumerKey
oauth_callback: this._url("http://127.0.0.1/foobar/libs/oauth/wtf.html"),
}
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var target = OAuth.addToURL(message.action, message.parameters);
message.parameters.oauth_signature = this._url(message.parameters.oauth_signature);
console.log(message.parameters);
$.ajax("https://api.twitter.com/oauth/request_token",
{ url: "https://api.twitter.com/oauth/request_token",
type: 'POST',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: "myCallback",
data: message.parameters,
success: function(data, textResp, xhr) {
console.log(data);
},
error: function(xhr, text, err) {
console.log(text);
}
});
};
return TwitterAPI;
})();
api = new TwitterAPI(key, secret);
$('button#request').on('click', function(e) {
e.stopPropagation();
api.getRequestToken();
});