I have a form which I want to submit without refreshing the whole page.
I've found a ready source code and implemented it on my pages, but it refuses to work!
here is the html form I need to submit:
<form method="POST" action="" name="actionForm" id="actionForm" class="actionForm">
<input type="hidden" name="adID" value="'.$row['adID'].'" />
<input type="hidden" name="adStatus" value="'.$row['adStatus'].'" />
<input type="submit" name="editAd" value="ערוך מודעה" class="actionButtons" />
<input type="submit" name="upgradeAd" value="הקפץ מודעה" class="actionButtons" />
<input type="submit" name="changeAdStatus" class="actionButtons" value="';
if ($row['adStatus'] == "disabled")
echo 'הצג מודעה בלוח" />';
else
echo 'הסתר מודעה מהלוח" />';
echo '
<input type="submit" name="deleteAd" value="מחק מודעה" class="deleteButton" />
</form>
and here is the script to forward to the processing php file and writing some results on the current page:
<script>
$(document).ready(function(){
$("#actionForm").validate({
debug: false,
rules: {
submitHandler: function(form) {
$.post('/tests/process.php', $("#actionForm").serialize(), function(data) {
$('#resDiv').html(data);
});
}
}});
});
</script>
the processing php only writes data to the database and prints a confirm message.
here is the link to it: http://codeviewer.org/view/code:29c4
I've inspected every single line of the code but still can't get why I see no message from the processing php...
any ideas?
thanks in advance for your help!
P.S. here is the full code of the initial php: http://codeviewer.org/view/code:29c3
I think your javascript snippet at the end of your code is wrong. The submit handler must not be in the rules: {} block.
Try the following:
<script>
$(document).ready(function() {
$("#actionForm").validate({
debug: false,
submitHandler: function(form) {
$.post('/tests/process.php', $("#actionForm").serialize(), function(data) {
$('#resDiv').html(data);
});
}
});
});
</script>
Related
I have php code that echos a form that was inserted into my html by another jquery code. This all works fine. I am trying to submit this form with ajax.
echo '<form id="comment_form" action="commentvalidation.php?PhotoID='.$_GET['PhotoID'].'" method="POST">';
echo '<label>Comment: </label>';
echo '<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>';
echo '<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >';
echo '</form>';
The form works fine when submitted traditionally. The problem is I cant get it to be be submitted with ajax. The .submit just wont prevent the default action.
<script>
$(function(){
$('#comment_form').submit(function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
</script>
You're probably binding the submit event handler before the form is in your page. Use event delegation instead of direct binding, for example
$(document.body).on('submit', '#comment_form', function(e) {
e.preventDefault();
alert('We are in');
// and the rest, no need for return false
});
As an addendum, try not to echo out great chunks of HTML from PHP. It's much more readable and you're less likely to run into problems with quotes and concatenation if you just switch to the PHP context when required, eg
// break out of the PHP context
?>
<form id="comment_form" action="commentvalidation.php?PhotoID=<?= htmlspecialchars($_GET['PhotoID']) ?>" method="POST">
<label>Comment: </label>
<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>
<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >
</form>
<?php
// and back to PHP
The problem seems to be from the fact that form that was inserted into my html by another jquery code. From what I understood from this, the form was dynamically created after the page was loaded.
In that case when the submit handler registration code was executed the element was not existing in the dom structure - means the handler was never registered to the form.
Try using a delegated event handler to solve this
$(function(){
$(document).on('submit', '#comment_form', function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
Demo: Problem
Demo: Solution
I have a form, which take name from form and it sends to javascript codes and show in php by Ajax. these actions are done with clicking by submit button, I need to have another button, as review in my main page. how can I address to ajax that in process.php page have "if isset(submit)" or "if isset(review)"?
I need to do different sql action when each of buttons are clicked.
how can I add another button and be able to do different action on php part in process.php page?
<script type="text/javascript">
$(document).ready(function(){
$("#myform").validate({
debug: false,
submitHandler: function(form) {
$.post('process.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
<body>
<form name="myform" id="myform" action="" method="POST">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
</body>
process.php:
<?php
print "<br>Your name is <b>".$_POST['name']."</b> ";
?>
You just need to add a button and an onclick handler for it.
Html:
<input type="button" id="review" value="Review"/>
Js:
$("#review").click(function(){
var myData = $("#myform").serialize() + "&review=review";
$.post('process.php', myData , function(data) {
$('#results').html(data);
});
}
);
Since you have set a variable review here, you can use it to know that is call has come by clicking the review button.
Bind the event handlers to the buttons' click events instead of the form's submit event.
Use the different event handler functions to add different pieces of extra data to the data object you pass to the ajax method.
I have a website started where I want to have 2 separate submit buttons, one of which will take data entered and do some calculations to it to display on the same screen. I've got this successfully working with:
<form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
<input type="submit" name="calc" value="Find Angle">
and then I use:
if (!isset($_POST['submit'])){
Do actions, display calculations}
Now I want a second submit button that still grabs the data they entered but then goes to a different address. Is there an elegant way to do this?
You could add an onclick method to the new submit button that will change the action of the form and then submit it.
<script type="text/javascript">
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
}
</script>
...
<form id="form1">
<!-- ... -->
<input type="button" onclick="submitForm('page1.php')" value="submit 1" />
<input type="button" onclick="submitForm('page2.php')" value="submit 2" />
</form>
You can change the form action by using formaction="page1.php" in button property .
<form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
<input type="submit" name="calc" value="Find Angle">
<input type="button" type="submit" formaction="page1.php">Action 0</button>
<input type="button" type="submit" formaction="page2.php">Action 1</button>
</form>
Note: The formaction attribute of the button tag is not supported in Internet Explorer 9 and earlier versions.
The best way to deal with multiple submit button is using switch case in action script
<form action="demo_form.php" method="get">
Choose your favorite subject:
<button name="subject" type="submit" value="html">HTML</button>
<button name="subject" type="submit" value="css">CSS</button>
<button name="subject" type="submit" value="javascript">Java Script</button>
<button name="subject" type="submit" value="jquery">jQuery</button>
</form>
Action / Server Side script:
demo_form.php
<?php
switch($_REQUEST['subject']) {
case 'html': //action for html here
break;
case 'css': //action for css here
break;
case 'javascript': //action for javascript here
break;
case 'jquery': //action for jquery here
break;
}
?>
Ref: W3Schools
Another approach is that You can create and Use some session variable to achieve it easily.
E.g. $_SESSION['validate'].
HTML and PHP Code for buttons
<button type="submit" id="first_submit" style="<?php echo isset($_SESSION['validate'])?'display:none':'';?>">first submit</button>
<button type="submit" id="second_submit" style="<?php echo isset($_SESSION['validate'])?'':'display:none';?>">second submit</button>
jquery and ajax Script
<script>
$(document).ready(function(){
$("#form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'handler-file.php',
data: new FormData(this),
dataType: "json",
enctype: 'multipart/form-data',
contentType: false,
cache: false,
processData:false,
error:function(error){
//your required code or alert
alert(error.responseText);
},
success: function(response){
if(response.status=='1')
{
//your required code or alert
$('#first_submit').hide();
$('#second_submit').show();
}
else if(response.status=='2')
{
//your required code or alert
$('#first_submit').show();
$('#second_submit').hide();
}
else
{
//your required code or alert
}
}
});
});
});
</script>
Handler PHP File
<?php
session_start();
$result['status']='0';
$result['error']='';
if(!isset($_SESSION['validate']))
{
if(!isset($_FILES['file']))
{
$result['error'].='[Er-02 file missing!]';
}
else
{
//your other code
$_SESSION['validate'] = true;
$result['status']='1';
}
}
else if($_SESSION['validate']==true)
{
if(!isset($_FILES['file']))
{
$result['error'].='[Er-03 Validation file missing!]';
}
else
{
//your other code
unset($_SESSION['validate']);
$result['status']='2';
}
}
else
{
$result['error'].='[Er-01 Invalid source!]';
}
echo json_encode($result);
?>
It may not be the optimal or efficient solution. My level of experience is not too much, so I came up with this solution what served my purpose best after all the solutions available but with their limitations. This was not anywhere so thought to write it here.
Note: You may notice it includes some other parts like response, success and error handling between presentation, script and backend file.
Hope it helps!
this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
Could someone provide me with the most simple code for form submission with jquery. On the web is with all sorts of gizmo coding.
$('#your_form_id').submit(function(){
var dataString = $("#your_form_id").serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function() {
alert('Sent!');
}
});
return false;
});
here is a another solution, not as simple as the Jquery Form Plugin, but it can be useful if you want to handle errors codes and messages by yourself
look at this HTML + Javascript sample :
<div>
<form method="post" id="fm-form" action ="">
<label>Name:</label>
<input type="text" id="fm-name" name="fm-name" value="" />
<label>Email:</label>
<input type="text" id="fm-email" name="fm-email" value="" />
<label>Birthdate:</label>
<input type="text" id="fm-birthdate" name="fm-birthdate" value="" />
<input type="submit" id="fm-submit" value="Save it">
</form>
</div>
<script type="text/javascript">
$(function() {
// disable the form submission
$("#fm-form").submit(function () { return false; });
// post the datas to "submit_form.php"
$("#fm-submit").click(function() {
$.post("/ajax/submit_form.php",
{ 'fm-name':$("#fm-name").val(),
'fm-email':$("#fm-email").val(),
'fm-birthdate':$("#fm-birthdate").val()
}
,function(xml) {
// submit_form.php will return an XML or JSON document
// check it for potential errors
});
});
});
</script>
What you want is jquery form plugin. It allows you to simply send normal 'form' using ajax - you can make a non-visible form and use this plugin to subnmit it. The option in Joel's answer is possible as well, it depends on the complexity of the thing you want to submit.
Take a look at the Form plugin:
$(function() {
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});