PHP form stay on same page - javascript

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>

Related

Pass values to $('form').submit(function ()

I am absolute begginner for the programming. Here I want to pass a argument to $('form').submit(function () {. Just I want to pass the email value to .submit() function, that has been created like this,
Here is the HTML code,
<div id="friends">
<?php
$query=$pdo->prepare("SELECT DISTINCT * FROM users as u
WHERE EXISTS (SELECT * FROM appointment as a
WHERE u.user_id = a.user_id AND
a.p_id= '".$_SESSION['p_id']."')");
$row=$query->execute();
$rs=$query->fetchAll(PDO::FETCH_OBJ);
foreach ($rs as $message){
$filename= $message->image;
$filepath="../../adminpanel/profile/blog/";
?>
<div class="friend">
<?php
printf(
'<img class="inline-block" src="data:image/png;base64, %s" alt="user" />',
base64_encode(file_get_contents($filepath.$filename ) )
);
?>
<p>
<strong> <?php echo $message->username ?></strong> <br>
<span id="email"><?php echo $message->email ?></span>
</p>
<div class="status available"></div>
</div>
<?php } ?>
Here is the HTML for submit button
<form class="" id="msgform" action="chat.php" method="post">
<div id="sendmessage">
<input type="text" placeholder="Send message..." class="textarea" name="message"/>
<button id="send" class="textarea" ></button>
</div>
</form>
Below is the javascript code, that how to set email to html to appear.
$(".friend").each(function(x){
$(this).click(function(){
var name = $(this).find("p strong").html();
var email = $(this).find("p span").html();
LoadChat(email);
$("#profile p").html(name);
$("#profile span").html(email);
});
});
I have passed this email variable to submit function, but always takes the email of last user. Here is the .submit function to sent data to server.
$('form').submit(function() {
const email = <?= json_encode($message->email) ?>
var message = $('.textarea').val();
if ($(".textarea").val()) {
$.post("handlers/messages.php", {
action: "sendMessage",
message: message,
email: email
}, function(response) {
if (response == 1) {
LoadChat();
document.getElementById('msgform').reset();
}
});
} else {
myFunction();
}
return false;
})
Just I want to pass the particular email value to submit function. Please help me may highly appreciated and thanks in advance.
$('form').submit(function() {
var email = $('#email').val();
var message = $('.textarea').val();
if ($(".textarea").val()) {
$.post("handlers/messages.php", {
action: "sendMessage",
message: message,
email: email
}, function(response) {
if (response == 1) {
LoadChat();
document.getElementById('msgform').reset();
}
});
} else {
myFunction();
}
return false;
})
You were getting the email which was printed by php (server side). You need to send what is on client or browser side.
var email = $('#email').val();
This will solve your issue

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>

Why is this callback value blank in javascript?

I have a simple page. When I submit the form; I want to return the result that I get on the PHP page on the HTML page.
I have done the following:
<form id="myForm" action="addfaq.php" method="POST" enctype="multipart/form-data">
<input class="form-control focus" type="text" placeholder="Enter FAQ" name="faqQuestion" id = "faqQuestion">
<textarea class="form-control focus" placeholder="Enter FAQ description" name="faqDesc" id="faqDesc" draggable="false" style="resize:none" rows="4" cols="48"></textarea>
Select Images : <input type="file" id="files" name="img[]" accept="image/jpeg" multiple />
<button class="btn btn-info" id = "submit" name="submit_button">Submit</button>
This is my javascript code :
$("#submit").click( function() {
if( $("#faqQuestion").val() == "" || $("#faqDesc").val() == "" ){
$("#message").html("Question / description are mandatory fields -- Please Enter.");
} else{
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#message").empty();
$("#message").html("log = " + info);
console.log("log = " + info);
clear();
});
$("#myForm").submit( function() {
return false;
});
}
});
function clear() {
$("#myForm :input").each( function() {
$(this).val("");
});
}
The PHP code is for taking the form inputs from the user The PHP code is for taking the form inputs from the userThe PHP code is for taking the form inputs from the userThe PHP code is for taking the form inputs from the user:
<?php
if (isset($_POST['submit_button']))
{
$faqQuestion = $_POST['faqQuestion'];
$faqDesc=$_POST['faqDesc'];
$faqRole=$_POST['faqRole'];
if ($faqQuestion=="" and $faqDesc="" and $faqRole="")
{
echo "Incomplete information";
}
else
{
if(isset($_FILES['img'])){
// Database connectivity and query to database
$retval = mysql_query($sql);
if($retval){
echo "Question uploaded";
} else{
echo "Problem uploading question";
}
} else{
echo "Duplicate question";
}
mysql_close($con);
}
}
}
?>
The PHP code for inserting the info of above form to the database. The problem is that; the callback that my javascript gets is blank. Hence I am unable to get the result on the HTML page. Please correct me.
Only add this line in your form:
<input type="hidden" name="submit_button">
This will solve your issue.
And also do not forget to add faqRole field in your form.

AJAX not returning result from php

I am trying to learn from an example from online,for a login form with php and jquery and i am using the exactly the same example, but for some reason the AJAX isnt getting anything back but redirecting my to another php.
Here is a link of what i had been trying and the problem.
http://rentaid.info/Bootstraptest/testlogin.html
It supposed to get the result and display it back on the same page, but it is redirecting me to another blank php with the result on it.
Thanks for your time, i provided all the codes that i have, i hope the question isnt too stupid.
HTML code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id= "loginform" class="form-horizontal" action='http://rentaid.info/Bootstraptest/agentlogin.php' method='POST'>
<p id="result"></p>
<!-- Sign In Form -->
<input required="" id="userid" name="username" type="text" class="form-control" placeholder="Registered Email" class="input-medium" required="">
<input required="" id="passwordinput" name="password" class="form-control" type="password" placeholder="Password" class="input-medium">
<!-- Button -->
<button id="signinbutton" name="signin" class="btn btn-success" style="width:100px;">Sign In</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javasript" src="http://rentaid.info/Bootstraptest/test.js"></script>
</body>
</html>
Javascript
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
$("#loginform").submit(function() {
return false;
});
}
});
php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
//get form data
$username = addslashes(strip_tags($_POST['username']));
$password = addslashes(strip_tags($_POST['password']));
$password1 = mysqli_real_escape_string($con, $password);
$username = mysqli_real_escape_string($con, $username);
if (!$username || !$password) {
$no = "Please enter name and password";
echo ($no);
} else {
//log in
$login = mysqli_query($con, "SELECT * FROM Agent WHERE username='$username'")or die(mysqli_error());
if (mysqli_num_rows($login) == 0)
echo "No such user";
else {
while ($login_row = mysqli_fetch_assoc($login)) {
//get database password
$password_db = $login_row['password'];
//encrypt form password
$password1 = md5($password1);
//check password
if ($password1 != $password_db)
echo "Incorrect Password";
else {
//assign session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
}
}
}
}
?>
Edit
$("button#signinbutton").click(function(){
if($("#username").val() ==""||$("#password").val()=="")
$("p#result).html("Please enter both userna");
else
$.post ($("#loginform").attr("action"),
$("#loginform:input").serializeArray(),
function(data) {
$("p#result).html(data); });
});
$("#loginform").submit(function(){
return false;
});
First of all, Remove :-
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
and if you want to display the data, echo username and password.
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
echo $username."<br>".;
echo $password1;
The reason you are being redirected is that you are also calling $.submit. The classic form submit will redirect you to a new page, which is exactly what you don't want when you're using AJAX. If you remove this call:
$("#loginform").submit(function() {
return false;
});
you probably should have working solution. If not, let me know :)
Modify your javascript section so that
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
}
});
$("#loginform").submit(function() {
return false;
});
is outside the function call.

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