I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}
Related
I have made this custom ajax function to avoid writing ajax code multiple times. My issue is that if there is no option passed for failcmds variable & obj.status is "failure", then also code execution moves to the succcmds code block & execute available commands. e.g. reload(2500) in the example code.
Pls help me to identify the missing part.
Custom Ajax function
function gr(url, varr, succcmds, failcmds, divid, drestype) {
$.ajax({
url: url,
type: "POST",
data: varr,
beforeSend: function(){
$('#loadingDiv').show();
},
complete: function(){
$('#loadingDiv').hide();
},
success: function(response){
if(response){
var obj = $.parseJSON(response);
if(obj.status == "failure") {
console.log('failcmds : ' + failcmds);
if(obj.message) {
gm("e",obj.message);
}
if(typeof failcmds === "undefined") {
return;
}else {
$.each(failcmds,function(index, value) {
value;
});
}
}else if(obj.status == "success"){
if(obj.message) {
gm("s",obj.message);
}
if(succcmds && succcmds !== null) {
$.each(succcmds,function(ind, val) {
val;
});
}
if (divid && divid !== null){
if(drestype && drestype == "html"){
$("#"+ divid).html(obj.data);
}else{
$("#"+ divid).append(obj.data);
}
}
}
}else{
gm("e", "Invalid Request");
}
},
error: function(){}
});
}
Sample usage of function
$(document).on("click", '.xyz', function() {
var d = $(this).prop('id');
var data = 'd='+ $(this).prop('id') + '&typ=sts';
gm('c','Are you sure you want to do this?');
$(document).on("click", '#btnYes', function() {
var sarr = [reload(2500)];
gr(basepath + "deletereq?", data, sarr);
});
});
then also code execution moves to the succcmds code block & execute available commands
No it doesn't. You executed those commands before you even called your function:
var sarr = [reload(2500)];
This will execute reload(2500) and put the result of that execution in the sarr array.
Instead, wrap that in a function:
var sarr = [function () { reload(2500); }];
Then you can later execute that function where you like:
$.each(succcmds,function(ind, val) {
val();
});
Basically you want your "commands" to be executable functions, not the results of executed functions.
building html that use jquery to get data from web API.
In the beginning of my script I did a function that checks the value of dropdown (what is selected) and according to the selected it's fill the global variable.
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.168.0.1';
}
}
after defining the function I calling it immediately to check it and fill the variable.
finally by Clicking on search it should check what selected from dropdown and according to that fill again the variable and start GET function with the modified URL
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
Problem: After I start the debug the $selcom always get the value of '192.168.5.37' doesn't matter what I do.
Tried to debug it many ways but couldn't find why it's assigning that value.
Please assist as it should be so simple but I must missed something.
Here is the part of the code from the begining:
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.16.0.1';
}
}
chkdom();
alert($seldom);
alert($("#dropdomain").val());
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
type: "GET",
dataType: 'Jsonp',
success: function (result) {....}
Problem: After I start the debug the $selcom always get the value of '192.168.5.37' doesn't matter what I do.
Don't:
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.168.0.1';
}
Do:
if ($("#dropdomain").val() === 'Europa') {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val() === "Canada") {
$seldom = '172.168.0.1';
}
See documentation of jQuery.val():
.val(value)
Description: Set the value of each element in the set of matched
elements.
value argument
Type: String or Number or Array
A string of text, a number, or an array of strings corresponding to the value of each matched element to
set as selected/checked.
So, calling $("#dropdomain").val('some value') writes a value to the $("#dropdomain") element. To read its value, call $("#dropdomain").val().
Try the code below:
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val() === 'Europa') {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val() === 'Canada') {
$seldom = '172.16.0.1';
}
}
chkdom();
alert($seldom);
alert($("#dropdomain").val());
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
type: "GET",
dataType: 'Jsonp',
success: function (result) {....}
This condition $("#dropdomain").val('Europa') is always writing and is being evaluated as true.
So, you need to compare the values:
var drop = $("#dropdomain").val();
if (drop === 'Europa') {
$seldom = '192.168.5.37';
} else if (drop === "Canada") {
$seldom = '172.16.0.1';
}
Please note that I had already tried to apply the solution on Handling session timeout in ajax calls but did not worked for me.
In an ASP.NET MVC5 project, I open pages by rendering partialview via AJAX as shown below:
function renderPartial(e, controller, action) {
var controllerName = controller;
var actionName = action;
if (String(actionName).trim() == '') {
return false;
}
if (typeof (controllerName) == "undefined") {
return false;
}
var url = "/" + controllerName + "/" + actionName;
$.ajax({
url: url,
data: { /* additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
error: function (jqXHR, textStatus, errorThrown) {
var message = errorThrown;
if (jqXHR.responseJSON != null) {
message = jqXHR.responseJSON.message;
}
},
success: function (data) {
var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
requestedUrl = window.location.href;
}
// if the url is the same, replace the state
if (typeof (history.pushState) != "undefined") {
if (window.location.href == requestedUrl) {
history.replaceState({ html: '' }, document.title, requestedUrl);
}
else {
history.pushState({ html: '' }, document.title, requestedUrl);
}
}
//Load partialview
$("#div-page-content").html(data);
}
});
};
On the other hand, when session timeout and call this method by a hyperlink, there is an empty white page on the partialview field where partialview page should be rendered. So, is it possible:
1) to display a partialview at this field?
2) to redirect user Login page?
Note: I would also be happy if you suggest a smart way to Handle Session Expire in ASP.NET MVC. Thanks in advance...
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.