PHP - How to avoid reload a form when change route - javascript

I have this simple form in index.php:
<div class="form-container">
<form id="create-form" action="create.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br/>
<label for="score">Amount:</label>
<input type="number" id="score" name="score">
<br/>
<input type="submit" name="addBtn" id="addBtn" value="Add" />
</form>
</div>
What create.php contains:
<?php
include 'db.php';
$name = $_POST["name"];
$score = $_POST["score"];
$sql = "insert into demo_table (name, score) values ('$name', '$score')";
$conn->query($sql);
$conn->close();
header("location: index.php");
?>
Currently, I have this script in index.js using JQuery and AJAX but keeps reloading the page because of the index.php call.
$(document).ready(function () {
$('#create-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'create.php',
data: $(this).serialize(),
success: function(response)
{
console.log('agregado');
location.href = 'index.php';
}
});
});
});
Currently this works well, but reloads the page when clicking on the button and when reload the data (last line in create.php). What I am trying to do is to implement AJAX and/or JQuery in order to avoid this and have a complete Single Page Application.
Disclaimer: I am starting learning PHP. So, I am making any mistake, please let me know first of all. I will be attentive to your answers.

Try to make in comment the code location.href = 'index.php'; inside the success method.
Like that :
$(document).ready(function () {
$('#create-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'create.php',
data: $(this).serialize(),
success: function(response)
{
console.log('agregado');
// location.href = 'index.php';
}
});
});
});

Related

PHP jQuery HTML form insert to MySQL then stay on same page

I have a simple PHP intranet site where there is an HTML form that takes 2 input fields. I want to take the user input from the HTML form, insert the values into MySQL database, but keep the user's browser on the same page. I have a separate PHP file that does the MySQL INSERT. I have been trying to do this with both pure PHP, and with the help of jQuery, but I can't get it to work! Any help would be greatly appreciated.
Here's my HTML form (which is in a PHP file):
<form name ="form" action="" method="POST">
Claim Title: <br>
<input type="text" name="title" required>
<span class="error">* </span>
<br><br>
Claim Body: <br>
<textarea name="claim" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name ="submit" value="Submit"/>
</form>
The PHP file that does the db processing is called db-insert.php:
<?php
require 'connect.php';
$conn = Connect();
// Claim form and sql insert variables
$title = $conn->real_escape_string($_POST['title']);
$claim = $conn->real_escape_string($_POST['claim']);
$claimInsert = "INSERT INTO claims(claim_title,claim_body,claim_type) VALUES('" . $title . "','" . $claim . "','T');";
$success = $conn->query($claimInsert);
$conn->close();
?>
The connect.php file:
<?php
function Connect(){
// Connection variables
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) or die($conn->connect_error);
return $conn;
}
?>
Finally the .js file that I've written (I use the term 'written' loosely as I obtained it from another StackOverflow page on something similar) is:
$(document).ready(function(){
$("button").click(function(){
$.get("db-insert.php", function(data, status){
alert("Data: " + data + "/nStatus: " + status);
});
});
});
I'm a bit of novice with jQuery/AJAX/related JavaScript and my PHP skills are growing but not amazing. I am using FireFox JavaScript debugger console and when I click the SUBMIT button for my form it isn't displaying anything, which makes me think it isn't processing the form data.
EDIT: I should have added this to underpin a comment made earlier in my post - I am in the early stages of dev work, please don't tell to parametrise and protect my SQL statements - I am aware of this :)
If your main goal is to do this without changing or refreshing the page, you can use Ajax and jQuery like this:
$(document).on('click', '#submit-my-form', function(){
var title = $("#title").val();
var claim = $("#claim").val();
jQuery.ajax({
type: "POST",
url: "http://your-site-url/db-insert.php",
dataType: 'json',
data: {title: title, claim: claim},
success: function(res) {
if (res)
{
alert('Hurray! Successfully done');
}
},
error: function(xhr) {
if (xhr)
{
alert('There was an error');
}
}
});
});
You can also add code to receive the insert status and process it in the return section of the Ajax code. Modify your html code by adding id tags to the inputs like this:
<input type="text" name="title" id="title" required>
<textarea name="claim" id="claim" rows="5" cols="40"></textarea>
<input type="submit" name ="submit" id="submit-my-form" value="Submit"/>
That should do it.
Use $.post() to send your data to PHP, and preventDefault() to prevent the page from reloading.
$.post() - Load data from the server using a HTTP POST request.
preventDefault() - The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
$(document).ready(function(){
$("form").on('submit', function(e){
e.preventDefault();
var data = {title: $('#title').val(), claim: $('#claim').val()};
console.log(data);
// $.post("db-insert.php", data, function(data, status){
// alert("Data: " + data + "/nStatus: " + status);
// });
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name ="form" action="" method="POST">
Claim Title: <br>
<input id="title" type="text" name="title" required>
<span class="error">* </span>
<br><br>
Claim Body: <br>
<textarea id="claim" name="claim" rows="5" cols="40"></textarea>
<br><br>
<input id="sub" type="submit" name ="submit" value="Submit"/>
</form>
Then in your db-insert.php
<?php
$title = $_POST['title'];
$claim = $_POST['claim'];
// rest of the code here
hope can help u
$("document").ready(function()
{
$("[name='submit']").click(function ()
{
sendS();
});
});
function sendS()
{
$.ajax(
{
type:"POST",
dataType:"json",
url:"php.php",
data:{title:$("[name='title']"),claim:$("[name='claim']")},
success: function(data)
{
//display or do somethg
alert(data);
},
error: function ()
{
alert("Error!");
}
});
}
<?php
$data1=$_POST["title"];
$data2=$_POST["claim"];
echo "Title : ".$data1."<br> Claim : ".$data2;
?>
Something like this
$(document).ready(function(){
$('form[name="form"]').submit( function(e){
e.preventDefault();
/*
you can put the url in the form action as normal,
its an old habit of mine, so if JavaScript is off on
the clients browser the form still works.
*/
var url = $(this).attr('action');
var iData = {
title: $('input[name="title"]').val(),
claim: $('textarea[name="claim"]').val()
};
console.log(url);
console.log(iData);
/*
Obviously you're going to need to un-comment this,
Ajax doesn't really work well on SO website
$.post(url, iData, function(data){
//do something on return
});
*/
//yea it's old school
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name ="form" action="db-insert.php" method="POST">
Claim Title: <br>
<input type="text" name="title" value="" required>
<span class="error">* </span>
<br><br>
Claim Body: <br>
<textarea name="claim" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name ="submit" value="Submit"/>
</form>

jquery.ajax, success and done function is not returning anything

I am a wordpress user and try to update the database using jquery.ajax. My code updates the database but the success function doesn't return anything to html div tag. Here are some portions of my code:
PHP Code:
$connect = mysqli_connect(HOST, USER, PASS, NAME);
if(mysqli_connect_errno()){
$msg = "Connection With Database is not Successful. Error: ".mysqli_error();
echo $msg;
die();
}
$nam = $_POST['name'];
$eml = $_POST['email'];
$entry = "INSERT INTO `table` (name, email,) VALUES ('$nam', '$eml')";
if(!mysqli_query($connect, $entry)){
$msg = "Error while submitting Your Data. Error: ".mysqli_error();
echo $msg;
die();
}
$msg = "Your data submitted successfully";
echo $msg;
mysqli_close($connect);
?>
HTML Code:
<form method="POST" id="data_form">
<input type="text" name="name" id="name" placeholder="Full Name" />
<br>
<input type="email" name="email" id="email" placeholder="Email Address" required />
<br>
<button type="submit" id="submit">Submit</button>
</form>
<div id="output"></div>
jQuery Code:
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false,
success: function(result){
$("#output").html(result);
}
});
});
});
I also used 'done' instead of 'success' but didn't work.
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false
}).done(function(result){
$("#output").html(result);
});
});
});
Actually I am trying to print the $msg variable from the php file to the 'output' div tag.
Any help would be greatly appreciated.

Posting html form data to php and accessing that through javascript

I'm trying to post some data to an html form, then that form sends the data to php, and finally javascript takes the data from that php.
This is my html form:
<form action="search.php" method='POST'>
<input id="movie_name" name="movie_name" type="text">
<input name="myBtn" type="submit" value="Submit Data">
</form>
This is my php file which is called search.php:
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo '<script>', 'hello();', 'var movie = '$movie_name';', '</script>';
}
?>
Finally my js script which is in the same file as the php one:
function hello(){
console.log('<?php echo $movie_name?;>');
}
What happens when I load this is that my html redirects ok and then for some in search.php nothing happens, the page goes white and the only thing the console says is "Resource interpreted as Script but transferred with MIME type text/html..."
What exactly you want is not clear. But i suggest you to use jQuery ajax like this:
<input id="movie_name" name="movie_name" type="text">
<input id="myBtn" name="myBtn" type="button" value="Submit Data">
$('#myBtn').click(function(e){
var movie_name = $('#movie_name').val();
$.ajax({
url: "search.php",
type: "POST",
data: {
'movie_name': movie_name
},
beforeSend : function() {
},
success : function(response) {
console.log(response);
},
error : function()
{
},
complete : function() {
}
});
});
in your search.php
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo $movie_name;
}
?>
This is better way from my point of view.
This should work:
<?php
if (isset($_POST['movie_name'])){
$movie_name = $_POST['movie_name'];
}
?>
<script type="text/javascript">
function hello(){
console.log('<?php echo $movie_name; ?>');
}
</script>
<?php
echo '<script> alert("'.$movie_name.'"); hello(); </script>';
?>

Sending data to server with $.ajax request

I have a simple form with 2 input:
<form name="contact" id="contact">
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
On submit I want using jQuery ajax method to send data to print.php. Code looks next:
var contact=$("#contact");
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
I want that Print.php script simply prints sent data, but nothing is happening. Script looks next:
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
echo $fname;
?>
Problem is obviusly in print.php.
you need to use following.
$("form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "print.php",
dataType: "json",
data: {
fname: firstName,
lname: lastName
},
success: functon(dt) {
alert(dt);
}
});
});
There is no $subject variable anywhere.
You set the first name and last name variables properly.
To check your script's response (which will be an error), go to your console and check network, and then repsonse data.
Change $subject to $fname and it should "work"
Also add on .on() submit event handler to your jQuery AJAX call like so:
$('form').on('submit', function() {
//ajax call
});
Edit:
You made an edit and changed $subject to $name. There is no $name variable either.
You do not need the JSON type on the ajax form. And include the preventDefault to avoid natural action(page refreshes when submitting)
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
event.preventDefault();
$.ajax({
type:"POST",
url:"print.php",
data:{
fname:firstName,
lname:lastName
}
});
});
It looks like your problem is that your HTML form doesn't know where to go ounce the submit happens and that is why nothing is happening. You need to tell your HTML form to run javascript.
You could link your HTML form to your javascript by using JQuery's .submit() method document here http://api.jquery.com/submit/
This will trigger your javascript to run once it is submitted if you wrap all your javascript around it.
$("form").submit(function( event ) {
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
Also you could give your HTML form an action so it knows what to do when the form is submitted.
Below we are saying run myFunction() when this form is submitted, we will then need to wrap all your javascript in myFunction().
<form name="contact" action=“javascript:myFunction();”>
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
Your javascript will look like this
function myFunction(){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
}
Once you get that far you will want to fix your php. The way you have it now $name is empty and won't print anything. You will want to fill the variable in before you echo it out. I am assuming you want $name to contain a concatenated version of $fname and $lname.
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
$name = $fname . ' ' . $lname;
echo $name;
?>
That should work for you.

Using AJAX to post form data to PHP page

I am simply trying to use the data submitted in a search form to query the database and bring back results similar to the search. My form looks like this:
<div id="searchform">
<form method="get">
<form id="submitsearch">
<input id="shop" name="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="submit" value="Go"/>
</form>
</form>
<div id="searchresults">
</div>
</div>
the Javascript I've got is:
$("#submitsearch").submit(function(event) {
event.preventDefault();
$("#searchresults").html('');
var values = $(this).serialize();
$.ajax({
url: "external-data/search.php",
type: "post",
data: values,
success: function (data) {
$("#searchresults").html(data);
}
});
});
return false;
I have also tried...
$("#submitbutton").click(function(){
var form_data = $("#submitsearch").serialize();
$.ajax({
url: "external-data/search.php",
type: 'POST',
data: form_data,
success: function (data) {
$("#searchresults").html(data);
}
});
return false;
});
And this seems to work slightly as it shows results, the first doesn't do anything. It's not sending the data to the PHP page but the PHP I've got is:
<?php
$str_shops = '';
$shop = $_POST['form_data'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE name LIKE '%$shop%'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<strong>" . $row['name'] . "</strong><br>" .
$row['address'] . "<br><br>";
}
mysqli_free_result($result);
echo $str_shops;
mysqli_close($db_server);
?>
Any help would be greatly appreciated! Thanks in advance.
You have two form tags. This won't work. You want one form tag with two attributes
<form method="get">
<form id="submitsearch">
to
<form method="get" id="submitsearch">
you can do it without using html form.
first you call the php page and then display a data within html.
this is what I do?!
<div>
<input id="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="button" value="Go"/>
</div>
<div id="searchresults">
</div>
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function(){
try
{
$.post("root/example.php",
{
'shop':$("#shop").val().trim()
}, function(data){
data=data.trim();
$("#searchresults").html(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>

Categories

Resources