Show alert after reloading page - javascript

I have tried this function but it displays the alert then refreshes the form. I want something that refreshes the page and then displays the alert. How can I do that?
$(document).on('click', '#insert', function(){
var address = $('#to_address').val();
var amount = $('#amount').val();
var this_email = $('#this_email').val();
var this_bal = $('#this_bal').val();
if(address != '' && amount != '' && this_email != '' && this_bal != '' )
{
$.ajax({
url:"WithdrawChk.php",
method:"POST",
data:{address:address, amount:amount, this_email:this_email, this_bal:this_bal},
success:function(data)
{
$('#alert_message').html('<div class="alert-success">'+data+'</div>');
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
else
{
alert("All Fields are required");
}
});

You can do something like this
success: function(data) {
window.sessionStorage.setItem("successData" , JSON.stringify(data));
window.location.reload();
}
$(document).ready(function(){
if(window.sessionStorage.getItem("successData")){
$('#alert_message').html('<div class="alert-success">' + JSON.parse(window.sessionStorage.getItem("successData")) + '</div>');
}
})
Make sure to clear the session storage before the ajax call. And you can store only string values in the local or session storage so you have to stringify the json object to store it in session storage , and then if you want to use it , you have to parse that.

As per Rorys suggestion you can store the data in localStorage and check for if it exists on the jQuery page ready function.
var localStorage = window.localStorage;
$(function(){
var data = localStorage.getItem("data");
if(data !== null){
$('#alert_message').html('<div class="alert-success">' + JSON.parse(data) + '</div>');
localStorage.removeItem("data");
}
});
success: function(data) {
localStorage.setItem("data", JSON.stringify(data);
window.location.reload();
}

Related

How to pass a variable to php page beside this.serialize with AJAX

I need to pass a variable from ajax to php beside the serialize data.
My code will explain what I mean:
$('#update_form').on('submit', function(e){
e.preventDefault();
var total = parseFloat($('#total').text()); // This is the var I want to pass
if($('.check_box:checked').length > 0)
{
$.ajax({
url:"pages/Model/multiple_update.php",
method:"POST",
data:$(this).serialize(),
success:function()
{
alert('Data Updated');
$('#multiple_update').attr('disabled', 'disabled');
fetch_data();
}
});
}
});
serialize() creates a querystring in the format a=1&b=2 so you could add to it like this
var total = parseFloat($('#total').text());
var qs = $(this).serialize() + '&total=' + total;
and then send that
data:qs,
Or
data:$(this).serialize() + '&total=' + total,

$("#signInModal").modal('hide'); not a function

I trying to hide modal after login success by call ajax
But I cannot use $("#signInModal").modal('hide'); ($().modal is not a function. i don't understand how it work, I use bootstrap 4 's modal. How can l use this or the other way to hide modal ##
i really use it ontop, and I cannot use it again.Please help me ##
here is my code
$("#signUpButton").on('click', function () {
$("#signInModal").modal('hide');
})
})(jQuery);
// //validate password on login event
(function ($) {
$(document).ready(function(){
$("#login").submit(function(event){
event.preventDefault();
var txtUsername = $("#exampleInputEmail1");
var txtPassword = $("#logInPassword");
var username=txtUsername.val().trim();
var password=txtPassword.val().trim();
console.log(username);
console.log(password);
if( username != "" && password != "" ){
$.ajax({
url:'login.php',
type:'Post',
data:{username:username,password:password},
success:function(response){
var msg = "";
console.log(response);
if(response == 1){
$("#signInModal").modal('hide');
console.log(response);
}else{
msg = "Invalid username and password!";
}
if (!strIsEmpty(msg)) {
console.log(msg);
return;
}
}
});
}
});
});
})(jQuery);
I think you included js in the footer of the page. Please call the function after it.

how do make waiting for ajax to complete

I newbie.
I have a function application for employment (apply-job).What I do is submit the request with an ordinary link, with a click-function applied on it but processing time is quite long. I want disable "#apply-job" avoid click too much or disable window and fade for ajax to complete. Thank.
My JS:
$("#apply-job").click(function() {
if($('#jobcandidate-name').val() != '' && $('#jobcandidate-email').val() != '' && $('#jobcandidate-phone').val().length >= 10 && $('#jobcandidate-address').val() != '' && ($("input[name='CandidateAttachment[2][fileAttachment][path]']").val() != undefined || $('#jobcandidate-curriculum_vitae').val() != '') ){
let data = $('#apply-job-form').serialize();
let roleArticle = $('.show_new_role :input').serialize();
if ($('#apply-job-form').find('.has-error').length){
swal("Thử lại", "Vui lòng kiểm tra lại thông tin!", "error");
} else {
$.ajax({
url: '$urlRequest',
type: 'POST',
dataType: 'html',
data : data + '&' + roleArticle
}).done(function(result) {
response = JSON.parse(result);
if (response.type == "success"){
let checkReload = swal("Thành công", "Cảm ơn bạn đã ứng tuyển!", "success");
checkReload.then(function() {
location.reload();
});
}
});
}
} else {
if ($("input[name='CandidateAttachment[2][fileAttachment][path]']").val() == undefined && $('#jobcandidate-curriculum_vitae').val() == '') {
$('#jobcandidate-curriculum_vitae').parents('.form-group').find('.txt-lable').css('color','red');
$('#jobcandidate-curriculum_vitae').parents('.form-group').find('.show_error2').text('* Không được bỏ trống');
}
swal("Thử lại", "Vui lòng kiểm tra lại thông tin!", "error");
}
});
ajax has await option. You can use it to make the execution wait till the ajax all is done. Make sure you combine it with async which will tell there's an asynchronous step in the function. See below snippet
$("#apply-job").click(async function() {
......
await $.ajax({
......
});
Update: to make sure the click is disabled while ajax is working, add a disabled attribute and assign the click only when the attribute is not present. Clear the attribute once process is complete.
$("#apply-job:not([disabled])").click(async function() {
$("#apply-job").attr("disabled","disabled")
......
await $.ajax({
......
$("#apply-job").remoeAttr("disabled")
});

How to hide current page

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();
}
}

Make a textbox visible and other css changes on ajax success

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.

Categories