Lock state multiple ajax calls - javascript

I have multiple rich text editors on single page.
There is autosaving of both done by ajax calls that are separate.
Each text editor is saved on focus lost or when focus is inside of editor every 20 seconds.
When editor is not saved and user navigates away I am showing "navigate away warning".
Now I need to manage warning that when one editor is in the middle of saving and the other one finishes earlier warning will not be removed.
What I have now:
editorOneIsSaving=true;
SetNavigateAwayNotification();
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorOne",
data: mypostdata1,
success: function (msg) {
editorOneIsSaving = false;
if (!editorTwoIsSaving) {
RemoveNavigatingAwayNotification();
}
updateSavedInfo();
},
});
For second editor:
editroTwoIsSaving=true;
SetNavigateAwayNotification();
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorTwo",
data: mypostdata2,
success: function (msg) {
editorTwoIsSaving = false;
if (!editorOneIsSaving) {
RemoveNavigatingAwayNotification();
}
updateSavedInfo();
}
});
I was looking into adding object to array or list but it is not really nice in javascript. This way I would know who is the owner of lock or if there would be more editors I could make sure that same editor is not taking lock multiple times.
Maybe I am just overthinking and I should go with simply counter which if is 0 then remove navigate away.

One way to do this would be to add a counter to each ajax call to save.
You increment the counter before sending the data to the server and decrement it in the promise.
something like the following
function showSavingMessage(){
//code to show message
}
function removeSavingMessage(){
// code to remove message
}
var ctr = 0;
function saveData(){
showSavingMessage();
ctr++;
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorXXX",
data: mypostdata2,
success: function (msg) {
if (ctr > 0){
ctr--;
} else {
removeSavingMessage();
}
}
});
}
You can handle errors any way you like. may be change the "saving" message to error message.
You can also pass the url and the data to the saveData function to make it reusable, so you have a single function with the Ajax code.

Related

How to put ajax request inside function and call it when necessary?

I have an ajax request:
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
I want to be able to put this inside a function that waits for me to trigger it with a return call. I am not exactly sure how to word it, I am new to javascript and jquery. But basically, I want to trigger this ajax call with various different button clicks and instead of having to put the ajax call inside every button click event, I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
Heres an example of a click event Id like to call the ajax request function with. Thanks!
$(function() {
$(".task-listing").click(function() {
//Call Ajax function here.
});
});
Callbacks are well-suited for this scenario. You can encapsulate your ajax call in a callback function.
function apiCall() {
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
}
You can now hook apiCall()method as a callback to button click.
$(function() {
$(".task-listing").click(apiCall);
});
By doing this you will able to achieve this.
I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
EDIT:
Note:
This is lead to start, you can alter this according to your requirement.
Is this not working for you? ↓↓
$(function() {
$(".task-listing").click(function() {
let pid = $(this).attr("id"); //get any other value which you want to pass in function, say url
someFunction(pid); // pass any other parameters, eg- someFunction(pid, url)
});
});
function someFunction(pid){ // someFunction(pid, url)
$.ajax({
type: 'POST',
url: '/get-result.php', // url: url
dataType: 'json',
data: 'pid=' + pid,
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
}
});
}

How do I pass value from a javascript function to C# Code behind?

I have a dynamic button which have unique id's, I'm getting the id of the clicked button like so:
$("button").click(function() {
//I want to pass this.id to my btnDetails_Click event in C# or to a variable Property(for efficiency)
});
How do I do this? Sorry noob in javascript.
I won't code precisely for you, but maybe what I will include could help and point you to right direction in your own conclusion.
Okay, let us say that the page you are using is called Page.aspx, and the method is called Done
var values = {"0,","1","2"};
var theids = JSON.stringify(values);
// Make an ajax call
$.ajax({
type: "POST",
url: "Page.aspx/Done",
contentType: "application/json; charset=utf-8",
data: {ids: theids },
dataType: "json",
success: function (result) {
alert('Alright, man!');
},
error: function (result) {
alert('Whoops :(');
}
});

Adding Spinner Function inside Jquery onclick function

I have the following code.
----HTML Part---
<div id="Optimize" class="Div"> Optimize </div>
----Jquery Part---
$('#Optimize').click(function()
{
var form_data = new FormData();
form_data.append('action',"Opt");
var perlURL= "$code";
$.ajax({
url: perlURL,
data: form_data,
type: 'post',
datatype: "script",
success: function(result) {
},
});
});
Once the user clicks on Optimization, the following jquery code will execute and display results to user. Now i need to insert a Spinner whenever user clicks Optimization to show that data is loading. Once data gets loaded, spinner should stop. So i have the two functions. If i insert those 2 functions, the Jquery code will look like this.
$('#Optimize').click(function()
{
startSpin(); // ------------------------START SPIN HERE----------------
var form_data = new FormData();
form_data.append('action',"Opt");
var perlURL= "$this_code";
$.ajax({
url: perlURL,
data: form_data,
type: 'post',
datatype: "script",
success: function(result) {
stopSpin(); // --------------STOP SPIN HERE --------------
},
});
This code should work as expected. i.e. spinner should start as soon as user clicks on "Optimize". but it doesnot start. i get a feeling that it straight away performs execution in asynchronous manner.
How can i ensure that the user executes startSpin(); first and then the later part of the function ?
I have read about promise() and have tried various ways to perform both functions simultaneously. but couldnt succeed.
This will surely help someone. I tried using the bind function in jquery and tried to bind both the functions to the onclick event. it was unsuccessful.
However after several retries, i thought of using the jquery function inside a javascript function. So now both the functions are plain javascript functions. I did the following.
-----------HTML CODE-------------
----------START SPIN HERE------------
<div class="Div" onclick="startSpin();setTimeout(function() { runopt(); }, 100); " > Run Optimization </div>
-----------SCRIPT CODE-------------
<script type="text/javascript">
function runopt() {
//$('#Optimize').click(function()
// {
var form_data = new FormData();
form_data.append('action',"Opt");
var perlURL= "$code";
$.ajax({
url: perlURL,
data: form_data,
type: 'post',
datatype: "script",
success: function(result) {
},
});
stopSpin(); // -----------------STOP SPIN HERE -----------------
// });
}
Commented out values in the script means earlier code. I have used both the functions at html side onclick and delayed the second function by 100 msec. it did the trick. the first function was allowed to run and then the second function { runopt() } was run.

Check if $.ajax has already been sent and if so then retrieve data without resending

I have this ajax request that is sent from javascript in my page
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
async: false,
success: function(data) {
alert(data);
}
});
This returns an array of items with some text and ...
Now if the user clicks on a certain button the data needs to be copied to another place on the page(div)
Is there any way I can get the data again from the file (in the network tab "chrome") without resending the request?
Put the response in global variable (dataArray) and every time check that variable has value or not. So that request will not send further time. Also, you can use that global variable (dataArray) in other methods.
var dataArray = "";
function getData(){
if(dataArray != ""){
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
//async: false,
success: function(data) {
//alert(data);
dataArray = data;
}
});
}
}

AJAX jQuery Freezing IE/Safari

At my wits end here.
Im running this script
<script type="text/javascript" charset="utf-8">
jQuery(window).ready(function(){
//alert('running');
var sold = false;
var leads = [
["one", 120],
["two", 0]
];
jQuery.each(leads, function(index, value) {
var _data = "";
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?lead=" + value[0],
dataType: "json",
//contentType: "application/json; charset=utf-8",
timeout: value[1] * 1000, //Yes i need to wait 120 seconds for "one"
async: false,
cache: false
}).success(function(data) {
_data = data;
console.log(data.status + " Lead: "+ value[0]);
if (data.status == "sold") {
sold = true;
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?resetSession",
dataType: "json",
//contentType: "application/json; charset=utf-8",
async: false,
cache: false
}).success(function() {
//Silence is golden.
});
window.location.href = data.link;
}
}).error(function(jqXHR, textStatus){
console.log("ERROR: " + textStatus + " Lead: " + value[0]);
});
if (_data.status == "sold") {
return false;
}
});
if (!sold) {
//If we get here, None of the leads were sold.
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?resetSession",
//contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false
}).success(function(data) {
//Silence is golden.
});
window.location.href = '/thank-you.php';
}
});
</script>
The script takes some info submits it to submit_lead.php which will return a json response with a status, a message and a link. Once it has this link it needs to call the same script with ?resetSession and the redirect the user to the link received.
I have a sync turned off because I need to wait until I get a response from "one" before trying "two", because if I receive a link there's no point trying the next one.
When the script runs on FF or Chrome, it runs fine. There is a little animation that plays while the requests are going through and once a link is returned it redirects accordingly.
When the script runs in <= IE8 or Safari, the page sorta loads half then waits (The animation loads but does not animate.). Once the ajax response has returned the page suddenly springs to life and then you get redirected.
I have tried window ready and document ready and nothing seems to work.
Any suggestions would be appreciated.
Thanks for reading.
Like i said in the comments, turn async back on.
Add your redirect or whatever operations you want to perform in the callback from the ajax function. Thats most likely the reason you are getting locking.

Categories

Resources