submit form using Jquery Ajax Form Plugin and php? - php

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>

Related

Ajax call not saving form information

I have tried using the code below to save and display information using ajax. But it doesn't work.
Here's the code.
<?php session_start();?>
<html>
<head>
<script src="style/jquery-ui.js" type="text/javascript" charset="utf-8"></script>
<script src="style/jquery-1.11.1.min.js"></script>
<script>
$(function() {
$("#ajaxquery").live( "submit" , function(){
// Intercept the form submission
var formdata = $(this).serialize(); // Serialize all form data
// Post data to your PHP processing script
$.post( "show.php", formdata, function( data ) {
// Act upon the data returned, setting it to #success <div>
$("#success").html ( data );
});
return false; // Prevent the form from actually submitting
})
});
</script>
</head>
<form id="ajaxquery" method="post" action="">
<label for="field">Type Something:</label>
<input type="text" name="field" id="field" value="" />
<input type="submit" value="Send to AJAX" />
</form>
<div id="success"> </div>
</html>
AND MY show.php which displays data in id="success"
<?php
// Process form data
echo '<strong>You submitted to me:</strong><br/>';
print_r( $_REQUEST );
?>
Please help...
at first you have to load jquery ui after jquery
<script src="style/jquery-1.11.1.min.js"></script>
<script src="style/jquery-ui.js" type="text/javascript" charset="utf-8"></script>
then in this case you don't need to use live you can simply do this
$("#ajaxquery").submit(function(){
// your code
})
"live" function ( or for now "on" ) used when you going to create or load html code after you set events.

$_POST for text in DIV elements

Because of my web style, i don't want to use input & textarea and get information by using $_POST[] and i need to get information that is in DIV element.
For example , I want to get information in this :
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
and :
$_POST[myname];
But i can't do it with $_POST , How can i do it ??
And if this method can't do this , do you know any other method to get information from DIV like this ?
you can call a onsubmit function and make a hidden field at the time of form submission like this
HTML
need to give a id to your form id="my_form"
<form action="submit.php" method="post" id="my_form">
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="submit" value="submit" name="submit" />
</form>
Jquery call on submit the form
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.mine').text();
$(this).append("<input type='hidden' name='myname' value=' " + hvalue + " '/>");
});
});
PHP : submit.php
echo $_POST['myname'];
You can use this method. First, with javascript get content of <div>
Code:
<script type="text/javascript">
var MyDiv1 = Document.getElementById('DIV1');
</script>
<body>
<div id="DIV1">
//Some content goes here.
</div>
</body>
And with ajax send this var to page with get or post method.
You would need some JavaScript to make that work, e.g. using jQuery:
$.post('http://example.org/script.php', {
myname: $('.mine').text()
});
It submits text found inside your <div> to a script of your choosing.
You can use following structure;
JS:
$(document).ready(function() {
$("#send").on("click", function() {
$.ajax({
url: "your_url",
method: "POST",
data: "myname=" + $(".mine").text(),
success: function(response) {
//handle response
}
})
})
})
HTML:
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="button" name="send" id="send" value="Send"/>
You can see a simulation here: http://jsfiddle.net/cubuzoa/2scaJ/
Do this in jquery
$('.mine').text();
and post data using ajax.
Put the content of DIV in a variable like below:
var x = document.getElementById('idname').innerHTML;

post data not set using jQuery post method on button selected by class

This site has been really helpful while writing this program. Unfortunately, I hit a snag at some point, and have boiled the problem down quite a bit since. At this point, I am looking at three files, a .html that contains a form, a .js that contains my event handlers, and a .php that receives my post variables and contains new content for the form.
I am getting the post data from the initial text input just fine. The new form content is set as I would expect. However, after this form content is set to a new input of type button with a class of button, the post method in my button class handler is not setting post data on login.php as I expect it to.
Here is my code:
Contents of interface.html page:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="interface" action="login.php" method="post">
<input type="text" value="enter username here" name="user"/>
<button id="submit">submit</button>
</form>
<script src='events.js'></script>
</body>
</html>
Contents of events.js file:
$("#submit").click(function(){
$.post(
$("#interface").attr("action"),
$(":input").serialize(),
function(info){$("#interface").html(info);}
);
});
$(".button").click(function(){
var $this=$(this);
$.post(
$("#interface").attr("action"),
{data:$this.val()},
function(info){$("#interface").html(info);}
);
});
$("#interface").submit(function(){
return false;
});
Contents of login.php file:
<?php
if(isset($_POST['user'])){
echo '<input type="button" class="button" value="set data"/>';
}else if(isset($_POST['data'])){
echo 'data is set';
}
?>
You need to wait until the button exists to bind an event to it. Additionally, i'd switch from click to submit and drop the click event binding on .button completely.
//$("#submit").click(function () {
$("#interface").submit(function (e) {
e.preventDefault();
var $form = $(this), data = $form.serialize();
if ($form.find(".button").length && $form.find(".button").val() ) {
data = {data: $form.find(".button").val()};
}
$.post($form.attr("action"), data, function (info) {
$form.html(info);
});
});
//$("#interface").submit(function () {
// return false;
//});
Since the form is not being replaced, and the event is on the form, you no longer need to re-bind anything.

sending form data to php using ajax

I Have an requirement to pass form data to php using ajax and implement it in php to calculate the sum , division and other arithmetic methods I am a new to ajax calls trying to learn but getting many doubts....
It would be great help if some one helps me out with this
index.html
<script type="text/javascript">
$(document).ready(function(){
$("#submit_btn").click(function() {
$.ajax({
url: 'count.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data');
}
})
});
</script>
</head>
<form name="contact" id="form" method="post" action="">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
In count.php i want to implement
<?php
$FNO = ($_POST['FNO']);
$SNO=($_post['SNO']);
$output=$FNO+$SNO;
echo $output;
?>
(i want to display output in count.php page not in the first page index.html)
Thanks for your help in advance.
You can use a simple .post with AJAX. Take a look at the following code to be able to acheive this:
$('#form').submit(function() {
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("count.php",$(this).serialize(),function(data){
alert(data); //check to show that the calculation was successful
});
return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});
This sends all of your form variables to count.php in a serialized array. This code works if you want to display your results on the index.html.
I saw at the very bottom of your question that you want to show the count on count.php. Well you probably know that you can simply put count.php into your form action page and this wouldn't require AJAX. If you really want to use jQuery to submit your form you can do the following but you'll need to specify a value in the action field of your form:
$("#submit_btn").click(function() {
$("#form").submit();
});
I have modified your PHP code as you made some mistakes there. For the javscript code, i have written completely new code for you.
Index.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<form name="contact" id="contactForm" method="post" action="count.php">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
<label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
<!-- The following div will use to display data from server -->
<div id="result"></div>
</body>
<script>
/* attach a submit handler to the form */
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
//Get the first value
value1 = $form.find( 'input[name="SNO"]' ).val(),
//get second value
value2 = $form.find( 'input[name="FNO"]' ).val(),
//get the url. action="count.php"
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { SNO: value1, FNO: value2 } );
/* Put the results in a div */
posting.done(function( data ) {
$( "#result" ).empty().append( data );
});
});
</script>
</html>
count.php
<?php
$FNO = $_POST['FNO'];
$SNO= $_POST['SNO'];
$output = $FNO + $SNO;
echo $output;
?>
There are a few things wrong with your code; from details to actual errors.
If we take a look at the Javascript then it just does not work. You use the variable data without ever setting it. You need to open the browser's Javascript console to see errors. Google it.
Also, the javascript is more complicated than is necessary. Ajax requests are kind-of special, whereas in this example you just need to set two POST variables. The jQuery.post() method will do that for you with less code:
<script type="text/javascript">
$(document).ready(function(){
$("#form").on("submit", function () {
$.post("/count.php", $(this).serialize(), function (data) {
alert(data);
}, "text");
return false;
});
});
</script>
As for the HTML, it is okay, but I would suggest that naming (i.e. name="") the input fields using actual and simple words, as opposed to abbreviations, will serve you better in the long run.
<form method="post" action="/count.php" id="form">
<label for="number1">Enter First no:</label>
<input type="number" name="number1" id="number1">
<label for="number2">Enter Second no:</label>
<input type="number" name="number2" id="number2">
<input type="submit" value="Calculate">
</form>
The PHP, as with the Javascript, just does not work. PHP, like most programming languages, are very picky about variables names. In other words, $_POST and $_post are not the same variable! In PHP you need to use $_POST to access POST variables.
Also, you should never trust data that you have no control over, which basically means anything that comes from the outside. Your PHP code, while it probably would not do much harm (aside from showing where the file is located on the file system, if errors are enabled), should sanitize and validate the POST variables. This can be done using the filter_input function.
<?php
$number1 = filter_input(INPUT_POST, 'number1', FILTER_SANITIZE_NUMBER_INT);
$number2 = filter_input(INPUT_POST, 'number2', FILTER_SANITIZE_NUMBER_INT);
if ( ! ctype_digit($number1) || ! ctype_digit($number2)) {
echo 'Error';
} else {
echo ($number1 + $number2);
}
Overall, I would say that you need to be more careful about how you write your code. Small errors, such as in your code, can cause everything to collapse. Figure out how to detect errors (in jQuery you need to use a console, in PHP you need to turn on error messages, and in HTML you need to use a validator).
You can do like below to pass form data in ajax call.
var formData = $('#client-form').serialize();
$.ajax({
url: 'www.xyz.com/index.php?' + formData,
type: 'POST',
data:{
},
success: function(data){},
error: function(data){},
})

Why can't a submit button send to PHP and jQuery at the same time?

I have this code.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<?
if (isset($_POST['submit2'])){
echo $_POST['text2'];
}
?>
<script>
$('#form').submit(function(e) {
$('#loading').show();
return false;
});
</script>
</body>
</html>
I want to store in my db the value written in the textbox using PHP, and while it's being saved, I want to show a gif using jQuery, once the page is loaded, this gif should be removed.
Then, If I don't comment nothing, gif appears when submit button is submitted but echo fails.
If I comment the jQuery script, PHP echoes the vale written.
If I comment the PHP script, gif is shown but no echo of course...
How could I do what i'm asking. I know that my full script does until only showing the gif, but this without this I can't continue.
You can achieve your desired behaviour, but you need to do it by submitting an AJAX request to the server and then handling the return value. So basically you'd add this ajax request to the click or submit event of the form, and handle the behaviour and request via javascript.
Perhaps something like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "formSubmitHandler.php" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<script>
$(document).ready(function(){
$('#form').submit(function(){
// Show the loading icon before the processing begins
$('#loading').show();
// Send the query/form details to the server
jQuery.ajax({
data: $(this).serialize(),
url: this.action,
type: this.method,
success: function(results) {
// Now that the processing has finished, you
// can hide the loading icon
$('#loading').hide();
// perhaps display some other message etc
}
})
return false;
});
});
</script>
</body>
</html>

Categories