I want to make the option I selected fix to after AJAX POST.
Currently I am doing the work manually.
I put the value at OnChange in the HiddenField,
and after doing AJAX POST, re-insert the value selected in "ddlUserCont".
<select id="ddlUserCont" onchange="ddlUserCont_Onchange(this);"></select>
function ddlUserCont_Onchange(obj) {
document.getElementById("<%=hidSelddlUserCont.ClientID %>").value = obj.value;
}
-> After AJAX POST action..
function btnTest_Click() {
// ... Some logic
$.ajax({
type: "POST",
cache: false,
url: "../../WebServices/WebService.asmx/GetTest",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
OnSuccess_GetTest(data, sTestVal);
},
error: function (request, status, error) {
console.log("code:" + request.status + "\n" + "message:" + request.responseText + "\n" + "error:" + error);
}
});
}
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value;
document.getElementById("ddlUserCont_" + sSelPageName).selected = "true";
}
Do I use UpdatePanel ?
Why is it getting reset? is the page reloading? or is some other script resetting it?
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value; // get the value from the hidden field
document.getElementById("ddlUserCont).value = sSelPageName; // set it on the select options element
}
Just make sure that select has an option child element with value=<sSelPageName> at the time.
Related
I have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});
function getSearchClients() {
console.log('Inside searchClient');
$('#progressbar').show();
var searchClientPhone = document.getElementById('searchClientCellPhoneNo').value;
$.ajax({
type:"POST",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
success: function(result){
$("#progressbar").hide();
$("#example td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue >= document.getElementById("selectedClientRewardPoints").value)) {
thisCell.css("background-color","#FF0000");
}
}
);
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
window.location.reload(true);
}
});
}
The textboxes do not become visible in the ajax success, though I have verified control goes to the success block.
I think this is because of window.location.reload(true), why do you think to reload the page again!!
As per my understand, when the page is reloaded for a second time, the search input parameter becomes null/empty, so in this snippet var cellValue = parseInt(thisCell.text()); cellValue is null/undefined.
Because of this, the following two lines do not function as expected
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
If you want to keep your status like :
$("#progressbar").hide();
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
you should store a boolean in the user localstore or a cookie (on ajax success). Then on the page just have a document ready:
$(document).ready({
if(localstorage/cookie) { / check the status of your cookie or localstorage
$("#progressbar").hide();
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
// clear the cookie or the localstorage
}
});
I hope this gives you an idea man...
There were a few things wrong. Primarily you were reloading the page, which is probably the main issue.
Also you had a few small issues with your number parsing and validating. I have fixed it below.
function getSearchClients() {
console.log('Inside searchClient');
$('#progressbar').show();
var searchClientPhone = $('#searchClientCellPhoneNo').val();
$.ajax({
type: "POST",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
success: function (results) {
$("#progressbar").hide();
$("#example td").each(function () {
var thisCell = $(this);
var cellText = thisCell.text();
// This will update your textbox...
$("#selectedClientName").val(result.clientName);
// And this is an example of updating based on an array of data.
result.transactions.forEach(function(result){
// Create a list item and append it to the list.
$('<li></li>').text(result).appendTo('#resultList');
});
// If the cell text is a number...
if (!isNaN(cellText)) {
// Parse the text to a base 10 integer...
var cellValue = parseInt(thisCell.text(), 10);
if (cellValue >= $("#selectedClientRewardPoints").val()) {
thisCell.css("background-color", "#FF0000");
}
}
});
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
// Do not reload the page.
}
});
}
Thanks #JimmyBoh for the pointers, this is how I fixed the issue :
1) Used struts2-json library. In struts.xml, added below:
<package name="json" extends="json-default">
<action name="searchClientCellPhoneNo" class="com.intracircle.action.RedeemAction" method="searchClientCellPhoneNo">
<result type="json">
<param name="root">jsonData</param>
</result>
</action>
</package>
2) In the action class, added a jsonData Map as follows :
private Map<String,Object> jsonData = new HashMap<String,Object>();
Added getters and setters for jsonData
public Map<String,Object> getJsonData() {
return jsonData;
}
public void setJsonData(Map<String,Object> jsonData) {
this.jsonData = jsonData;
}
In the action method, added data to be returned to jsp to the jsonData Map as follows :
public String searchClientCellPhoneNo() {
clientList = userdao.getClientsList(searchClientPhone);
if(clientList != null && clientList.size() > 0) {
selectedClientName = clientList.get(0).getProfileName();
jsonData.put("selectedClientName",selectedClientName);
int storeId = ((Stores)SecurityUtils.getSubject().getSession().getAttribute(SESSION_CONSTANTS.SESSION_STORE)).getStoreId();
selectedClientRewardPoints = redeemDao.getCountRewardPointsForClientForStore(storeId, clientList.get(0).getId());
jsonData.put("selectedClientRewardPoints", selectedClientRewardPoints);
}
viewRedeemScheme();
return SUCCESS;
}
3) In the jsp ajax method, did the following changes : Make sure, you add dataType:'json' and if you want to print the ajax result using alter, stringify it.
$.ajax({
type:"GET",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
dataType: 'json',
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
success: function(result){
alert("result: " + JSON.stringify(result));
console.log("Result " + result);
$("#selectedClientName").val(result.selectedClientName);
$("#selectedClientRewardPoints").val(result.selectedClientRewardPoints);
$("#progressbar").hide();
$("#example td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue >= document.getElementById("selectedClientRewardPoints").value)) {
thisCell.css("background-color","#FF0000");
}
}
);
$("#selectedClientName").show();
$("#selectedClientNameLabel").show();
$("#selectedClientRewardPointsLabel").show();
$("#selectedClientRewardPoints").show();
}
});
Thanks everyone for the help, especially #JimmyBoh.
I have an ajax request, whereby I am installing a magento shop automatically, and when the process is done, it would redirect the user to the newly created shop. Here are my codes:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
The way this is done:
After every 4 seconds the function installStatus is run, which will output the current progress in JSON format. My problem is, this function needs to be executed simultaneously with the function post().
This is not happening, the installStatus is only run after the first function has been completed.
What is wrong?
You are executing installStatus when you define it. So this:
setInterval(installStatus(),4000);
needs to be
setInterval(installStatus, 4000);
The new XMLHttpRequest has a nice progress event you can listen to show the user the upload progress.
Here's the spec with a nice demo: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
Initially you should call installStatus() only once and then inside the method inside ajax success you should update the procent in the progress bar and call it recursively the same method. On the server side you can save the current procent in a cookie and with every recursive call you can update the cookie and return the procent.
I have a web-page with the following script
Javascript
function LinkClicked() {
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
}
});
}
How do I stop the user from repeatedly clicking whilst the query is running? The call is from a cell in a grid and can't easily be disabled. Ideally, I'd like a way of doing it in the script without disabling the link on the DOM.
Here I clicked five times, and you can see five AJAX requests are sent. The page should disable the same call being repeatedly invoked whilst it is already running.
Thanks in advance.
You could have an external variable tracking the state
var linkEnabled = true;
function LinkClicked() {
if(!linkEnabled){
return;
}
linkEnabled = false;
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
linkEnabled =true;
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
linkEnabled = true;
}
});
}
This also has the advantage that you can choose to enable other effects of this function if you want, and only prevent the repeat ajax calls.
(Note that ideally you would want to stick the external variable in a closure or a namespace rather than making it a global).
Disable a button when user clicks it, and set disabled to false when you get response from ajax.
Declare a variable outside of the function with an initial value of false:
var pending = false;
When you make the request, you'd do:
if (pending == true) {return;}
pending = true;
This makes it stop if you're already running, and when the request is done:
pending = false;
Now even without a button, the request won't fire multiple times.
As a side note, your data doesn't need to be a string. You can just do:
data: {stage: stage, stop: stop, nDays: nDays}
you can just check use this
var ajax_stat = false
function doing_ajax(){
if(ajax_stat) return;
ajax_stat = true;
var xmlRequest = $.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
ajax_stat = false;
}
});
}
Use below code. it will not make multiple ajax calls.
function LinkClicked() {
if($(window).data("ajaxRUnning")){
return;
}
$(window).data("ajaxRUnning",true);
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
$(window).data("ajaxRUnning",false);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
$(window).data("ajaxRUnning",false);
}
});
}
I have this code using this code I am inserting an item from one list box to other list box. I need to set the default selection for tagrget list box item when it is added.
please can any body help me out how to set the deafult selection to the list box.
How to set the default selection to the currently added item to the list box
function DoInsert(ind) {
var sourceIndex = $("#lstAvailableCode").val(); /// Selected Item to add
var targetIndex = $("#lstCodelist").val(); /// added item to the list box(target list box)
var success = 0;
var rightSelectedIndex = $("#lstCodelist").get(0).selectedIndex;
var functionName = "/Ajax/SaveCodeforInsert";
if (ind == "plan") {
functionName = "/Ajax/SaveCodeforInsertForPlan";
}
$.ajax({
type: "POST",
traditional: true,
url: functionName,
async: false,
data: "ControlPlanNum=" + $("#ddControlPlan").val() + "&LevelNum=" + $("#ddlLevel").val() + "&ColumnNum=" + $("#ddlColumn").val() + "&SourcbaObjectID=" + sourceIndex + "&TargetbaObjectID=" + targetIndex + "&userID=<%=Model.userID%>",
dataType: "json",
error: function (data) {
alert("Error Adding Code");
FinishAjaxLoading();
},
success: function (data) {
if (data == 0) { success = 1; } else { success = data; }
FinishAjaxLoading();
}
});
could you use
.focus()
Example:
$("#lstCodelist").focus();
you can use .focus in the success callback to set the focus
$("element").focus()