ajax [file 1] -> php [file 2] -> $_POST [file 1] - javascript

I am building a budget application with HTML, Javascript, and PHP. My goal is to have the user be able to add data into a database from a form provided. I already have a ton of php at the top of my 'dashboard.php' (which contains the form) so I didn't want to run dashboard.php on submit, so instead I created a button that preforms an AJAX call to a different php file 'addIncome.php'.
I have two different files...
dashboard.php &
addincome.php
dashboard.php contains my form, as well as my javascript to run an AJAX call.
addincome.php is using $_POST to grab the values from the form in dashboard.php and make a mysqli_query. However, at first nothing was happening so I decided to echo the value of one of the return values from my $_POST. And ended up getting this error...
undefined index iName in addIncome.php
undefined index iAmount in addIncome.php
So from there I though that maybe I didn't have access to the dashboard.php by default so I included...
include('dashboard.php');
Still no difference...
I'm really at a stand still here. Any thoughts?
Thanks
The form...
<form>
<input type="text" name="iName" placeholder="income name">
<input type="number" step="0.01" min="0" name="iAmount" placeholder="amount">
<input type="date" name="iDate">
</form>
The javascript...
<script>
$('.in-btn').click(function() {
$.ajax({
url: "addIncome.php",
type: "POST",
data: 'show=content',
success: function(data) {
$('.in-btn').html(data);
}
});
setTimeout(() => {
// location.reload();
}, 2000);
});
</script>
The php...
<?php
echo "adding...";
require_once('connection.php');
include('dashboard.php');
$iUser = $_SESSION["username"];
$iName = $_POST["iName"];
$iAmount = $_POST["iAmount"];
echo $iName;
$sql = "INSERT INTO income (user, name, amount, date) VALUE ('pmanke', '$iName', '$iAmount','1/16/19')";
mysqli_query($dbCon, $sql);
?>

You are not sending any post data with your AJAX call except for:
show=content. You want to send your form data. You can retrieve your form data with:
$("#id-of-form").serialize()
That way your PHP code is able to retrieve the correct values from your POST data.
An even more general way to do this is to just create a normal form with a submit button and an action and use javascript to catch the submit event and make an AJAX call instead:
HTML:
<form id="idForm" action="addIncome.php">
<input type="text" name="iName" placeholder="income name">
<input type="number" step="0.01" min="0" name="iAmount" placeholder="amount">
<input type="date" name="iDate">
<input type="submit" />
</form>
Javascript:
$("#idForm").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

Related

Get input field value in same page without refreshing page php

I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}

Passing variable from PHP to Javascript, using Ajax returns 'undefined'

I have got a PHP file that received data that has been posted from a form. It then sends it to a database. However I needed to get those variables and put them in JavaScript. I have done the following, but when logging the variables supposed to store the php data (in the script file) it return undefined.
What am I doing wrong? I am new to all the languages. The files are all separate - with the PHP and Script files being external.
SCRIPT:
$(function(){
var data1 = $("#username").val();
console.log(data1);
$.ajax({
type: "POST",
url: 'signUp.php',
data: ({data1}),
success: function(data) {
console.log("success");
}
});
});
PHP
if (isset($_POST['signup'])){
//The connection to the database
include_once 'databaseHandler.php';
//Gets the infomation submitted from the form
//Protects the database by converting everything to text...
//The database therefore cannot read the inputs as code
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
echo (".$user.");
HTML
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
You never set the post parameter 'signup'. Which in turn does not let you enter your if construct and therefor php gives you nothing.
Try:
data:{
"username":$('usernameSignUp').val(),
"password":$('passwordSignUp').val(),
"signup":1,
}
I think, you don't send the variable correctly.
var data1 = $("#usernameSignUp").val();
var data2 = $("#passwordSignUp").val();
$.ajax({
type: "POST",
url: 'signUp.php',
data: {signup:'1',username:data1,password:data2 },//Supose data1= username data, data2 = password data
success: function(data) {
console.log("success");
}
});
There is so much wrong here, it is hard to know where to begin.
You make the Ajax request when the page loads. This is before the user has typed anything into the form.
When the form is submitted, you don't use Ajax at all
You pass a field called data1 to the server (which it is not looking for)
You give that field the value of the input with id="username" (which doesn't exist)
You don't pass fields called username or password to the PHP (which it is looking for)
You don't pass a field called signup to the PHP (which it tests for with isset before doing anything)
Your PHP echos a variable called $user which you haven't defined
Your JavaScript doesn't look at the response, it just logs the string "success"
You'd need something more like:
$(function() {
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: 'http://example.com/signUp.php',
data: ({
signup: 1,
username: $("#usernameSignUp").val(),
password: $("#passwordSignUp").val()
}),
success: function(data) {
console.log("Success", data);
},
error: function(data) {
console.log("This is a cross origin request to a dummy URL, what did you expect");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
Then there are the things which are bad practises but which don't directly affect the ability of the code to work.
You use mysqli_real_escape_string instead of placeholders.
You don't hash your passwords. "Not hashing at all" is an unsuitable hashing algorithm; you need to take better care of your users' passwords.
The HTML5 placeholder attribute is not a substitute for the label element

Ajax post not working codeigniter

I am using codeigniter 3.1
Ajax post not working and i am getting 403 (Forbidden) in console.
[POST http://localhost/test/post 403 (Forbidden)]
HTML
<div class="post">
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
</div>
<button id="post">Submit</button>
JAVASCRIPT
$('#post').on('click', function () {
var value1=$("#data1").val();
var value2=$("#data2").val();
$.ajax({
url: window.location.href+'/post',
type: "POST",
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
});
CONTROLLERS
public function post()
{
$data1 = $this->common->nohtml($this->input->post("data1", true));
$data2 = $this->common->nohtml($this->input->post("data2", true));
$this->data_models->update($this->data->INFO, array(
"data1" => $data1,
"data2" => $data2,
)
);
}
If you want CSRF protection on (a good idea) then you must pass the CSRF token when posting form data - via AJAX or not. Consider this approach.
The easiest way to put the token in your form is to use Codeigniter's "Form Helper" (Documented here) You can load the function your controller or use autoloading. This view code assumes you have the helper loaded.
HTML
<div class="post">
<?= form_open('controller_name/post'); //makes form opening HTML tag ?>
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
<?php
echo form_submit('submit','Submit', ['id'=>'post']); //makes standard "submit" button html
echo form_close(); // outputs </form>
?>
</div>
The form_open() function also automatically adds a hidden field containing the CSRF token to the HTML.
Javascript
$('#post').submit(function( event ) {
//the next line will capture your form's fields to a format
//perfect for posting to the server
var postingData = $( this ).serializeArray();
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
data: postingData,
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
controller
By the time $_POST gets to your controller the CSRF token has been striped away so you don't have to worry about it "polluting" your incoming data.
public function post()
{
//get all the posted data in one gulp and NO, you do not want to use xss_clean
$posted = $this->input->post();
//With the above the var $posted has this value (showing made up values)
// array("data1" => "whatever was in the field", "data2" => "whatever was in the field");
//sanitize the field data (?)
//just stick the clean data back where it came from
$posted['data1'] = $this->common->nohtml($posted["data1"]);
$posted['data2'] = $this->common->nohtml($posted["data2"]);
$this->data_models->update($this->data->INFO, $posted);
//you must respond to the ajax in some fashion
//this could be one way to indicate success
$response['status'] = 'success';
echo json_encode($response);
}
You could also send back some other status if, for instance, the model function reported a problem. You then need to react to that status in you javascript. But if you don't respond it will likely result in problems down the road.

Submitting form with AJAX not working. It ignores ajax

I've never used Ajax before, but from researching and other posts here it looks like it should be able to run a form submit code without having to reload the page, but it doesn't seem to work.
It just redirects to ajax_submit.php as if the js file isn't there. I was trying to use Ajax to get to ajax_submit without reloading anything.
Is what i'm trying to do even possible?
HTML form:
<form class="ajax_form" action="ajax_submit.php" method="post">
<input class="input" id="license" type="text" name="license" placeholder="License" value="<?php echo htmlentities($person['license1']); ?>" />
<input class="input" id="license_number" type="text" name="license_number" placeholder="License number" value="<?php echo htmlentities($person['license_number1']); ?>" />
<input type="submit" class="form_button" name="submit_license1" value="Save"/>
<input type="submit" class="form_button" name="clear1" value="Clear"/>
</form>
in scripts.js file:
$(document).ready(function(){
$('.ajax_form').submit(function (event) {
alert('ok');
event.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize(),
success: function (data) {alert('ok');}
});
});
});
in ajax_submit.php:
require_once("functions.php");
require_once("session.php");
include("open_db.php");
if(isset($_POST["submit_license1"])){
//query to insert
}elseif(isset($_POST['clear1'])) {
//query to delete
}
I have "<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>"
in the html head
form.serialize() doesn't know which button was used to submit the form, so it can't include any buttons in the result. So when the PHP script checks which submit button is set in $_POST, neither of them will match.
Instead of using a handler on the submit event, use a click handler on the buttons, and add the button's name and value to the data parameter.
$(":submit").click(function(event) {
alert('ok');
event.preventDefault();
var form = $(this.form);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize() + '&' + this.name + '=' + this.value,
success: function (data) {alert('ok');}
});
});
Your ajax call is working perfectly. You have few conceptual error with your code -
form.serialize() will not attach submit button's info.
If you want to clear your form, you can do it using something like this
$('#resetForm').click(function(){
$('.ajax_form')[0].reset();
});
Lastly complete your task & return success or failed value to ajax call using echo like echo 'successful' or echo failed etc. Use an else condition with your code. It will be more clearer to you.
Remove the "action" and "method" attributes from the form. You shouldn't need them.

Submit form without page reloading

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;
});

Categories

Resources