I'm trying to submit a rails form using jQuery (Which I know little about) and have had success in setting up a form to submit on clicking the submit button and run a callback(I believe this is the correct terminology?), but I would also like to make it work when just hitting enter.
As it stands, hitting enter will submit data to the database but will not run the commands to append the div or clear the text field. How could I make this happen so it works the same for the enter key as it does the submit button? I've tried to wrap the code inside a function that will run when enter is hit but having no luck!
function runScript(e) {
if (e.keyCode == 13) {
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
}
I tried that with no luck.
My current, button-working, JS file:
var scrollToBottom = function(anim){
var myDiv = $(".wrap");
myDiv.animate({ scrollTop: myDiv[0].scrollHeight - myDiv.height() }, anim);
};
$(document).ready(function(){
scrollToBottom(0)
//JS to POST form
$('.submit').click(function() {
var valuesToSubmit = $('.msgform').serialize();
$.ajax({
type: 'POST',
url: window.location.href + '/messages', //sumbits it to the given url of the form
data: valuesToSubmit,// { chat_id, <%= #chat.id %> },
dataType: "JSON", // you want a difference between normal and ajax-calls
})
.done(refresherFunc)
.fail(function(){
alert("Error sending message. It would be nice to make this a flash error.");
});
return false; // prevents normal behaviour
})
});
var refresherFunc = function(json) {
// Get debugging goodies.
console.log(json);
// Set variables with JSON object data
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
Catch your form submit event with jQuery's submit() function and return false inside it. This function will be called any way you submit the form (clicking on submit button or pressing enter key). Returning false will prevent the browser from completing the form sumbittion which lets you do whatever you want with it.
See example: http://jsfiddle.net/vgk4wu46/
Related
I do not have much grip on javascript and having problemswith it.
My data is coming from a server and the user when clicks on an item is redirected to a new page which has that items all details. The problem is when a user clicks on an item,how to send the data from one page to the next.
No php is used. javascript ajax jquery used and data coming from json
this is format and when user clicks on play button a new age should be displayed where the data is to be shown to user.
Template={"Big_Display_Template": '{{#items}}<input type="hidden" name="guid" value="{{id}}"><div class="hero"
style="background-image:url({{videoStillURL}})"><div class="hero-content"><br>
<h2>{{name}}</h2> <p>{{shortDescription}}</p> <div class="hero-links"><a href="Watch_Live.html"
onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});">
Play<span class="genericon genericon-play"> </span></a></div>
<div class="hero-links-fav"><a href="#">Favourite<span class="genericon genericon-fav">
</span></a></div></div></div>{{/items}}'
}
This is my function PassDataToNextPage()
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
$.ajax({
url: url,
type: 'POST',
data: 'name=' + name + '&guid=' + guid + '&shortDescription=' + Description,
success: function(result) {
dataUrl=data;
}
});
return window.location+"/"+dataUrl;
}
I know this is wrong but how to make it right? thanks a lot in advance
The problem lies in the return window.location+"/"+dataUrl; line: the redirect should be done inside the success function because it will be called when the request is completed:
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
$.ajax({
url: url,
type: 'POST',
data: 'name=' + name + '&guid=' + guid + '&shortDescription=' + Description,
success: function(result) {
dataUrl = data;
window.location = window.location + "/" + dataUrl;
}
});
}
In the template you must add return false in the onclick attribute to avoid the browser following the link interrupting your handler:
<a href="Watch_Live.html" onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});return false">
You can pass key:value data via url GET parameters.
For example: if you want to pass data to this page: Watch_Live.html, you can do something like:
<button>Pass data</button>
To parse the parametesr in the other page, read this SO answer to a similar question.
https://stackoverflow.com/a/901144/4440845
Look like you want to pass data and go to the next page with the data, you don't need ajax to achieve. Simply:
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
window.location.href = url + '?name=' + name + '&guid=' + guid + '&shortDescription=' + Description;
}
Comment:
You can use:
< a onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});">Play< /a>
The click event will be handled by the function PassDataToNextPage in onclick.
Assuming you use PHP in your next page, you can fetch the data
$name = $_GET['name'];
$guid = $_GET['guid'];
$shortDesc = $_GET['shortDescription'];
The page is jumping to the bottom when the submit button is pushed on the contact form. I think this is caused by js. When you want to try it, push the link below, next contact, fill in the form and press "verstuur"
http://expertlemmer.nl/PC-laptop-reparatie-Lemmer/
javascript:
$('form#contactForm button.submit').on('click', function() {
$('#image-loader').fadeIn();
var contactFname = $('#contactForm #contactFname').val();
var contactLname = $('#contactForm #contactLname').val();
var contactStraat = $('#contactForm #contactStraat').val();
var contactPostcode = $('#contactForm #contactPostcode').val();
var contactTel = $('#contactForm #contactTel').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactFname=' + contactFname + '&contactLname=' + contactLname +
'&contactEmail=' + contactEmail + '&contactSubject=' + contactSubject +
'&contactStraat=' + contactStraat + '&contactPostcode=' + contactPostcode +
'&contactTel=' + contactTel + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
Hello i was on your webpage. And you are using in your script :
$('form#contactForm button.submit').on('click', function() {
e.preventDefault();
// and so on
The problem is that, you do not pass the e in the function. You have to use it like this :
$('form#contactForm button.submit').on('click', function(e) {
e.preventDefault();
// and so on
Then it will prevent the form from refreshing the page. I am just guessing that you want to send the form through ajax.
Your form has no "ACTION" attribute, this means it's posting to the current URL. The current URL has an anchor : #contact, this means you'll jump straight to the contact part.
See what you get when you go into this link and scroll down(Scroll, don't click contact), you'll jump to the review section.
http://expertlemmer.nl/PC-laptop-reparatie-Lemmer/#journal
Long story short, Put an action tag on your form :)
Here's a simple question:
On the page there are two javascript.
The first script gets JSON and used it to build multiple forms with buttons:
$.getJSON("http://api.server.com/my/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<div class='accordion-group span4'><div class='accordion-heading'>Video Frame<blockquote><a href='http://server.com/video/?my=" + result.File + "' target='_blank'><img src='http://jpg.server.com/" + result.File + ".jpg' class='img-polaroid'/></a><p>" + result.ListId + "</p><small>" + result.OwnerId + "</small><small>" + result.updatedAt + "</small> </blockquote><a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion2' href='#" + result.File + "'>Share video</a></div><div id='" + result.File + "' class='accordion-body collapse'><div class='accordion-inner'><form class='share_file_form'>Set list<input name='nd' id='user_id' type='hidden'><input name='file' value = '" + result.File + "' type='hidden'><div class='list'></div><input type='text' placeholder='New list'><div class='modal-footer'><button class='share_file_submit'>Share video</button></div></form><div id='user_info_result'></div></div></div></div>");
});
$('#mytile').html(results.join(""));
}
);
The second script is a response by pressing a button on the form of constructing the first script:
$(document).on('click', '.share_file_form', function(event) {
$(this).validate({
submitHandler: function(form) {
$.ajax({
type: "GET",
url: "http://api.server.com/set/",
timeout: 20000,
data: $(form).serialize(),
beforeSend: function() {
$(".share_file_submit").attr("disabled", true);
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
},
success: function(msg){
console.log("Data Saved: " + msg);
$("#share_file_submit").attr('disabled', false);
$("#share_file_submit").html("Share video");
$("#user_info_result_2").html(msg);
},
error: function(msg){
//////////////// $('#user_info_result_2').html("<div class='alert alert-error span3'>Failed from timeout. Please try again later. <span id='timer'></span> sec.</div>");
}
});
}
});
});
Everything works, but at the time of the second script, the inscription appears on the buttons of all forms, and I need only one button, which I click.
The problem is this line:
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
It sets the html for all elements with the "share_file_submit" class on the entire page. You can fix it by adding a context to the selector:
$(".share_file_submit", $(form)).html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
If you really want to use validate plugin properly you shouldn't initialize it within a click handler.
Should be initializing right after the form building code.
Within $.getJSON
$('#mytile').html(results.join(""));
$('.share_file_form').validate(/* options*/);
The submitHandler will over ride the default submit event of the form and validation will be active while user fills out form.
To fix button issue:
submitHandler: function(form) {// form is current form elemnt
$.ajax({
beforeSend:function(){
/* look within form for button*/
$(form).find(".share_file_submit").prop('disabled',true);
})
});
Now if user uses Enter key you aren't relying on a click event to prevent submittal by browser default
I have two ajax calls on a page. There are text inputs for searching or for returning a result.
The page has several non ajax inputs and the ajax text input is within this . Whenever I hit enter -- to return the ajax call the form submits and refreshes the page prematurely. How do I prevent the ajax from submitting the form when enter is pressed on these inputs? It should just get the results.
However, I cannot do the jquery key press because it needs to run the ajax even if the user tabs to another field. Basically I need this to not submit the full form on the page before the user can even get the ajax results. I read return false would fix this but it has not.
Here is the javascript:
<script type="text/javascript">
$(function() {
$("[id^='product-search']").change(function() {
var myClass = $(this).attr("class");
// getting the value that user typed
var searchString = $("#product-search" + myClass).val();
// forming the queryString
var data = 'productSearch='+ searchString + '&formID=' + myClass;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/product_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results" + myClass).html('');
$("#searchresults" + myClass).show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results" + myClass).show();
$("#results" + myClass).append(html);
}
});
}
return false;
});
$("[id^='inventory-ESN-']").change(function() {
var arr = [<?php
$j = 1;
foreach($checkESNArray as $value){
echo "'$value'";
if(count($checkESNArray) != $j)
echo ", ";
$j++;
}
?>];
var carrier = $(this).attr("class");
var idVersion = $(this).attr("id");
if($.inArray(carrier,arr) > -1) {
// getting the value that user typed
var checkESN = $("#inventory-ESN-" + idVersion).val();
// forming the queryString
var data = 'checkESN='+ checkESN + '&carrier=' + carrier;
// if checkESN is not empty
if(checkESN) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/checkESN.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#esnResults" + idVersion).html('');
},
success: function(html){ // this happens after we get results
$("#esnResults" + idVersion).show();
$("#esnResults" + idVersion).append(html);
}
});
}
}
return false;
});
});
</script>
I would suggest you to bind that ajax call to the submit event of the form and return false at the end, this will prevent triggering default submit function by the browser and only your ajax call will be executed.
UPDATE
I don't know the structure of your HTML, so I will add just a dummy example to make it clear. Let's say we have some form (I guess you have such a form, which submission you tries to prevent)
HTML:
<form id="myForm">
<input id="searchQuery" name="search" />
</form>
JavaScript:
$("#myForm").submit({
// this will preform necessary ajax call and other stuff
productSearch(); // I would suggest also to remove that functionality from
// change event listener and make a separate function to avoid duplicating code
return false;
});
this code will run every time when the form is trying to be submitted (especially when user hits Enter key in the input), will perform necessary ajax call and will return false preventing in that way the for submission.
i have a page where i'm using a with id="emailfrnd", from the following script i successfully implemented the colorbox:
<script type="text/javascript">
$(document).ready(function(){
$("#emailfrnd").colorbox({
inline: true,
href:"#ef",
close:"",
opacity:0.95,
onClosed:function(){
//window.parent.location.reload(true);
}
});
});
</script>
now the new colorbox contains a form with a send button in it of id "emailfrnd_submit" now i had written some validations using the jquery & ajax and if there are no errorMessages i'll get another colorbox and the code is as follows:
if (errorMessage == '') {
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=emailfrnd',
data: "name=" + name + "&email=" + email + "&message=" + message,
async: true,
success: function (data) {
if (data == 1) {
$("#emailfrnd_submit").colorbox({
inline: false,
close: "",
html: "<div style='height:230px;width:400px;display:block;'><p style='color:black;font:16px verdana;'>Your email was successfully sent.</p><br/><p style='color:gray; font:16px verdana;'>Thank you for telling your friend</p><div id='emailfrnd_sub' style='width: 50px;margin-top:30px;float: right;'><input type='submit' value='OK' name='emailfrnd_submit' id='emailfrnd_sub' class='redbut' style='float:right;position:absolute;right: 198px;margin-top: 0px;color:white;'></div></div>",
opacity: 0.95,
onClosed: function () {
//window.parent.location.reload(true);
}
});
//window.location.assign("../index.php");
} else {
alert('mail not send');
}
}
});
} else {
alert(errorMessage);
}
});
upto now i succeed in getting the things as i want, here after doing the validations and onclick the send button according to this code a new colorbox with the html content as above is coming, here i have a Ok button here, i want to make that button as the closing button of this colorbox. how can i get that functionality for the ok button here??
anyone help is much appreciated....thanks in advance.....
You don't need 2 colorboxes to do it.
Why don't you simple create a div which class is message_content and you update it's text according to the ajax status ?
It's much better.
Example:
html:
<div id="colorbox_content"> //#todo: change to colorbox id
<form id="your_form"> //#todo: change according to your form id
</form>
<div class="message_content">
<p class="message"></p>
<span class="close">Close</span>
</div>
</div>
js:
/**
* Close message
*/
jQuery('#colorbox_content').on('click', '.close', function() {
jQuery(this).closest('#message_content').slideUp();
});
/**
* On form submit
*/
if (errorMessage == '') {
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=emailfrnd',
data: "name=" + name + "&email=" + email + "&message=" + message,
async: true,
success: function (data) {
if (data == 1) {
var message = "Your email was successfully sent.";
//window.location.assign("../index.php");
} else {
var message = "Your email was successfully sent.";
}
jQuery('#colorbox_content').slideDown().find('.message').text(message);
}
});
} else {
alert(errorMessage);
}
Update based on this comment:
If you want the same funcionality for different buttons you have to use the same class for them.
here's what do you need.
demo
I changed some ids to classes so you don't need 2 events with the same code.
And here's the las version.
You can see that you can store your options for each kind of colorbox and then pass them thrue parameter.
i got the answer and the fiddile shows how to do it.....::::)))))
http://jsfiddle.net/srinivaswaterdrop01/4vuDC/189/