Related
I have a classifieds website, and on the page where ads are showed, I am creating a "Send a tip to a friend" form...
So anybody who wants can send a tip of the ad to some friends email-adress.
I am guessing the form must be submitted to a php page right?
<form name="tip" method="post" action="tip.php">
Tip somebody:
<input
name="tip_email"
type="text"
size="30"
onfocus="tip_div(1);"
onblur="tip_div(2);"
/>
<input type="submit" value="Skicka Tips" />
<input type="hidden" name="ad_id" />
</form>
When submitting the form, the page gets reloaded... I don't want that...
Is there any way to make it not reload and still send the mail?
Preferrably without ajax or jquery...
I've found what I think is an easier way.
If you put an Iframe in the page, you can redirect the exit of the action there and make it show up.
You can do nothing, of course. In that case, you can set the iframe display to none.
<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
<input type="submit" value="Skicka Tips">
<input type="hidden" name="ad_id" value="2">
</form>
You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/
Your code should be something along the lines of:
$('#submit').click(function() {
$.ajax({
url: 'send_email.php',
type: 'POST',
data: {
email: 'email#example.com',
message: 'hello world!'
},
success: function(msg) {
alert('Email Sent');
}
});
});
The form will submit in the background to the send_email.php page which will need to handle the request and send the email.
You either use AJAX or you
create and append an iframe to the document
set the iframes name to 'foo'
set the forms target to 'foo'
submit
have the forms action render javascript with 'parent.notify(...)' to give feedback
optionally you can remove the iframe
Fastest and easiest way is to use an iframe.
Put a frame at the bottom of your page.
<iframe name="frame"></iframe>
And in your form do this.
<form target="frame">
</form>
and to make the frame invisible in your css.
iframe{
display: none;
}
SUBMITTING THE FORM WITHOUT RELOADING THE PAGE AND GET THE RESULT OF SUBMITTED DATA ON THE SAME PAGE.
Here's some of the code I found on the internet that solves this problem :
1.) IFRAME
When the form is submitted, The action will be executed and target the specific iframe to reload.
index.php
<iframe name="content" style="">
</iframe>
<form action="iframe_content.php" method="post" target="content">
<input type="text" name="Name" value="">
<input type="submit" name="Submit" value="Submit">
</form>
iframe_content.php
<?php
$Submit = isset($_POST['Submit']) ? $_POST['Submit'] : false;
$Name = isset($_POST['Name']) ? $_POST['Name'] : '';
if($Submit){
echo $Name;
}
?>
2.) AJAX
Index.php:
<form >
<input type="" name="name" id="name">
<input type="" name="descr" id="descr">
<input type="submit" name="" value="submit" onclick="return clickButton();">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
var descr=document.getElementById('descr').value;
$.ajax({
type:"post",
url:"server_action.php",
data:
{
'name' :name,
'descr' :descr
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
server_action.php
<?php
$name = isset($_POST['name']) ? $_POST['name'] : '';
$descr = isset($_POST['descr']) ? $_POST['descr'] : '';
echo $name;
echo $descr;
?>
Tags: phpajaxjqueryserversidehtml
A further possibility is to make a direct javascript link to your function:
<form action="javascript:your_function();" method="post">
...
It's a must to take help of jquery-ajax in this case. Without ajax, there is currently no solution.
First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().
event.preventDefault()
Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func() and do whatever you want to do when call ends.
Example:
Form:
<form id="form-id" onsubmit="func()">
<input id="input-id" type="text">
</form>
Javascript:
function func(){
event.preventDefault();
var newValue = $('#input-field-id').val();
$.ajax({
type: 'POST',
url: '...',
data: {...},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
}
this is exactly how it CAN work without jQuery and AJAX and it's working very well using a simple iFrame. I LOVE IT, works in Opera10, FF3 and IE6. Thanks to some of the above posters pointing me the right direction, that's the only reason I am posting here:
<select name="aAddToPage[65654]"
onchange="
if (bCanAddMore) {
addToPage(65654,this);
}
else {
alert('Could not add another, wait until previous is added.');
this.options[0].selected = true;
};
" />
<option value="">Add to page..</option>
[more options with values here]</select>
<script type="text/javascript">
function addToPage(iProduct, oSelect){
iPage = oSelect.options[oSelect.selectedIndex].value;
if (iPage != "") {
bCanAddMore = false;
window.hiddenFrame.document.formFrame.iProduct.value = iProduct;
window.hiddenFrame.document.formFrame.iAddToPage.value = iPage;
window.hiddenFrame.document.formFrame.submit();
}
}
var bCanAddMore = true;</script>
<iframe name="hiddenFrame" style="display:none;" src="frame.php?p=addProductToPage" onload="bCanAddMore = true;"></iframe>
the php code generating the page that is being called above:
if( $_GET['p'] == 'addProductToPage' ){ // hidden form processing
if(!empty($_POST['iAddToPage'])) {
//.. do something with it..
}
print('
<html>
<body>
<form name="formFrame" id="formFrameId" style="display:none;" method="POST" action="frame.php?p=addProductToPage" >
<input type="hidden" name="iProduct" value="" />
<input type="hidden" name="iAddToPage" value="" />
</form>
</body>
</html>
');
}
This should solve your problem.In this code after submit button click we call jquery ajax and we pass url to posttype POST/GET
data: data information you can select input fields or any other.
sucess: callback if everything is ok from server
function parameter text, html or json, response from server
in sucess you can write write warnings if data you got is in some kind of state and so on. or execute your code what to do next.
<form id='tip'>
Tip somebody: <input name="tip_email" id="tip_email" type="text" size="30" onfocus="tip_div(1);" onblur="tip_div(2);"/>
<input type="submit" id="submit" value="Skicka Tips"/>
<input type="hidden" id="ad_id" name="ad_id" />
</form>
<script>
$( "#tip" ).submit(function( e ) {
e.preventDefault();
$.ajax({
url: tip.php,
type:'POST',
data:
{
tip_email: $('#tip_email').val(),
ad_id: $('#ad_id').val()
},
success: function(msg)
{
alert('Email Sent');
}
});
});
</script>
You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.
I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.
Have you tried using an iFrame? No ajax, and the original page will not load.
You can display the submit form as a separate page inside the iframe, and when it gets submitted the outer/container page will not reload. This solution will not make use of any kind of ajax.
function Foo(){
event.preventDefault();
$.ajax( {
url:"<?php echo base_url();?>Controllername/ctlr_function",
type:"POST",
data:'email='+$("#email").val(),
success:function(msg) {
alert('You are subscribed');
}
} );
}
I tried many times for a good solution and answer by #taufique helped me to arrive at this answer.
NB : Don't forget to put event.preventDefault(); at the beginning of the body of the function .
I did something similar to the jquery above, but I needed to reset my form data and graphic attachment canvases.
So here is what I came up with:
<script>
$(document).ready(function(){
$("#text_only_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
});
$("#pic_radio_button_id").click(function(){
$("#single_pic_div").show();
$("#multi_pic_div").hide();
});
$("#gallery_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").show();
});
$("#my_Submit_button_ID").click(function() {
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
var canvas=document.getElementById("canvas");
var canvasA=document.getElementById("canvasA");
var canvasB=document.getElementById("canvasB");
var canvasC=document.getElementById("canvasC");
var canvasD=document.getElementById("canvasD");
var ctx=canvas.getContext("2d");
var ctxA=canvasA.getContext("2d");
var ctxB=canvasB.getContext("2d");
var ctxC=canvasC.getContext("2d");
var ctxD=canvasD.getContext("2d");
ctx.clearRect(0, 0,480,480);
ctxA.clearRect(0, 0,480,480);
ctxB.clearRect(0, 0,480,480);
ctxC.clearRect(0, 0,480,480);
ctxD.clearRect(0, 0,480,480);
} });
return false;
}); });
</script>
That works well for me, for your application of just an html form, we can simplify this jquery code like this:
<script>
$(document).ready(function(){
$("#my_Submit_button_ID").click(function() {
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
} });
return false;
}); });
</script>
I don't know JavaScript and I just started to learn PHP, so what helped for me from all those responses was:
Create inedx.php and insert:
<iframe name="email" style=""></iframe>
<form action="email.php" method="post" target="email">
<input type="email" name="email" >
<input type="submit" name="Submit" value="Submit">
</form>
Create email.php and insert this code to check if you are getting the data (you should see it on index.php in the iframe):
<?php
if (isset($_POST['Submit'])){
$email = $_POST['email'];
echo $email;
}
?>
If everything is ok, change the code on email.php to:
<?php
if (isset($_POST['Submit'])){
$to = $_POST['email'];
$subject = "Test email";
$message = "Test message";
$headers = "From: test#test.com \r\n";
$headers .= "Reply-To: test#test.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);
}
?>
Hope this helps for all other rookies like me :)
Modern Answer without XHR or jQuery
It's 2022, we don't need to use old tools like XHR or jQuery when we have the Fetch API and the FormData API!
The first thing we need to do is prevent the default form submission behavior from occurring with event.preventDefault():
form.addEventListener("submit", function(event){
event.preventDefault();
// ...
});
Now we need to replace the submission behavior with our own AJAX request. The Fetch API makes it pretty simple to post form data - just create a new FormData object, populating it with the form's values, and use it as the body of a fetch request:
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form))
});
Note that this submits an HTTP request using the multipart/form-data format. If you need to post the data using application/x-www-form-urlencoded, create a new URLSearchParams object from the FormData object and use that as the fetch's body.
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form))
});
Here's a full code example:
let form = document.querySelector("form");
form.addEventListener("submit", function(event){
event.preventDefault();
fetch(form.action, {
method: "post",
body: //new FormData(form) // for multipart/form-data
new URLSearchParams(new FormData(form)) //for application/x-www-form-urlencoded
});
});
<form method="POST">
<input name="name" placeholder="Name" />
<input name="phone" type="tel" placeholder="Phone" />
<input name="email" type="email" placeholder="Email" />
<input name="submit" type="submit" />
</form>
The page will get reloaded if you don't want to use javascript
You will need to use JavaScript without resulting to an iframe (ugly approach).
You can do it in JavaScript; using jQuery will make it painless.
I suggest you check out AJAX and Posting.
if you're submitting to the same page where the form is you could write the form tags with out an action and it will submit, like this
<form method='post'> <!-- you can see there is no action here-->
Here is some jQuery for posting to a php page and getting html back:
$('form').submit(function() {
$.post('tip.php', function(html) {
// do what you need in your success callback
}
return false;
});
I have a classifieds website, and on the page where ads are showed, I am creating a "Send a tip to a friend" form...
So anybody who wants can send a tip of the ad to some friends email-adress.
I am guessing the form must be submitted to a php page right?
<form name="tip" method="post" action="tip.php">
Tip somebody:
<input
name="tip_email"
type="text"
size="30"
onfocus="tip_div(1);"
onblur="tip_div(2);"
/>
<input type="submit" value="Skicka Tips" />
<input type="hidden" name="ad_id" />
</form>
When submitting the form, the page gets reloaded... I don't want that...
Is there any way to make it not reload and still send the mail?
Preferrably without ajax or jquery...
I've found what I think is an easier way.
If you put an Iframe in the page, you can redirect the exit of the action there and make it show up.
You can do nothing, of course. In that case, you can set the iframe display to none.
<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
<input type="submit" value="Skicka Tips">
<input type="hidden" name="ad_id" value="2">
</form>
You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/
Your code should be something along the lines of:
$('#submit').click(function() {
$.ajax({
url: 'send_email.php',
type: 'POST',
data: {
email: 'email#example.com',
message: 'hello world!'
},
success: function(msg) {
alert('Email Sent');
}
});
});
The form will submit in the background to the send_email.php page which will need to handle the request and send the email.
You either use AJAX or you
create and append an iframe to the document
set the iframes name to 'foo'
set the forms target to 'foo'
submit
have the forms action render javascript with 'parent.notify(...)' to give feedback
optionally you can remove the iframe
Fastest and easiest way is to use an iframe.
Put a frame at the bottom of your page.
<iframe name="frame"></iframe>
And in your form do this.
<form target="frame">
</form>
and to make the frame invisible in your css.
iframe{
display: none;
}
SUBMITTING THE FORM WITHOUT RELOADING THE PAGE AND GET THE RESULT OF SUBMITTED DATA ON THE SAME PAGE.
Here's some of the code I found on the internet that solves this problem :
1.) IFRAME
When the form is submitted, The action will be executed and target the specific iframe to reload.
index.php
<iframe name="content" style="">
</iframe>
<form action="iframe_content.php" method="post" target="content">
<input type="text" name="Name" value="">
<input type="submit" name="Submit" value="Submit">
</form>
iframe_content.php
<?php
$Submit = isset($_POST['Submit']) ? $_POST['Submit'] : false;
$Name = isset($_POST['Name']) ? $_POST['Name'] : '';
if($Submit){
echo $Name;
}
?>
2.) AJAX
Index.php:
<form >
<input type="" name="name" id="name">
<input type="" name="descr" id="descr">
<input type="submit" name="" value="submit" onclick="return clickButton();">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
var descr=document.getElementById('descr').value;
$.ajax({
type:"post",
url:"server_action.php",
data:
{
'name' :name,
'descr' :descr
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
server_action.php
<?php
$name = isset($_POST['name']) ? $_POST['name'] : '';
$descr = isset($_POST['descr']) ? $_POST['descr'] : '';
echo $name;
echo $descr;
?>
Tags: phpajaxjqueryserversidehtml
A further possibility is to make a direct javascript link to your function:
<form action="javascript:your_function();" method="post">
...
It's a must to take help of jquery-ajax in this case. Without ajax, there is currently no solution.
First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().
event.preventDefault()
Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func() and do whatever you want to do when call ends.
Example:
Form:
<form id="form-id" onsubmit="func()">
<input id="input-id" type="text">
</form>
Javascript:
function func(){
event.preventDefault();
var newValue = $('#input-field-id').val();
$.ajax({
type: 'POST',
url: '...',
data: {...},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
}
this is exactly how it CAN work without jQuery and AJAX and it's working very well using a simple iFrame. I LOVE IT, works in Opera10, FF3 and IE6. Thanks to some of the above posters pointing me the right direction, that's the only reason I am posting here:
<select name="aAddToPage[65654]"
onchange="
if (bCanAddMore) {
addToPage(65654,this);
}
else {
alert('Could not add another, wait until previous is added.');
this.options[0].selected = true;
};
" />
<option value="">Add to page..</option>
[more options with values here]</select>
<script type="text/javascript">
function addToPage(iProduct, oSelect){
iPage = oSelect.options[oSelect.selectedIndex].value;
if (iPage != "") {
bCanAddMore = false;
window.hiddenFrame.document.formFrame.iProduct.value = iProduct;
window.hiddenFrame.document.formFrame.iAddToPage.value = iPage;
window.hiddenFrame.document.formFrame.submit();
}
}
var bCanAddMore = true;</script>
<iframe name="hiddenFrame" style="display:none;" src="frame.php?p=addProductToPage" onload="bCanAddMore = true;"></iframe>
the php code generating the page that is being called above:
if( $_GET['p'] == 'addProductToPage' ){ // hidden form processing
if(!empty($_POST['iAddToPage'])) {
//.. do something with it..
}
print('
<html>
<body>
<form name="formFrame" id="formFrameId" style="display:none;" method="POST" action="frame.php?p=addProductToPage" >
<input type="hidden" name="iProduct" value="" />
<input type="hidden" name="iAddToPage" value="" />
</form>
</body>
</html>
');
}
This should solve your problem.In this code after submit button click we call jquery ajax and we pass url to posttype POST/GET
data: data information you can select input fields or any other.
sucess: callback if everything is ok from server
function parameter text, html or json, response from server
in sucess you can write write warnings if data you got is in some kind of state and so on. or execute your code what to do next.
<form id='tip'>
Tip somebody: <input name="tip_email" id="tip_email" type="text" size="30" onfocus="tip_div(1);" onblur="tip_div(2);"/>
<input type="submit" id="submit" value="Skicka Tips"/>
<input type="hidden" id="ad_id" name="ad_id" />
</form>
<script>
$( "#tip" ).submit(function( e ) {
e.preventDefault();
$.ajax({
url: tip.php,
type:'POST',
data:
{
tip_email: $('#tip_email').val(),
ad_id: $('#ad_id').val()
},
success: function(msg)
{
alert('Email Sent');
}
});
});
</script>
You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.
I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.
Have you tried using an iFrame? No ajax, and the original page will not load.
You can display the submit form as a separate page inside the iframe, and when it gets submitted the outer/container page will not reload. This solution will not make use of any kind of ajax.
function Foo(){
event.preventDefault();
$.ajax( {
url:"<?php echo base_url();?>Controllername/ctlr_function",
type:"POST",
data:'email='+$("#email").val(),
success:function(msg) {
alert('You are subscribed');
}
} );
}
I tried many times for a good solution and answer by #taufique helped me to arrive at this answer.
NB : Don't forget to put event.preventDefault(); at the beginning of the body of the function .
I did something similar to the jquery above, but I needed to reset my form data and graphic attachment canvases.
So here is what I came up with:
<script>
$(document).ready(function(){
$("#text_only_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
});
$("#pic_radio_button_id").click(function(){
$("#single_pic_div").show();
$("#multi_pic_div").hide();
});
$("#gallery_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").show();
});
$("#my_Submit_button_ID").click(function() {
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
var canvas=document.getElementById("canvas");
var canvasA=document.getElementById("canvasA");
var canvasB=document.getElementById("canvasB");
var canvasC=document.getElementById("canvasC");
var canvasD=document.getElementById("canvasD");
var ctx=canvas.getContext("2d");
var ctxA=canvasA.getContext("2d");
var ctxB=canvasB.getContext("2d");
var ctxC=canvasC.getContext("2d");
var ctxD=canvasD.getContext("2d");
ctx.clearRect(0, 0,480,480);
ctxA.clearRect(0, 0,480,480);
ctxB.clearRect(0, 0,480,480);
ctxC.clearRect(0, 0,480,480);
ctxD.clearRect(0, 0,480,480);
} });
return false;
}); });
</script>
That works well for me, for your application of just an html form, we can simplify this jquery code like this:
<script>
$(document).ready(function(){
$("#my_Submit_button_ID").click(function() {
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
} });
return false;
}); });
</script>
I don't know JavaScript and I just started to learn PHP, so what helped for me from all those responses was:
Create inedx.php and insert:
<iframe name="email" style=""></iframe>
<form action="email.php" method="post" target="email">
<input type="email" name="email" >
<input type="submit" name="Submit" value="Submit">
</form>
Create email.php and insert this code to check if you are getting the data (you should see it on index.php in the iframe):
<?php
if (isset($_POST['Submit'])){
$email = $_POST['email'];
echo $email;
}
?>
If everything is ok, change the code on email.php to:
<?php
if (isset($_POST['Submit'])){
$to = $_POST['email'];
$subject = "Test email";
$message = "Test message";
$headers = "From: test#test.com \r\n";
$headers .= "Reply-To: test#test.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);
}
?>
Hope this helps for all other rookies like me :)
Modern Answer without XHR or jQuery
It's 2022, we don't need to use old tools like XHR or jQuery when we have the Fetch API and the FormData API!
The first thing we need to do is prevent the default form submission behavior from occurring with event.preventDefault():
form.addEventListener("submit", function(event){
event.preventDefault();
// ...
});
Now we need to replace the submission behavior with our own AJAX request. The Fetch API makes it pretty simple to post form data - just create a new FormData object, populating it with the form's values, and use it as the body of a fetch request:
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form))
});
Note that this submits an HTTP request using the multipart/form-data format. If you need to post the data using application/x-www-form-urlencoded, create a new URLSearchParams object from the FormData object and use that as the fetch's body.
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form))
});
Here's a full code example:
let form = document.querySelector("form");
form.addEventListener("submit", function(event){
event.preventDefault();
fetch(form.action, {
method: "post",
body: //new FormData(form) // for multipart/form-data
new URLSearchParams(new FormData(form)) //for application/x-www-form-urlencoded
});
});
<form method="POST">
<input name="name" placeholder="Name" />
<input name="phone" type="tel" placeholder="Phone" />
<input name="email" type="email" placeholder="Email" />
<input name="submit" type="submit" />
</form>
The page will get reloaded if you don't want to use javascript
You will need to use JavaScript without resulting to an iframe (ugly approach).
You can do it in JavaScript; using jQuery will make it painless.
I suggest you check out AJAX and Posting.
if you're submitting to the same page where the form is you could write the form tags with out an action and it will submit, like this
<form method='post'> <!-- you can see there is no action here-->
Here is some jQuery for posting to a php page and getting html back:
$('form').submit(function() {
$.post('tip.php', function(html) {
// do what you need in your success callback
}
return false;
});
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){},
})
I'm pretty sure it has to do with my core.js file with the ajax hashing url. But I'm trying to submit a form, but it's not submitting like I want it to. This is the core.js file:
// call init
$(init);
function init() {
ajax_page_handler();
page_load($(window.location).attr("hash")); // goto first page if #! is available
}
function page_load($href) {
if($href != undefined && $href.substring(0, 2) == '#/') {
// replace body the #content with loaded html
$('#content').load($href.substring(2), function () {
$('#content').hide().fadeIn('slow');
});
}
}
function ajax_page_handler() {
$(window).bind('hashchange', function () {
$href = $(window.location).attr("hash");
page_load($href);
});
// this allow you to reload by clicking the same link
$('a[href^="#/"]').live('click', function() {
$curhref = $(window.location).attr("hash");
$href = $(this).attr('href');
if($curhref == $href) {
page_load($href);
}
});
}
The live viewing is over at www.krissales.com. The form is here: http://www.krissales.com/#/media/5.Testing-1
Hit the link "Post Comment", then you'll type info in, then hit comment, but it just refreshes, but doesn't submit it.
The steps I've taken to solve it was in the comment file, in the form action field, I inserted the tag name="#content" simply because that's the name of my div that I'm submitting to.
The original stuff is on http://blog.krissales.com/article/7.Testing-3-man ( where you can actually post a comment, and it'll work)
But apparently it's not working. Do you guys have a clue as to what it is that I'm doing wrong? thanks for your help in advance!
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form action="#/media/article.php" name="#content" method="POST">
Name:
<br />
<input type="text" name="name" class="userpass"/>
<br /><br />
Comment:
<br />
<textarea id="elm1" name="comment" rows="7" cols="30" style="width: 500px;">
</textarea>
<br />
<input type="submit" name="submit" value="Comment" class="button" />
<input type="reset" name="submit" value="Reset" class="button" />
</form>
I noticed that you are not setting the ajax type on the file 'comment.php'.
you need...
$.ajax({
type: 'POST',
url: 'comment_ajax.php',
data: { form_name: name, form_comment: comment },
success: function(data) {
$('#new_comment').prepend(data);
// close modal box
// do other shit
// kthnxbai
}
});
If type is not specified, it defaults to a GET request which will not post data. :)
Your current core.js handles changes in the URL hash, and it reroutes any links with a hash to load that relative path into #content. What's missing is code to redirect form submits to do the same thing (add this to ajax_page_handler):
$('form').live('submit', function(e) {
var $action = $(this).attr('action');
if($action.substring(0, 2) == '#/') {
// replace the #content with result of the form post
$.ajax({
url: $action.substring(2),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
$('#content').html(data);
$('#content').hide().fadeIn('slow');
}
});
// stop the real form submit from happening
e.preventDefault();
}
});
You should change the action attribute of your form like this :
<form action="script-handling-comment-data.php#/media/article.php" name="#content" method="POST">
For the moment, you're sending the comment data to http://www.krissales.com/ and i think the main page doesn't handle the comment posting.
You seem to be handling links properly, but form submission isn't a link, you probably want to handle submission using $(form).submit(function(){ ... })
In your case, if you gave your form the id form1
$('#form1').submit(function(){
var keyValues = $(this).serializeArray();
var map = {};
for(i in keyValues)
{
var value = keyValues.value;
var name = keyValues.name;
map[name] = value;
}
$.post($(this).attr('action'),map,function(){
alert("Submitted values: " + $(this).serialize());
});
return false;
})
See serializeArray, $.post and .submit for more information
I am trying to use jQuery-AJAX to submit the data in my form to my controller (index.php) where it is processed by PHP and inserted via PDO into the database if valid. Once the code is inserted into the database, the div where the form previously existed should be replaced by the contents of another page (newpage.php). The original page should not be refreshed upon submitting of the form, only the div where the form previously existed should be refreshed. There is a particular problem with my code, although I can't seem to find where the issue is at:
Here is my jQuery:
<script type="text/javascript">
function processForm() {
var action= $('#action').val();
var data = $('#data').val();
var dataString = 'action=' + action + '&data=' + data;
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
}
</script>
Here is my HTML: (As a side note, I noticed that when I take the "return false;" out of the HTML, that the form will submit to my database, but the whole page also reloads - and is blank. When I leave the "return false;" in the HTML, the newpage.php loads correctly into the div, but the data does not make it into the database)
<form action="" method="post" onsubmit="processForm();return false;">
<input type="hidden" name="action" value="action1" />
<input type="text" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Here is my PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
I feel like I am making a silly mistake somewhere, but I just can't put my finger on it. Thanks for any assistance you can provide!
SOLUTION (via Jen):
jQuery:
<script type="text/javascript">
function processForm() {
var dataString = $("#yourForm").serialize();
$.ajax ({
type: 'POST',
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
</script>
HTML:
<form id="yourForm">
<input type="hidden" name="action" value="action1" />
<input type="text" id="data" name="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
What I learned: Use the .serialize() jQuery method if it is an option, as it will save a bunch of time writing out the var for each form value and .serialize() does not typically make mistakes sending the info to php.
Give this a try:
$("#yourForm").submit(function(){
// Could use just this line and not vars below
//dataString = $("#yourForm").serialize();
// vars are being set by selecting inputs by id but id not set in form fields
var action= $('#action').val(); // value of id='action'
var data = $('#data').val(); // value of id='data'
var dataString = 'action=' + action + '&data=' + data;
// dataString = 'action=&data=' so nothing is posted to db
// because input fields cannot be found by id
// fix by adding id fields to form fields
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
And change the form to (I added the id attributes):
<form id="yourForm">
<input type="hidden" id="action" name="action" value="action1" />
<input type="text" id="data" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Seems like you need an explanation rather than a fix of code. Here is a brief explanation for the 2 cases:
When you take out return false; the code will treat your form as a normal HTML form that will be submitted to the server via action="", which leads to nowhere. The Javascript, however, also does its job in this case but because the page is redirected to nowhere, then it turns blank at the end.
When you put return false; back to the form, the form will catch the event handler and know that this form will be returned FALSE to submit. That's why you can see how your Javascript code does the job. However, one thing you should notice is that your jQuery AJAX function needs to POST (or GET) to a processing file, not '.'
Considering this reply based on no knowledge of your real situation. You need to look back over your code and see how you can edit it. Would be happy to reply if you have any questions.
Hope this small hint helps (: