I have a html table with onkeypress event Like :
<tr onclick="RowOnClickEvent();" class="PikerBodyRowStyle" onkeypress="return Test(event);">
<td class="PikerCellStyle" style="width:10px; text-align:left"> <input type="checkbox" value="#item.AccountHeadID" name="chkBox" /> </td>
<td class="PikerCellStyle" style="width:150px; text-align:left">#Html.DisplayFor(modelItem => item.AccountCode)</td>
<td class="PikerCellStyle" style="width:160px; text-align:left">#Html.DisplayFor(modelItem => item.AccountHeadName)</td>
</tr>
And my JavaScript function like :
function Test(e) {
// debugger;
if (e.keyCode == 13) {
if (SelectedItemID > 0) {
$.ajax({
type: "GET",
dataType: "json",
url: '#Url.Action("GetData", "ChartsOfAccount")',
data: { id: SelectedItemID },
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (xhr, status, error) {
alert(error);
}
});
}
return false;
}
}
its work good in Internet explorer but Mozilla Firefox not work.
Change
onkeypress="return Test(e);"
to
onkeypress="return Test(event);"
You cannot give a javascript action to a tablerow. Instead you can use some button or link to create your action. You can also put it in td tag. javascript actions works there.
Related
I have the following form:
<form class="footer-newsletter-form" id="footer-newsletter" method="post" action="http://xxxxxx.us1.list-manage.com/subscribe/post-json?u=xxxxxxxxxxxxxxxxxxxxxxxxx&id=xxxxxxxxxx&c=?">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.email_placeholder' | t }}" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the following jquery bit:
<script type="text/javascript">
$(document).ready(function () {
function register($form) {
jQuery.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { console.log('error') },
success : function(data) {
if (data.result != "success") {
console.log('success');
} else {
console.log('not success');
//formSuccess();
}
}
});
}
jQuery(document).on('submit', '.footer-newsletter-form', function(event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch(error){}
});
});
</script>
Which submits correctly. However, when I press the submit button what I expect to happen is that the page does not refresh and when I check the browser console I'll either see "success" or "not success". Instead what happens is I'm sent to a page that displays the following JSON message: ?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."}).
So how do I take that success message (or error if there's an error) and have the page not only remain as is, but also capture the success message so I can display a "Success" alert? The success alert I know how to do. I just need help having the browser remain where it is and tell the difference between success and error.
P.S. I'm not sure if this is relevant but the platform is Shopify. I don't think Shopify does anything to prevent the submission from going through as it should or the response coming back so I don't think it is relevant.
The whole issue was the $(document).ready(function () {}); part. For some reason unbeknownst to me that causes the event.preventDefault(); method from running and the form submits regularly. If you remove the $(document).ready(function () {}); part it'll work as intended.
My final code for anyone looking in the future:
Form:
<form class="footer-newsletter-form" method="POST" id="footer-newsletter" action="https://xxxxxxxxxxxxx.us1.list-manage.com/subscribe/post-json?c=?">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="id" value="xxxxxxxxxx">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the JS:
<script>
function register($form) {
$.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log('error')
},
success: function (data) {
if (data.result != "success") {
console.log('Error: ' + data.msg);
} else {
console.log("Success");
$($form).find("div#subscribe-result").html("<p class='success-message'>Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you!</p>");
setTimeout(function() { $($form).find("div#subscribe-result").hide(); }, 7000);
}
}
});
}
$(document).on('submit', '#footer-newsletter', function (event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch (error) {}
});
</script>
I try send from html through JScript to java two parameters:
1. nameSelectedWhisky
2. quantitySelectedWhisky
function buyFromJS() {
//
// $.getJSON("buySuccessfulWhisky",
// {
// nameSelectedWhisky:$('#nameWhiskey').val(),
// quantitySelectedWhisky:$('#numberOrderWhisky').val()
// },
// function() {
// window.location.href = "warehouseWhisky";
// } );
//}
var nameSelectedWhisky = $('#nameWhiskey').val();
var quantitySelectedWhisky = $('#numberOrderWhisky').val();
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST",
data: JSON.stringify(nameSelectedWhisky.id, quantitySelectedWhisky.id),
url: '/buySuccessfulWhisky',
success: function (msg) {
window.location.href = "warehouseWhisky";
},
error:function(){
alert("ERROR");
}
})
}
<form id="buySelectedWhiskyThroughJavaScript" method="post">
<tr th:each="buySelectedWhisky : ${buySelectedWhisky}">
<td align="center">
<img th:attr="src=${buySelectedWhisky.photo}" width="150" height="250"/>Photo</td>
<td align="center" th:text="${buySelectedWhisky.nameWhisky}">Name</td>
<td align="center" th:text="${buySelectedWhisky.describeWhisky}">Describe</td>
<td align="center" width="100">
<input type="number" style="width: 100px" min="1" th:attr="max=${buySelectedWhisky.quantityWhisky}"
placeholder="Enter quantity" name="numberOrderWhisky" id="numberOrderWhisky"/>
</td>
<td align="center" th:text="${buySelectedWhisky.price}">Price</td>
<td align="center">
<input type="hidden" name="nameWhiskey" id="nameWhiskey" th:value="${buySelectedWhisky.nameWhisky}"/>
<!--<input type="hidden" name="quantityWhiskeyInDB" id="quantityWhiskeyInDB" th:value="${buySelectedWhisky.quantityWhisky}"/>-->
<input type="button" class="buttons" onclick="buyFromJS()" name="buttonBuyWhiskey" style="width: 60px" value="Buy"/> </td>
</tr>
</form>
I add two versions JavaScript
1 Version use $.getJSON("buySuccessfulWhisky"
This version is working and java recive all parameters, BUT this version is not updating the page
window.location.href = "warehouseWhisky";
if I try to add location.reload() after "warehouseWhisky", then "buySuccessfulWhisky" is updated instead of "warehouseWhisky". Becouse if I will not update page "warehouseWhisky" I see wrong not updated information. If I'm updating the page "in the manual mode" - everything is working.
How proper update the "warehouseWhisky" page?
Next code through AJAX
Is not sending information to java
Java code to recive from JScript
#Controller
public class SuccessfulBuyWhiskey {
#RequestMapping(value = "buySuccessfulWhisky", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView view(#RequestParam("nameSelectedWhisky")String name,
#RequestParam("quantitySelectedWhisky")Integer quantityOrder) {
System.out.println("Name: = "+name);
System.out.println("Quantity: = "+quantityOrder);
function sendBuyWhiskyInJava(){
$('#buySelectedWhiskyThroughJavaScript').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/buySuccessfulWhisky',
data: {
nameSelectedWhisky: $("#nameWhiskey").val(),
quantitySelectedWhisky: $("#numberOrderWhisky").val()
},
success: function(data) {
window.location.href = "warehouseWhisky";
console.log(data)
}
})
})
}
I have a hyperlink on my page
<a id="delete-file" href="">
<img border="0" src="images/delete_.png" alt="Delete File" width="20" height="20" />
</a>
I'm trying to prevent the default action when it is clicked and run an AJAX function instead. For some reason when I click it, it just brings me to the top of the page and my my AJAX is not fired. No console error messages either.
Can someone help me with my syntax?
<!---Script to upload file link --->
<cfoutput>
<script>
$(document).ready(function() {
$('##upload-file').submit(function(event){
event.preventDefault();
$.each($('##upload')[0].files, function(i, file) {
var formData = new FormData();
formData.append('file-0', file);
ajaxUpload(formData);
});
$('##delete-file').click(function(event){
event.preventDefault();
ajaxDelete();
});
function ajaxUpload(formData) {
console.log("ajaxUpload function called");
$.ajax({
type: 'POST',
url: "actionpages/file_upload_action.cfm?ticket_id=#url.ticket_id#",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$('.loader').show();
},
complete: function(){
$('.loader').hide(3000);
},
success: function(data) {
console.log("File successfully sent.");
$("##addFileResponse").append( "File successfully sent." );
PopulateFileUploadDiv();
},
error: function(data) {
console.log(data);
}
});
}
});
function ajaxDelete() {
console.log("ajaxDelete function called");
$.ajax({
type: 'POST',
url: "actionpages/delete_attachment.cfm?ticketID=#URL.ticket_id#&file_path=#filecheck.file_path#",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$('.loader').show();
},
complete: function(){
$('.loader').hide(3000);
},
success: function(data) {
console.log("File successfully deleted.");
$("##addFileResponse").append( "File successfully deleted." );
PopulateFileUploadDiv();
},
error: function(data) {
console.log(data);
}
});
}
});
</script>
</cfoutput>
$(document).on("click","##delete-file",function(e){
ajaxDelete();
e.preventDefault();
});
Try placing any div wrapping the ##delete-file (loaded before the DOM) that you might have in place of the document.
$(document).ready(function(){
$("#wrapper-div").on("click","##delete-file",function(e){
ajaxDelete();
e.preventDefault();
});
});
If you can't get it to work with the ID because of Cold Fusion, try adding a class to the link:
<a id="delete-file" href="" class="delete-btn">
And then try
$(document).ready(function(){
$(".delete-btn").on("click",function(e){
ajaxDelete();
e.preventDefault();
});
});
This is a very long shot but I think the problem is that you are not escaping all of your hash signs. Notice at your urls:
url: "actionpages/delete_attachment.cfm?ticketID=#URL.ticket_id#&file_path=#filecheck.file_path#"
url: "actionpages/file_upload_action.cfm?ticket_id=#url.ticket_id#",
You are escaping the hash sign for your ids but not there so I'm guessing your server is malforming your Javascript, creating an error and preventing the code from executing. You should try double-pounding them too.
If it's truly an issue with the Id, then maybe you can use other jQuery Constructor like this:
jQuery ( element )
$(document.getElementById('delete-file'));
Ok, so my assumption of the error relating to the fact that my AJAX calls lost their uniqueness because the code for the AJAX was outside of my was correct. I basically had to ajust my code so that I my AJAX code was within my tag, but more importantly, that the functions were giving unique names and were passing the unique data from my output.
Here is my modified and correct code:
<cfoutput>
<table width="50%" border="0" cellpadding="5">
<tr bgcolor="##CCCCCC">
<td width="8%"> </td>
<td width="67%" ><strong>Filename</strong></td>
<td width="18%" ><strong>Actions</strong></td>
</tr>
<cfloop query="filecheck">
<tr bgcolor="###iif(currentrow MOD 2,DE('ffffff'),DE('efefef'))#" class="btnav" onmouseover="style.backgroundColor='##FFFFCC';"
onmouseout="style.backgroundColor='###iif(currentrow MOD 2,DE('ffffff'),DE('efefef'))#'">
<td><img src="images/Paper-Clip-icon.png" alt="Attachment" /><br /></td>
<td>#filecheck.file_path#
(Record-ID #ID#)
</td>
<td>
<a id="delete-file#ID#" class="delete-btn#ID#" href="">
<img border="0" src="images/delete_.png" alt="Delete File" width="20" height="20" />
</a>
<!---Script to upload file link --->
<script>
$(document).ready(function(){
$(".delete-btn#ID#").on("click",function(e){
// ajaxDelete();
console.log("Start of prevent.");
e.preventDefault();
console.log("Calling AJAX with id of #ID#.");
ajaxDelete#ID#();
});
function ajaxDelete#ID#() {
console.log("ajaxDelete function called");
$.ajax({
type: 'POST',
url: "actionpages/delete_attachment.cfm?fileID=#filecheck.ID#&ticketID=#URL.ticket_id#&file_path=#filecheck.file_path#&techID=#url.techID#&TT=#type.TT#",
data: #filecheck.ID#,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$('.loader').show();
},
complete: function(){
$('.loader').hide(3000);
},
success: function(data) {
console.log("File successfully deleted.");
$("##addFileResponse").append( "File successfully deleted." );
PopulateFileUploadDiv();
},
error: function(data) {
console.log(data);
$("##addFileResponse").append( "Something went wrong." );
}
});
}
});
</script>
</td>
</tr>
</cfloop><br />
</table>
</cfoutput>
I'm using jquery/ajax/php to log in to my website. When I check this log in functionality to my server then it's take few seconds to check log in details. So I want to show a loading image while it's check the log in details. How Can I show this loading image ?
This loading image I want to use:
<img src="images/loading-image.gif"/>
Form:
<div id="success"></div>
<form id="login_process">
<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Username</td>
<td><input type="text" name="front_username" placeholder="Username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="front_password" placeholder="Password"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="LogIn" class="submit"></td>
</tr>
<tr>
<td colspan="2">Forgot your password ? Click here.</td>
</tr>
</table>
</form>
Jquery Code:
<script>
$('#login_process').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'login_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$.each( data, function( key, value ) {
if(key !== 'error') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
window.location.href = "index.php";
}, 2000);
}
}
});
});
</script>
Here you go, you just need to get the loading-image and show it before making ajax call, when call is done you just hide it.
html
<img id="loaderAnim" src="images/loading-image.gif"/>
JS
//Hide image on page load
$('#loaderAnim').hide();
$('#login_process').submit(function(event) {
event.preventDefault();
$('#loaderAnim').show(); // Show it before making ajax call
$.ajax({
type: 'POST',
url: 'login_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#loaderAnim').hide(); // Hide always after every request
$('#success').html('');
$.each( data, function( key, value ) {
if(key !== 'error') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
window.location.href = "index.php";
}, 2000);
}
}
});
Add a class to your image tag as follows,
<img class="img-loading" src="images/loading-image.gif"/>
I'm not gonna write the CSS initial hide of the loading image or the positioning of it, hope you can do it your self.
Then easiest is to change you script as follows,
<script>
$('#login_process').submit(function(event) {
event.preventDefault();
//SHOW YOUR LOADING IMAGE
$('.img-loading').show();
$.ajax({
type: 'POST',
url: 'login_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$.each( data, function( key, value ) {
if(key !== 'error') {
$('#success').append('<p>'+value+'</p>');
}
//HIDE YOUR LOADING IMAGE
$('.img-loading').hide();
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
window.location.href = "index.php";
}, 2000);
}
});
});
</script>
Use css to hide the image initially, then modify your code as follows:
HTML:
<img class="loading" src="images/loading-image.gif"/>
JS:
$('#login_process').submit(function(event) {
event.preventDefault();
$('.loading').show();
.....
......
success: function (data) {
$('.loading').hide();
....
});
Im working on a MVC4 site, and I have a webgrid with a search textbox. My Textbox is inside a form, which will be submitted when I press enter. I also have a onkeypress script bound to the textbox, that will, after 3 sek, update my webgrid with what else is entered.
My problem is, that I only want to run the script if not the last key pressed is Enter.
My code looks like this:
#using (Ajax.BeginForm("Filter", new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "projects" }))
{
<div class="paddingTextToleft">
Search:
<input id="searching" name="searchString" type="text" value="" onkeypress="return keypressed()">
<p class="error">#ViewBag.SearchMessage</p>
</div>
<br />
}
And the script:
var timeoutReference;
function keypressed() {
if (window.event.keyCode == 13) {
//Do not run the script!
return true;
}
else {
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function () {
var value = $("#searching").val();
$.ajax({
url: '#Url.Action("Filter", "Project")',
contentType: 'application/html; charset=utf-8',
type: "GET",
dataType: 'html',
data: { searchString: value },
}).success(function (result) {
$('#projects').html(result);
});
}, 3000);
}
};
I want it to stop the script (or not run the rest of it), if the key pressed is enter.
Hope anyone can help me.
Thanks
Firstly you are not sending Event to the function.
Call it with some parameters e.g:
<input id="searching" name="searchString" type="text" value="" onkeypress="keypressed(e)">
Then accept this event in a function:
var timeoutReference;
function keypressed(e) {
if (e.keyCode == 13) {
//Do not run the script!
return;
}
else {
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function () {
var value = $("#searching").val();
$.ajax({
url: '#Url.Action("Filter", "Project")',
contentType: 'application/html; charset=utf-8',
type: "GET",
dataType: 'html',
data: { searchString: value },
}).success(function (result) {
$('#projects').html(result);
});
}, 3000);
}
};