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

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>

Related

PHP - How to avoid reload a form when change route

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

how to change geojson search parameters from html form

I made a geojson file using php from a database, but I need to be able to change the query parameters using a form from the main page, here is the form and the loaded json file:
<script src="js/jquery-3.3.1.min.js" type="text/javascript"></script>
<div class="form">
<form method="get">
<input type="text" name="number" id="number" placeholder="to" >
<input type="text" name="startDate" id="sDate" placeholder="From" >
<input type="text" name="endDate" id="eDate" placeholder="till"><br/>
<input type="submit" name="Search" id="Search" value="Search">
</form>
</div>
<script>
var geoJsonData = $.ajax({
url: "json2.php",
dataType: "json",
success: console.log("succes"),
error: function (xhr) {
alert("Json error")
}
})
</script>
and here is the query from the geojson file(json2.php):
$number = $_GET['number'];
$startD = date('d.m.Y');
$endD = date('d.m.Y');
$startData = strtotime($startD . '00:00:00');
$pgsqlstartdata = date('Y-m-d H:i:s', $startData);
$endData = strtotime($endD . '23:59:59');
$pgsqlenddata = date('Y-m-d H:i:s', $endData);
$query = pg_query($connect, "SELECT number, state, date, lat,long "
. "FROM schema.table "
. "WHERE number = '$number' AND "
. "data BETWEEN '$pgsqlstartdata' and '$pgsqlenddata' order by data asc limit 100 ");
when i try to include the json fle to the form file its giving me parese error because the form its not json format, so anyone has any ideea how to send the parameters?
I'm not sure exactly what you want to accomplish, but if the goal is to pass the form to PHP as json, then you need to use the serialize() function. Also, you are not currently passing any data with your AJAX call. Let's fix that.
First, change your form method to post and add an id to your form so we can access it directly:
<form method="post" id="geoform">
Next, change the first rows in your AJAX call:
var geoJsonData = $.ajax({
url: "json2.php",
dataType: "json",
type: "post",
data: $("#geoform").serialize(),
Finally, deserialize and output the form in PHP so you can see what you're working with:
<?php
$formData = json_decode($_POST);
var_dump($formData);

PHP form stay on same page

Hi i am trying to update data in a database from a form on the same page as the php code without redirecting/reloading the page.
I tried this tutorial but that didn't work: http://www.formget.com/form-submit-without-page-refreshing-jquery-php/
Update code:
<?php
include "db.php";
session_start();
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
?>
Profilecomplete.js:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {
value: name
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
The form:
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate">
<label for="name">Value</label>
</div>
<button type="submit" id="submit" class="btn-flat">Update</button>
</form>
Use this, it's working already.
index.php
<form method="post">
<input type="text" id="name">
<input type="submit" id="submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var nameInput = $("#name").val();
var name = {
'name' : nameInput
}
if (nameInput == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {value: name}, function(data) {
alert(data);
//$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
profilecomplete.php
<?php
$_POST = array_shift($_POST); // array_shift is very important, it lets you use the posted data.
echo $_POST['name'];
?>
if you want a more simple way.
try to use $.ajax()
It looks like the issue, or at least, one of the issues, is on this line;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
You are opening and closing the single quotes twice, here
WHERE username='$_SESSION['user']'
Try using this instead;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='" . $_SESSION["user"] . "'");
How your click event can occur even if you are not preventing the default behavior of the form submit button. Make the submit input as a button or use event.preventDefault() to submit the form via ajax.
<?php
include "db.php";
session_start();
if(isset($_POST)) {
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='{$_SESSION['user']}'");
echo ($query) ? "Updated" : "Not Updated";
exit;
} else {
?>
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate" name="name">
<label for="name">Value</label>
</div>
<button type="button" id="submit" class="btn-flat">Update</button>
</form>
<?php } ?>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name === '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {name: name}, function(data) {
alert(data);
$('form')[0].reset(); // To reset form fields
});
}
});
});
</script>

Issue receiving a response using AJAX, jQuery and PHP

I am trying to figure out how to send values and receive the right response.
The only response that I can seem to get is 0.
This is the AJAX and form I am sending with:
<script type="text/javascript">
$(document).ready(function(){
$(':submit').on('click', function() {
var email = $("#txtEmail").val();
var password = $("#txtPassword").val();
$.ajax({ // ajax call starts
url: 'isValid.php',
data: {'email': $("#txtEmail").val(),
'password': $("#txtPassword").val()
},
dataType: 'json', // Choosing a JSON datatype
})
.done(function(data) {
$('#valid').html(data);
});
return false;
});
});
</script>
<form method="post" action="">
Email:<br/>
<input id="txtEmail" name="txtEmail" type=text/><br/>
Password:<br/>
<input id="txtPassword" name="txtPassword" type=text/><br/>
<input type="submit" value="Login"/>
<input type="reset" value="Clear"/>
</form>
<div id="valid"></div>
This is the php script I am using to try and send the response back:
<?php
$email = $_GET["login"];
$pass = $_GET["password"];
print json_encode($email + " " + $pass);
?>
All I am getting back is a 0 and am not sure why.
Thats because you are concatenating wrongly your response, and you have wrong parameters in your get:
<?php
$email = $_GET["email"];
$pass = $_GET["password"];
print json_encode($email . " " . $pass);
?>

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