How to combine 2 function with 1 function in the javascript? - javascript

I am creating the function to save data using javascript pass to backend. Now I need to combine two function with 1 function in the javascript. Because I want to click one button can run the two functions.
First function - The first function is once I've clicked the button, the images will show in the page then pass to backend to do the save function.
function save_qr(form) {
html2canvas($("#createImg"), {
onrendered: function(canvas) {
var imgsrc = canvas.toDataURL("image/png");
console.log(imgsrc);
$("#newimg").attr('src', imgsrc);
$("#img").show();
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "?f=" + loc,
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}
});
}
Second function- This function will pass to backend to do insert form data function.
function save_qr(form) {
var error_msg = new Array();
$("#" + form + " .blank").each(function() {
if ($.trim($(this).val()) == "") {
error_msg.push("The " + $(this).attr("title") + " should not be blank.");
}
});
var loc = getQueryVariable('loc');
var serialized = $('#' + form).serialize();
var extra = '&action=save';
var form_data = serialized + extra;
if (error_msg.length < 1) {
$.ajax({
type: 'POST',
url: "?f=" + loc,
data: form_data,
beforeSend: function() {
show_overLay();
},
success: function(data) {
if (data) {
console.log(data);
hide_overLay(data);
//$('#save').prop('disabled',true);
window.location = "?loc=" + loc;
} else {
hide_overLay(data);
}
}
});
} else {
alert(error_msg.join("\n"));
}
}
That means I want to do the first function first to show the image first then to do the second function. The url using same location backend within in the two functions. Hope someone can guide me how to combine these two function with 1 function. Thanks.
Noteļ¼šThese two functions are worked if do it separate.
ERROR:

Am I just blind or is it that simply. Rename the functions to save_qr1 and save_qr2 (Currently the functions have the same name) and use them in a new full_save_qr function:
function full_save_qr(form) {
save_qr1(form);
save_qr2(form);
}
The functions are processes synchronous. That means your save_qr1 will be processed before save_qr2. If you want a specific time to happen between the two functions you need to use something like setTimeout
function full_save_qr(form) {
save_qr1(form);
setTimeout(() => save_qr2(form), 1000);
}

Simply add global variable like var isImageShow = false. Call wrap your code like
var isImageShow = false;
function save_qr(form) {
if (!isImageShow) {
isImageShow = true;
// 1st function code
} else {
// 2nd function code
}
}
If you want to check condition on dataURL then declare dataURL as global variable. And update condition as if(!dataURL). Also update var dataURL = canvas.toDataURL(); to dataURL = canvas.toDataURL(); so it will use globally declared dataURL.
var dataURL = "";
function save_qr(form) {
if (!dataURL) {
html2canvas($("#createImg"), {
onrendered: function(canvas) {
var imgsrc = canvas.toDataURL("image/png");
console.log(imgsrc);
$("#newimg").attr('src', imgsrc);
$("#img").show();
dataURL = canvas.toDataURL(); // removed var from here.
$.ajax({
type: "POST",
url: "?f=" + loc,
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}
});
} else {
// 2nd function code
}
}

Related

While uploading multiple input files to the document library, Ajax executes after the loop ends in jQuery

I'm having a problem when using the jQuery .each() and .ajax() functions together when i want to upload all input file to SharePoint document library .
function checkAttachments(NewlyCreatedItemId)
{
$("[type='file']").each(function(){
var FileUploaderID=$(this).attr("id");
var attachfor=$(this).attr("alt");
var file = document.getElementById(FileUploaderID.toString()).files[0];
if (file != undefined) {
uploadDocument(FileUploaderID,attachfor,NewlyCreatedItemId);
}
else {
alert('Please, upload attachments for ');
}
});
}
function uploadDocument(uploader,attachfor,createdID) {
var files = $("#"+uploader+"")[0].files;
if (files.length > 0) {
var fileName = files[0].name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary = "ClaimAttachments";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
// Construct the Endpoint
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?#target='" + targetUrl + "'&$expand=ListItemAllFields";
uploadFileToFolder(files[0], url, function(data) {
var file = data.d;
var DocFileName = file.Name;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
FileLeafRef: DocFileName , //FileLeafRef --> Internal Name for Name Column
AttachFor : attachfor ,
RequestGUID : createdID
};
alert("File uploaded successfully!");
}, function(data) {
alert("File uploading failed");
});
} else {
alert("Kindly select a file to upload.!");
}
}
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileObj);
// Add the file to the SharePoint folder.
getFile.done(function(arrayBuffer) {
$.ajax({
url: apiUrl,//File Collection Endpoint
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function(data) {
success(data);
},
error: function(data) {
success(data);
}
});
});
}
it uploads the file of the first file uploader only because when it reach to the ajax call in function (uploadFileToFolder) go to the next iteration, how to can solve it .

How to transfer a variable value from one function to anoter function?

Actually i want to transfer the value of my variable to another function in javascript. I tried many methods. In fact I search on stackoverflow but i didn't get correct output.
When i click on button show() function runs and form open
function show(){
var target = event.target || event.srcElement;
var id = target.id;
var x = document.getElementById(id).parentElement.id; // I am getting the value of 'x' when i alert it shows correct output
//alert(x);
$.ajax({
url: 'php/retrieve_characters.php',
type: 'post',
data: {},
success: function(response) {
var data = $.parseJSON(response);
if(data!='') {
$.each(data, function(i, item) {
$('#0').attr('src',data[0].charac);
$('#1').attr('src', data[1].charac);
});
}
}
})
}
Now when form opens i click a button which is in form and new function runs
function setimage(){
var target = event.target || event.srcElement;
var id = target.id;
$.ajax({
url: 'php/retrieve_characters.php',
type: 'post',
data: {},
success: function(response) {
var data = $.parseJSON(response);
if(data!='') {
$.each(data, function(i, item) {
var parent=document.getElementById("par1");
var child = parent.lastElementChild;
while (child) {
parent.removeChild(child);
child = parent.lastElementChild;
}
var li = document.createElement("img");
li.setAttribute("id", "char"+id);
li.setAttribute("src", data[id].charac);
li.setAttribute("onclick", "show()");
li.setAttribute("class", "imgs-thumbnail");
parent.appendChild(li);
});
}
}
})
}
In function setimage() i want the value of x which is in first function.
Remember one thing I don't want to call one function into another because in both functions i m retrieving data from database which will be messed up if both functions will be concatenated.

i am transferring control to a function written in jquery ajax

function Edit() {
var mode = 2; // 2 For Edit
var Fid = 0;
var viewName = 'MemberEditor';
var actionURL = '#Url.Action("setViewMode", "Member")';
$.ajax({
type: "POST",
data: {
Mode: mode,
lFeatureId: Fid,
ViewName: viewName
},
url: actionURL,
success: function (result) {
setViewMode(result);
}
});
}
this is the function where in i am calling setViewMode(result).
but somehow it is sot being called properly..
function setViewMode(data) {
for (keyVar in data) {
if (keyVar.search("Btn") != -1) {
jQuery('#' + keyVar).attr("disabled", data[keyVar]);
} else {
jQuery('#' + keyVar).prop("readonly", data[keyVar]);
}
}
}
The control isn't getting transferred to the loop. Can anyone help please?
I think you are getting back a JSON string. Use .$parseJSON(data) to get the contents stored.

jquery iframe load dynamically

I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...

How could I trigger func when another has been completed?

I am using JQuery to collect latest tweets using Twitter API, but I am having some issues when calling two functions.
$(document).ready(function(){
JQTWEET.loadTweets();
});
This, is working ok, but then I want to call this function:
showHideTweets: function() {
alert("hola");
var ojeto = $(JQTWEET.appendTo).find(".item").first();
$(JQTWEET.appendTo).find(".item").first().css("display", "block");
},
Both functions are inside: jqtweet.js ...
loadTweets: function() {
var request;
// different JSON request {hash|user}
if (JQTWEET.search) {
request = {
q: JQTWEET.search,
count: JQTWEET.numTweets,
api: 'search_tweets'
}
} else {
request = {
q: JQTWEET.user,
count: JQTWEET.numTweets,
api: 'statuses_userTimeline'
}
}
$.ajax({
url: 'tweets.php',
type: 'POST',
dataType: 'json',
data: request,
success: function(data, textStatus, xhr) {
if (data.httpstatus == 200) {
if (JQTWEET.search) data = data.statuses;
var text, name, img;
try {
// append tweets into page
for (var i = 0; i < JQTWEET.numTweets; i++) {
img = '';
url = 'http://twitter.com/' + data[i].user.screen_name + '/status/' + data[i].id_str;
try {
if (data[i].entities['media']) {
img = '<img src="' + data[i].entities['media'][0].media_url + '" />';
}
} catch (e) {
//no media
}
var textoMostrar = JQTWEET.template.replace('{TEXT}', JQTWEET.ify.clean(data[i].text) ).replace('{USER}', data[i].user.screen_name).replace('{IMG}', img).replace('{URL}', url );
/*.replace('{AGO}', JQTWEET.timeAgo(data[i].created_at) ) */
//alert(JQTWEET.timeAgo(data[i].created_at));
$(JQTWEET.appendTo).append( JQTWEET.template.replace('{TEXT}', JQTWEET.ify.clean(data[i].text) )
.replace('{USER}', data[i].user.screen_name)
.replace('{NAME}', data[i].user.name)
.replace('{IMG}', img)
.replace('{PROFIMG}', data[i].user.profile_image_url)
/*.replace('{AGO}', JQTWEET.timeAgo(data[i].created_at) )*/
.replace('{URL}', url )
);
if ( (JQTWEET.numTweets - 1) == i) {
$(JQTWEET.appendTo).find(".item").last().addClass("last");
}
}
} catch (e) {
//item is less than item count
}
if (JQTWEET.useGridalicious) {
//run grid-a-licious
$(JQTWEET.appendTo).gridalicious({
gutter: 13,
width: 200,
animate: true
});
}
} else alert('no data returned');
}
});
callback();
},
showHideTweets: function() {
alert("hola");
var ojeto = $(JQTWEET.appendTo).find(".item").first();
$(JQTWEET.appendTo).find(".item").first().css("display", "block");
},
The problem is that if a call functions like this:
$(document).ready(function(){
JQTWEET.loadTweets();
JQTWEET.showHideTweets();
});
Second function executes before tweets has been loaded, so it have nothing to search in, because I can see the alert("hola") working, but Ojeto is 0.
I was trying to create some kind of callback inside loadTweets(); but I could not.
The callback isn't a bad idea.
change loadTweets to look like this:
loadTweets: function(callback) {
And call it here:
$.ajax({
...
success: function(data, textStatus, xhr) {
...
if (callback) callback();
}
});
And then in your DOM ready callback:
$(document).ready(function(){
JQTWEET.loadTweets(JQTWEET.showHideTweets);
});
Your other option (which I actually prefer, in general) is to use a deferred object:
loadTweets: function(callback) {
var def = $.Deferred();
...
$.ajax({
...
success: function(data, textStatus, xhr) {
...
def.resolve();
}
});
return def.promise();
}
...
$(document).ready(function(){
JQTWEET.loadTweets().done(JQTWEET.showHideTweets);
});
Try jQuery methods chaining:
$(document).ready(function(){
JQTWEET.loadTweets().showHideTweets();
});

Categories

Resources