Enter to submit rather than refresh [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Enter button on Keyboard refreshes rather than submitting
I have the following form structure
structure of my form:
<form name="form">
<label>Name:</label>
<input type="text" name="name" id="id" size="50"/></br>
<label></label>
<input type="button" value="Get Info" onClick="get();">
</form>
<div id="age"></div>
My javascript for the get function is as follows:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
}
Now when i use button(input type="button") to post information it works well,But when i fill the information and press enter on the keyboard page gets refreshed.
How can i make Enter button to post the info?

Many times the default behavior in a form when enter is pressed in a non-textarea field is to submit, even when a submit button was not pressed or even present.
Try this:
<form name="form" onsubmit="get();return false;">
In fact, using this technique, you would be able to change your input button to a submit to simplify the form with the same outcome:
<input type="submit" value="Get Info"/>

try return false; in your function. This will stop the button from having its usual behaviour:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
return false;
}

I do it a little differently (which probably means its the wrong way). I dont make a form at all. I just create inputs, selects, etc.. and then when i do my POST i just get the values wen the function is called..
$.ajax({
type: "POST",
url: "someFile.php",
data: { 'name': $("#ElementID").val()},
success: function(data) {
//some function....
{
});
Hope that may be helpful....

I see you posted this as jQuery so I figured I'd give you a solution using that.
$('form[name=form]').submit(function(e) {
var $form = $(this);
$.post( $form.attr('action'), $form.serializeArray(), function( result ) {
$('#age').html( result ).show();
});
e.preventDefault();
});
This will keep you from having to create a crazy json object for the data parameter and from repeating yourself with the form's action attribute. This will also keep the browser's behavior where pressing enter when on an input will submit the form.
Here goes some code I have from an example earlier. The only thing in the form's action file is <?php print_r($_POST); ?>.

Related

AJAX PHP - Reload div after submit

I'm trying to reload a select with jquery and ajax, this select must be reload after I submit a new entry, right now I reach this point.
$("form").on("submit", function (e) {
e.preventDefault();
var form_id = $(this).attr('id');
var form_details = $('#' + form_id);
$.ajax({
type: "POST",
url: 'Users.php',
data: form_details.serialize(),
success: function (data) {
$('#check_data').html(data);
$('#div_to_update').load('my_page.php #div_to_update');
}
}
});
The div to be reloaded has a html select generate by a php code, the other fields are just plain html:
This is the first form, that must be reloaded with the values I enter in the form2:
<div id="div_to_update">
<form id="form1">
<?php Helper::combo_users(); ?>
/*
...
*/
</form>
</div>
This is the form 2:
<form id="form2" method="post">
<input type="text" id="user_reg" name="user_reg"/>
<input type="text" id="user_name" name="user_name"/>
<input type="submit" value="Add"/>
</form>
The odd thing is, this code will run the first time ok(I enter the values in the form2 and send, the form1 will reload with the new value), but the second time it does not work(when I click submit on the form2 nothing seems to happen) and the third time it will work again (click the submit button again and the value is send and the form 1 is reloaded) and so on.
Simply you are not working for second time since you are serializing a form which is dynamically updated within ajax.
jQuery won't serialize when you load a form elements such as inputs dynamically.
You're solution can be loading your new values with JSON object, and put in a foreach to display new content.

how to have a pop up contact form on submit display a confirmation message in the popup?

I'm having great issues making this contact form that can be seen on the below visual. What I want the contact form to do is display on submit a thank you message or a message of confirmation instead of redirecting to the contact.php file where there isn't any styles you can see this in action on the provided link.
I've found some information that I can do this with Jquery Ajax that I've also tried displayed below, but I still can't seem to get it to work on submit to show a message in the pop up.
Does anyone know an easier way to do this or maybe point me in the right direction as this is something that I've been trying to fix for god knows how long.
Thank you for any help
Visual:
http://madaxedesign.co.uk/dev/index.html
PHP & HTML:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form id="submit_message" class="hide_900" method="post" action="/contact.php" onsubmit="javascript: doSubmit();">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div class="submit">
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
Jquery:
function doSubmit(){
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
You can add return false; at the end of your doSubmit function or the following code to prevent the form to redirect the user to the action page.
var doSubmit = function (event) {
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
event.preventDefault();
}
$(function () {
$('#submit_message').submit(doSubmit);
});
Modified HTLM
<form id="submit_message">
...
</form>
What is this code doing ?
First, we are defining a function to submit the form data.
Notice the event argument in the function. The first variable in this function is all the form values serialized in a ajax-complient request string. The .ajax() function is sending all the datas to your server. Note that as you did not set the type argument in the .ajax() function, the data are going to be send using the GET HTTP method.
Finally, event.preventDefault() prevents the submit event to be triggered in the browser. When the browser detect a submit event, it will try to submit the form based on the action and the method parameters in the <form> html tag. Usually, this submission performs an user redirection to the action page. This event.preventDefault() will disable this redirection. Note that the event argument is going to be set automatically by jQuery.
Last part, the $(function() { ... }); part means "execute this part when the document is fully loaded." It ensures that the element with sumbit_message id exists before calling the .submit() method. This last method is an event binder. It means that when the submit event is fired on the submit_message form, the function doSubmit will be called.
I hope you have a better understanding of this script. This is a pretty basic one, but if you understand clearly the mechanics, it will help you do become a better jQuery programmer. :)
Fiddle Demo
1.<form onsubmit='confirm()'>
function confirm()
{
alert("Thank You");
}
2.in contact.php call the page that is displayed again
You need to prevent the default event of the form. To do this, add the e.preventDefault(); function to the top of your function in order to prevent this event from firing.
Also notice that we are passing the e parameter to your function. This represents the event that has been fired.
function doSubmit(e){
e.preventDefault();
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
}
Try this
change your form with
<form id="submit_message" class="hide_900" method="post">
and in script put it
$("#submit_message").submit(function(e){
e.preventDefault();
//call your ajax
});

Form variables passed via jquery potential issue

I have a form for a mailing list script which I am trying to get working with ajax so the form can refresh without reloading. With the $.ajax part of the jquery commented out, the form variables are sent to the URL string.
?email=test%40address.com&sub=sub&submit=Submit+Form
My question is why is the submit=Submit+Form part there given that it isn't part of my "datastring" and will that be a problem when it comes to processing the actual PHP script?
Here is the form :
<form name="email_list" action="">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" name="submit" value="Submit Form" class="email_submit"></p>
</form>
and the JQuery
$(function() {
$('.email_submit').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = '&email=' + email + '&sub=' + sub;
//alert (dataString);return false;
/*$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});*/
});
You should put the submit handler on the form, not on the button, even if is a submit button.
<form name="email_list" action="" id="my_form">
Update the javascript
$(function() {
$('#my_form').submit(function() {
...
});
});
To serialize all the inputs into a string you could use $("#my_form").serialize() which builds a string with all the inputs and their data ready for posting:
var dataString = $("#my_form").serialize();
Also note that having a name attribute defined for the submit input means that its value will be sent also in the form. If you don't need that, you can simply remove the name attribute.
Submit+Form is the urlencoded version of Submit Form. The field submit is sent because you specify a name attribute to <input type="submit" name="submit" ... />. It will most likely not cause any problems for you (can't say without looking at your server-side code though).
Also, you really should specify a method attribute to your <form>. It seems to default to GET, which is why the form fields are added to the query string.
If you let your ajax POST happen, since you'r manually creating your dataString you won't see the Submit=, however when you let it submit 'normally' you see it, since the submit button is an input field with a value.
You won't encounter any issues with this. You can access the submit value just the same as any other POST value $_POST['submit'] though I'm not sure why you'd want to.

Simple PHP/AJAX question

Ok, so I am fairly new to webdeveloping, so probably a silly question:
I have this search form which does autocomplete for fooditems (gets values from a database column) and that works. Now when I press the submit button I want to load a block of code that displays the food-items' calories etc (also in the database on the same row as the food-item).
How can I accomplish such a thing. I kno this is a fairly broad question, but what i am really asking is, how can I make a small part of my website reload when pressing the submit button and using the input given in the text field as a parameter of some kind.
I don't need whole answers, just any tips getting to the right path would be greatly appreciated!
here my code for the input and button:
in head
<script type="text/javascript" src="jquery.js"></script>
<script>
function ok(){
$.post("test.php", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
}
</script>
in body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" onclick="ok()" />
</form>
or:
head:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script>
$("input[type='submit']").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
</script>
body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" />
</form>
jQuery and Ajax.
Change that input to a button
<button id="submit">Save</button>
For this I would do something like:
$("button#submit]").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
You need to first catch the click event .bind("click"). Then initiate an ajax call $.post which you will send data to. This data is received on the server via the POST array.
Like Josh said, jQuery is the way to go here.
You'll want to do 3 things:
Attach a click handler to a button like "onclick='doSomething();'"
In that function,use jQuery to do an async post to a script like
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
When this comes back, you can do something with that data(instead of the alert above), like $('#listnode').append... which would stick the HTML into your list
This is the general pattern, but you'll have to fit it to your scenario.
It is hard to answer your question from what little you have given us, but I will assume little knowledge.
Your input fields have to be inside a form tag. The form tag includes an action and a method. The method must be "POST" to send the data. The action can be any URL.
You simply have to name the URL of your php script that will handle the results.
It will find the data in $_POST['food'] etc. It has to build the reply page - the whole screen, with the food and data and the search form for the next submit if you want.
If you want to use AJAX to replace part of the screen, then you have a whole nother level of problems. The trick is to replace the content of a div tag with the requested data.

Disable the enter key on a jquery-powered form

I have a form using the form jQuery plug in to handel the posting of the data. In the example i am working with the data is psoted to another php file which reades a database and echos back a result which is displayed below the from.
The code works very well with one glitch. If you hit the enter button while the text filed is selected everything cleared including the result that has been written to the screen. Is it possible to disable to enter key and prevent it from doing this?
FORM:
<html>
<head>
</head>
<p>enter code here
<form name="form" action="" method="">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name"/>
<input type="button" value="get" onclick="get();"/>
</form>
<div id="age"></div>
</p>
</body>
</html>
SCRIPT:
function get() {
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
}
Cheers.
You should consider using the jQuery Forms Plugin. It will save you from doing some of the dirty work, additionally it will intercept all ways of submitting the form - so instead of having to disable the RETURN key it will submit your form via AJAX.
If you don't want that, get rid of the button with the onclick event and replace it with a submit button and register your function as a onsubmit handöer:
$('form[name=form]').submit(function(e) {
e.preventDefault();
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
});
$(document).ready(function(){
$('form').submit(function(){
return false;
});
});
This will prevent the form from submitting, however the form will not work at all for users with javascript disabled.
A found some tuts and solved the issue.
I just put this in before my Jquery code to disable the enter button.
$(function () {
$('input').keypress(function (e) {
var code = null;
code = (e.keyCode ? e.keyCode : e.which);
return (code == 13) ? false : true;
});
});

Categories