Change text using javascript not working in chrome - javascript

I want to change text to "saving ... " when a link clicked, then I use ajax, query resets to save the form. one i receive the request i need to change the text back to normal.
In Firefox the work fine, but in chrome the text get change once response received. There is a delay in changing the text.
See my code:
function submitForm(frm, action) {
var performAction = true;
var isChange = false;
document.getElementById('saveButton').innerHTML = 'processing....';
freezeWindow();
if ((document.getElementById("primaryIframe") != null) && (action == "Save")) {
var frameId = 0;
functionSaveIframes(frameId, isChange);
} else {
if (performAction == true) {
sessionStorage.setItem('singlePage', 'false');
window.open('www.google.com', '_self');
}
}
}
function functionSaveIframes (frameId,isChange) {
var iframes = {"0":"frame1","1":"frame2"};
var url = {"0":"/test/testPrimaryPostAction.do",
"1":"/test/test2PrimaryPostAction.do"};
var iframe = document.getElementById(iframes[frameId]);
var doc = iframe.contentWindow.document;
var form = doc.forms[0];
var isEdited = doc.forms[0].isEdited.value;
var formData = $(form).serializeArray();
formData.push({name: 'fwdval', value: 'Save'});
var myUrl = url[frameId];
if(isEdited == 'true'){
isChange=true;
$.ajax({
type: "POST",
async: false,
cache: false,
url: myUrl,
data: formData,
success: function(data) {
doc.forms[0].isEdited.value = "false";
frameId = frameId + 1 ;
if (frameId < 9) {
functionSaveIframes(frameId,isChange);
}else if (frameId == 9){
reloadErrors(isChange);
}
},
error: function(e){
$("#freezeFrame").css("display","none");
alert("error Saving Data in " + iframes[frameId] + "Please try again");
}
});
}
else{
frameId = frameId + 1 ;
if (frameId < 9) {
functionSaveIframes(frameId,isChange);
}
else if (frameId == 9){
reloadErrors(isChange);
}
}
}
<li><a id="saveButton" href="javascript:submitForm( document.forms[0], 'Save' );"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save</a>
</li>

**In Success Function you need to change text by using .html() **
Please check the below example.

Related

JavaScript/JQuery: Stop script until modal form submitted

Okay, this is probably an easy one, but I just can't wrap my head around how to do it from the examples online.
Background: My code displays a modal form $("#multi_med_modal_form") asking for user input. The input from the modal form is used to finish populating some html $('#med_output') before moving on to the next line from an AJAX response.
Problem: After the modal displays, the code continues to execute subsequent lines from the AJAX response so that by the time the user submits the modal form, the variables have changed and the program (understandably) throws an error.
Question: How do I make JavaScript/JQuery wait for stop the code at $("#multi-submit-btn").click() below?
$("#med_input_form").submit(function(event){
console.log('Med Input Form Submitted');
event.preventDefault();
var serializedData = $(this).serialize();
$.ajax({
type: "POST",
url: '{% url "medrec_v2:post_medrec" %}',
data: serializedData,
success: function(response) {
$('#med_output').html("");
var med_ajax = JSON.parse(response["med_output"]);
med_ajax.line.forEach(line => {
console.log(line)
input_text = line[0]
med_list = line[1]
dose = line[2]
if (med_list.length == 0) {
// <!---Need new Modal!-->
} else if (med_list.length > 1){
input_name = modal_option_builder("multi", line);
$("#multi_med_modal").modal('show');
//!!!---------- WAIT FOR USER TO SUBMIT MODAL FORM HERE!! ------------------!!!//
$("#multi-submit-btn").click( () => {
radio_id = $("input[name='" + input_name + "']:checked").val()
for (i = 1; i < med_list.length; i++) {
if (med_list[i].id == radio_id) {
radio_med = med_list[i];
break;
}
};
radio_html_name = html_builder(radio_med)
$('#med_output').append("<tr><th scope='row'>"+radio_html_name+"</th><td>"+dose+"</td><td>"+ radio_med.med_commonuses+ "</td></tr>");
$("#multi_med_modal").modal('hide');
})
} else {
html_name = html_builder(med_list[0]);
$('#med_output').append("<tr><th scope='row'>"+html_name+"</th><td>"+dose+"</td><td>"+ med_list[0].med_commonuses+ "</td></tr>");
}
})
}
})
});
/*<------------Build title and body for Modal form----------->
send to form to select correct medicaiton*/
function modal_option_builder(modal_type, line) {
if (modal_type =="multi") {
$("#multi_med_modal_form").empty()
input_text = line[0]
med_list = line[1]
$("#modaltitle").html('Multiple medications found for "'+input_text+'"!'); //set modal title to line string where multiple medications found
form_lines=[]
for (i = 0; i < med_list.length; i++) {
input_type = "radio";
input_id = input_type +"_"+med_list[i].id;
input_name = input_type+'-'+ input_text.replace(' ', '-');
$("#multi_med_modal_form").append(`
<div class="form-check">
<input class="form-check-input" type="`+input_type+`" name="`+input_name+`" id="`+input_id+`" value="`+med_list[i].id+`">
<label class="form-check-label" for="`+input_id+`">`+med_list[i].display_name+`</label>
</div>`);
};
return input_name;
} else if (modal_type = "no_match") {
$("#modaltitle").html('No matches found for"'+med_list[0]+'"!');
$("#multi_med_modal_form").html("");
}
};```
Like I said, this is probably easy, I just can't figure out how to do it. Thank you!
I figured it out. There's no way to "stop" the code from executing like I was describing (as far as I know). I just had to assign an id to the html element I was creating to populate with user feedback afterwards.
Here's the code:
/*------------AJAX FUNCTION---------------------*/
$("#med_input_form").submit(function(event){
console.log('Med Input Form Submitted');
event.preventDefault();
var serializedData = $(this).serialize();
$.ajax({
type: "POST",
url: '{% url "medrec_v2:post_medrec" %}',
data: serializedData,
success: function(response) {
$('#med_output').empty();
prevMedList = []
var med_ajax = JSON.parse(response["med_output"]);
line_no = 0
med_ajax.line.forEach(line => {
console.log(line)
line_no += 1
input_text = line[0]
med_list = line[1]
dose = line[2]
sig = line[3]
$('#med_output').append("<tr id='output_"+line_no+"'></tr>");
if (med_list.length == 0) {
$("#no-med-modal").modal("show");
console.log("no-med-modal shown")
$("#multi-submit-btn").click( () => {
});
} else if (med_list.length > 1){
input_name = multi_modal_builder(line);
$("#multi-med-modal").modal('show');
//---------- WAIT FOR $("#multi-submit-btn").click() HERE!! -----------//
$("#multi-submit-btn").click( () => {
radio_id = $("input[name='" + input_name + "']:checked").val()
for (i = 1; i < med_list.length; i++) {
if (med_list[i].id == radio_id) {
radio_med = med_list[i];
break;
}
};
radio_html_name = html_builder(radio_med)
$('#output_'+line_no).append("<tr><th scope='row'>"+radio_html_name+"</th><td>"+dose+"</td><td>"+ sig+ "</td><td>"+radio_med.med_commonuses+ "</td></tr>");
$("#multi-med-modal").modal('hide');
prevMedList.append([radio_id,dose]);
})
} else {
for (i in prevMedList) {
if (med_list[0].id == prevMedList[0]){
prev="true";
break;
}};
if (prev=="true"){continue};
html_name = html_builder(med_list[0]);
// console.log(html_name);
$('#output_'+line_no+'').append("<th scope='row'>"+html_name+"</th> <td>"+dose+"</td> <td>"+ sig+ "</td> <td>"+med_list[0].med_commonuses+ "</td>");
prevMedList.append([radio_id,dose]);
}
})
}
})
});

Unable to see the source of the problem with the code for sending data to PHP file

I am very sorry to appear much ignorant but I have experienced this problem for long and I am now completely unable to understand why my JQuery function is not working.
I need this code to send data to PHP file which I am sure its working. I have tried to code everything with php but I have found there are place that I will have to include ajax.
$(document).ready(function(){
$('#sending').on('submit', function(event){
event.preventDefault();
if(($('#receiver_id1').val() == '0') && ($('#receiver_id2').val() == '0') && ($('#receiver_id3').val() == '0'))
{
alert("Please fill in the recipient!");
return false;
}
else if($.trim($("#message").val()) == '')
{
alert("You cannot send an empty message.");
return false;
}
else if($('#subject').val() == '')
{
var retVal = confirm("Are you sure to send a message without a subject?");
if( retVal == true ) {
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
type:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
} else {
return false;
}
} else
{
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, from_user_name:from_user_name, from_user_id:from_user_id, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
});
});
I really need help. I absolutely need this script to work. Thanks in advance.

Save values of dynamic generated HTML using javascript

I m generating dynamic html with its id. You can see the below link for the dynamic generated HTML.
Dymanic Generated HTML
So for saving this, I need some suggestion on how to save it in javascript. I tried the other fields of the HTML..
function SaveNPEDetails() {
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
// Need to write saving logic for dynamic generated html here.
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
As per our discussion you can try something like
function SaveNPEDetails() {
var data = [];
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
var chs = $("#dvNPEAddData").children(".addNPEData")
for (var i = 0; i < chs.length; i++) {
var d = {};
var ch = chs[i];
var val = $(ch).find("input[name='TerRouteName']").val();
d[$(ch).find("input[name='TerRouteName']").attr("name")] = val;
val = $(ch).find("select[name='CableType']").val();
d[$(ch).find("select[name='CableType']").attr("name")] = val;
val = $(ch).find("select[name='CableSize']").val();
d[$(ch).find("select[name='CableSize']").attr("name")] = val;
val = $(ch).find("input[name='NoLiveFibre']").val();
d[$(ch).find("input[name='NoLiveFibre']").attr("name")] = val;
data.push(d);
}
var d = JSON.stringify(data);
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields , myJsonXML : d}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
Using your example in the fiddle I've done the following
$('#submit').click(function() {
var DashboardFields = {},
status = true;
$.each($('input[type="text"]'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '') {
alert(id + ' field is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
$.each($('select'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '--Select--' || $(v).val() == null) {
alert(id + ' select is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
if(!status){
alert('you have empty fields');
} else {
console.log(DashboardFields); //Here should be your Ajax Call
}
});
JsFiddle
I've used your example with ID's and created a filter in order to take dynamically the fields not by ID's, I used the ID's to map the DashboardFields object but I strongly encourage to use name or other data- param and change the jQuery code after (the line with var id=$(v).attr('id'))
Hope this helps you

Using jquery validate during form submission

I'm really new at this and I'm encountering an issue where the alert for a ddl is popping up, but in the background the form is still submitting with a blank from the value "" on the 'Select' option
The ddl:
Type
My scripts:
<script type="text/javascript">
function saveCallReport() {
var selectedFranchises = "";
var selectedGroups = "";
var selectedContacts = "";
var selectedTopics = "";
var ID = $('#<%=txtID.ClientID %>').val();
if (ID == '') ID = '0';
var Created = $('#<%=txtCreated.ClientID %>').val();
var Confidential = document.getElementById('<%=chkConfidential.ClientID %>').checked;
var Description = $('#<%=txtDescription.ClientID %>').val();
var Employee = $('#<%=ddlEmployee.ClientID %>').val();
var Priority = $('#<%=ddlPriority.ClientID %>').val();
var Type = $('#<%=ddlType.ClientID %>').val();
// Get Selected Franchises
var LstRight = document.getElementById("<%=lstSelectedFranchises.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedFranchises = selectedFranchises + LstRight.options[i].value + ',';
}
if (selectedFranchises == null)
selectedFranchises = "";
// Get Selected Groups
LstRight = document.getElementById("<%=lstSelectedGroups.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedGroups = selectedGroups + LstRight.options[i].value + ',';
}
if (selectedGroups == null)
selectedGroups = "";
// Get Selected Contacts
LstRight = document.getElementById("<%=lstSelectedContacts.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedContacts = selectedContacts + LstRight.options[i].value + ',';
}
if (selectedContacts == null)
selectedContacts = "";
// Get Selected Topics
LstRight = document.getElementById("<%=lstSelectedTopics.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedTopics = selectedTopics + LstRight.options[i].value + ',';
}
if (selectedTopics == null)
selectedTopics = "";
var obj = {
id: ID,
created: Created,
hqemployee: Employee,
type: Type,
priority: Priority,
confidential: Confidential,
description: Description,
franchises: selectedFranchises,
groups: selectedGroups,
contacts: selectedContacts,
topics: selectedTopics,
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%= ResolveUrl("~/CallReportDetail.aspx/saveCallReport") %>',
data: JSON.stringify(obj),
dataType: "json",
success: function (result) {
$('#txtID').val(result.d);
window.location.replace("/CallReports/Details?Id=" + result.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("There was a problem saving the Call Report: " + thrownError);
}
});
return false;
}
var submit = 0;
function CheckDouble() {
if (++submit > 1) {
alert('Saving...');
return false;
}
}
$(function formValid() {
$("[id*=btnSave]").click(function() {
var ddlType = $("[id*=ddlType]");
if (ddlType.val() == "") {
alert("Please select a type!");
return false;
}
});
});
</script>
My submit button:
<td style="padding-left: 720px;">
<asp:LinkButton ID="btnSave" Type="submit" runat="server" Text="Save" OnClientClick="CheckDouble(); return saveCallReport();" UseSubmitBehavior="false" CssClass="btn btn-primary btn-sm"/>
</td>
Can anybody tell me where I may be going wrong? I had a notion that I need a submitHandler, but don't have a clue how to write that into this code.
Ok there's a few issues here.
You should avoid adding OnClientClick and JQuery .click() events on the same button. It's just bad style, and a bit confusing.
You're submitting the data via JQuery ajax, so there's no need for a LinkButton. Just use a normal html button.
Your saveCallReport() function handles the success and failure outcomes all by itself, there's no need to return anything.
The CheckDouble() method will increment the submit value even if the validation fails, so then a subsequent click on the button after you select from the ddl will alert the Saving... message, which is not the intended behavior. You should just add/remove a disabled attribute on the button while it's submitting.
So anyway, here's what I would suggest. The html button:
<button id="btnSave" class="btn btn-primary btn-sm">Save</button>
Wire up the button:
$(document).ready(function() {
$('#btnSave').click(function () {
var ddlType = $("#ddlType");
if (ddlType.val() == "") {
alert("Please select a type!");
return false;
}
$(this).attr("disabled", "disabled");
saveCallReport();
$(this).removeAttr("disabled");
});
});

Java Script if statement not working

I have javascript function that includes few if else statements for some reason one of the statements is not working properly.
Script:
function makePayment(reservationID) {
var expirationDate = $("#expirationDate").val();
var creditCard = $("#creditcard").val();
if (creditCard.length == 16 && expirationDate.length == 4) {
var month = "";
var year = "";
month += expirationDate.charAt(0);
month += expirationDate.charAt(1);
year += expirationDate.charAt(2);
year += expirationDate.charAt(3);
var monthInt = parseFloat(month);
var yearInt = parseFloat(year);
var currect;
if (monthInt > 0 && monthInt < 13 && yearInt > 12 && yearInt < 24) {
$.ajax({
url: "CreditAuthentication",
data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate,
success: function(responseText) {
currect = responseText;
console.log(responseText);
}, error: function(xhr) {
alert(xhr.status);
}});
if (currect == true) {
//
$.ajax({
type: "POST",
url: "paymentMethods",
data: "type=make&reservationID=" + reservationID,
success: function(msg) {
console.log("Paymentmade");
alert("Payment made");
//alert(CCA);
document.location = "index.jsp#reservation";
}
});
}
else if(currect === "false") {
alert("Please enter valid details. 3rd");
}
//
} else {
alert("Please enter valid details. 2nd");
}
} else {
alert("Please enter valid payment information. 1st");
}
}
I have checked in FireBug and the return value from my servlet is correct and and the console.log(responseText); displays the response in console. However for some reason this part of statement is not working and not displaying the alerts:
if (currect == true) {
$.ajax({
type: "POST",
url: "paymentMethods",
data: "type=make&reservationID=" + reservationID,
success: function (msg) {
console.log("Paymentmade");
alert("Payment made");
document.location = "index.jsp#reservation";
}
});
} else if (currect === "false") {
alert("Please enter valid details. 3rd");
}
Thanks in Advance!
Please make sure currect is not null or undefined and if it is not.
make a 'currect' global so it can be accessable:
var currect; //declare it here
$.ajax({
url: "CreditAuthentication",
data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate,
success: function(responseText) {
currect = responseText;
console.log(responseText);
}, error: function(xhr) {
alert(xhr.status);
}});
then if currect is a boolean then try:
if (currect) {
//your code
} else {
//your code
}
and if it is string:
if (currect === 'true') {
//your code
} else if(currect === 'false') {
//your code
}
You have to place the currect if/else in the success function of your ajax call.

Categories

Resources