How to pass both form data and credentials on submit in ajax ?
Last Updated :
12 Jan, 2023
The purpose of this article is to send the form data and credentials to the PHP backend using AJAX in an HTML document.
Approach: Create a form in an HTML document with a submit button and assign an id to that button. In JavaScript, the file adds an event listener to the form’s submit button i.e click. Then the request is made to a PHP file using jQuery Ajax.
Example:
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content =
"width=device-width, initial-scale=1.0" >
< script src =
</ script >
< script src = "script.js" ></ script >
</ head >
< body >
< div class = "container" >
< h1 >Demo Form</ h1 >
< form >
< input type = "text" name = "name"
id = "name" placeholder =
"Enter your Name" >
< input type = "text" name = "age"
id = "age" placeholder =
"Enter your Age" >
< textarea name = "aaddress"
id = "address" cols = "30"
rows = "10" placeholder =
"Enter your address" >
</ textarea >
< button type = "submit"
id = "submitBtn" >
Submit
</ button >
</ form >
</ div >
</ body >
</ html >
|
CSS
.container {
margin : 35px 0px ;
}
input,
textarea,
button {
display : block ;
margin : 30px auto ;
outline : none ;
border : 2px solid black ;
border-radius: 5px ;
padding : 5px ;
}
button {
cursor : pointer ;
font-size : large ;
font-weight : bolder ;
}
h 1 {
text-align : center ;
}
|
Javascript
let submitBtn = document.getElementById( 'submitBtn' );
submitBtn.addEventListener( 'click' , (event) => {
event.preventDefault();
let name = document.getElementById( 'name' ).value;
let age = document.getElementById( 'age' ).value;
let address = document.getElementById( 'address' ).value;
$.post( 'action.php' , {
name : name,
age : age,
address : address
}, (response) => {
console.log(response);
});
});
|
PHP
<?php
if (isset( $_POST [ 'name' ])) {
$name = $_POST [ 'name' ];
$age = $_POST [ 'age' ];
$address = $_POST [ 'address' ];
echo "Success" ;
}
?>
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...