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.
Related
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']);
}
});
}
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 :(');
}
});
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.
Below is my code..
HTML Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="body">
<div class="dropdown_div">
<select id="q_type" class="dropdown" onchange="getSubject(this.value)">
<option>Question1</option>
<option>Question2</option>
</select>
</div>
<div class="dropdown_div">
<select id="q_subject" class="dropdown">
<option>Subject1</option>
</select>
</div>
</div>
JS Code
function getSubject(val){
$("option", $("#q_subject")).remove();
var option = "<option>Subject</option>";
$("#q_subject").append(option);
$.ajax({
url: "api.path",
type: 'POST',
dataType: 'json',
data: {id: id},
async: true,
cache: false,
success: function(response) {
alert("Hi");
$("option", $("#q_subject")).remove();
var option = "<option>Subject1</option>";
option += "<option value=1234>Subject2</option>";
$("#q_subject").append(option);
}
});
}
How do I use pushState into my code and let user can click back button to return last page and then still see the ajax data?
First of all, you should save data received from ajax request to browser local storage. Afterwards, in order to show ajax result when browser "back" button was fired, you should bind statements that you are calling in ajax.success() method to window onpopstate event. To omit code duplication, it`s better to use a declared function instead of anonymous one.
function success(response) {
alert("Hi");
$("option", $("#q_subject")).remove();
var option = "<option>Subject1</option>";
option += "<option value=1234>Subject2</option>";
$("#q_subject").append(option);
}
Save data to localstorage and call success function:
$.ajax({
url: "api.path",
type: 'POST',
dataType: 'json',
data: {id: id},
async: true,
cache: false,
success: function(response) {
localStorage.setItem("response", response);
success(response);
}
});
Call success() when "back" button was fired:
window.onpopstate = function (e) {
var res = localStorage.getItem('response');
success(res);
}
I would rather suggest you to use sessionStorage which expires when the browser window is closed :)
$.ajax({
url: "api.path",
type: 'POST',
dataType: 'json',
data: {id: id},
async: true,
cache: false,
success: function(response) {
sessionStorage.setItem("DataSaved", response);
success(response);
}
});
And then
window.onpopstate = function (e) {
var res = sessionStorage.getItem('DataSaved');
success(res);
}
You can solve this using the local Storage or Session storage. You will also need to have a onload function callback, to check if there are any previous values that you stored in the local/session storage, if yes, then show that data in the select box.
I noticed this Back() issue when using Ajax to navigate an MVC-5 application from within a JavaScript generated diagram. All clicks in the diagram are handled by Ajax.
Above solutions do not replace the complete body, in the repaired cases a Back() would restore just the edit fields. In my case, I don't need that. I need to replace the entire page from the AJAX and also enable the Back button to return to my original diagram context.
I tried above solution to replace body, and I have to note, it would only trigger the window.pop event after
history.pushState({}, '')
But when the event triggered and it uses Ajax to fill the body, my Javascript would not properly re-initialize the diagram page.
I decided to use another pattern, to circumvent the the window.pop event and avoid the back-issue. Below code will not return into the Ajax code context, but instead simply replace current page, processing the Ajax return information from the server (=Controller) as a redirect link, like
var url = "/ProcessDiagram/MenuClick?command=" + idmenuparent+"_"+citem; // my Ajax
$.get(url,
function (data) {
window.location = data; // Server returns a link, go for it !
return true; // Just return true after going to the link
});
.. this will preserve the Back() context, because the browser will take care of things.
Controller side composes the redirect link, like
public ActionResult MenuClick(string command)
{
List<string> sl = command.Split(new char[] {'_'}).ToList();
var prId = int.Parse(sl[0].Substring(3));
if (sl[1] == "PU")
return Content("/ProductionUnitTypes/Details/" + UnitContextId(prId) );
if (sl[1] == "IR")
return Content("/ItemRoles/Details/" + RoleContextId(prId) );
// etcetera
}
I solved it by including the below code just before the $.get() function
$.ajaxSetup({cache: false});
It works! Try it :)
I am having trouble on calling a methode. I can do it with below codes but how to put in js var with my call?
$.ajax({
url: '#Url.Action("surfacepost", "surface", new { text = "ThisSchouldBeAJaVar" })',
method: 'GET',
success: function (data) {
}
});
In fact this mthode is getting a partial as I am going to display. So if there is a better way of dynamic load a partial using js, please also let me know.
Thanks
The problem is that the '#Url.Action()' method is executed by .NET, before the page is send to the browser, it is not aware of any javascript on the page, and the execution of the method cannot be influenced by javascript that is run after the page has 'left the server'
What you could do is create a placeholder, and replace it in javascript:
var url = '#Url.Action("surfacepost", "surface", new { text = "placeholder" })'
url.replace('placeholder', ThisSchouldBeAJaVar);
$.ajax({
url: url,
method: 'GET',
success: function (data) {
}
});
Or you could just type the url and append the var:
$.ajax({
url: '/surface/surfacepost/?text=' + ThisSchouldBeAJaVar,
method: 'GET',
success: function (data) {
}
});