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.
Related
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>
I have some working code but want to add upload image field but with no success.
My current code is:
Form:
<form id="add_product_form" enctype="multipart/form-data">
<input id="uploadFile" type="file" name="image" class="img" /><br />
<input id="status" type="checkbox" checked /><br />
<input id="product" type="text" /><br />
<label for="button" id="response"></label>
<input type="button" id="button" value="Добави" /><br />
</form>
jQuery:
<script type="text/javascript">
$('document').ready(function(){
$('#button').click(function(){
var image = $('input[type=file]').val().split('\\').pop();
function chkb(bool){ if(bool) return 1; return 0; } var status=chkb($("#status").is(':checked'));
if($('#product').val()==""){ alert("enter name"); return false; } else { var product = $('#product').val(); }
jQuery.post("products_add_process.php", {
image: image,
status: status,
product: product
},
function(data, textStatus) {
$('#response').html(data);
if(data == 1){
$('#response').html("OK");
$('#response').css('color','green');
document.getElementById("add_product_form").reset();
} else {
$('#response').html("Not OK");
$('#response').css('color','red');
}
});
});
});
</script>
products_add_process.php:
<?php
$image_name = $_FILES['image']['name'];
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
$image_tmp_name = $_FILES['image']['tmp_name'];
$status = $_POST['status'];
$product = $_POST['product'];
if($image_name == '') {
echo "<script>alert('Select image')</script>";
exit();
} else {
$random_digit=rand(0000000000,9999999999);
$image=$random_digit.$image_name;
move_uploaded_file($image_tmp_name,"uploads/$image");
$query=mysql_query("INSERT INTO products(product, image, status) VALUES ('$product', '$image', '$status')");
if(mysql_affected_rows()>0){
$response = 1;
echo "1";
} else {
$response = 2;
echo "2";
}
}
?>
I put alert 'Select image' and then understand that $image_name is empty and maybe somewhere have to put some code to say that I want to send DATA TYPE. I try to add to form enctype="multipart/form-data" but won't work.
Where and what have to add in existing code to make sending data, without making very big changes because this code have in a lot of files and will be difficult to edit big part of codes.
Maybe have to add that form and jQuery are in php file which is called in other mother file and structure is something like this:
products.php /call products_add.php/
products_add.php /where is the form and jQuery/
products_add_process.php /called from products_add.php to upload data/
p.s. Sorry if I don't explain my problem well but I'm from soon at stackoverflow and still learning how to post my questions :)
I have problem with pop up form . It doesn't send email. Here is html form:
<form action="#" method="post" id="form" >
<img src="images/3.png" id="close"/>
<h2>Contact Us</h2><hr/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<textarea name="message" placeholder="Message" id="msg"></textarea>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
JS to pop up html form:
function check_empty(){
if(document.getElementById('name').value == ""
|| document.getElementById('email').value == ""
||document.getElementById('msg').value == "" ){
alert ("Fill All Fields !");
}
else {
document.getElementById('form').submit();
alert ("Form submitted successfully...");
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}
And php function to send form data to email. Everything work but i don't receive email on gmail. Similar php script i used to post email without pop up and it worked.
<?php
if(isset($_POST['submit'])){
$to = "myemail#gmail.com";
$from = $_POST['email'];
$first_name = $_POST['name'];
$message = $first_name . " wrote following:" . "\n\n" . $_POST['message'];
mail($to,$from,$message);
}
?>
Simple: You don't have an element named "submit" in your form, so your if() test always fails.
id != name in HTML forms; meaning, id does not equal name.
A simple work around:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted ...
}
But this code is bad in any case. You should NEVER use only client-side validation. It's too easy to bypass. ALWAYS validate/verify on the server as well.
You should set your action in the form to the URL of your action in the server.
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.
I'm new to ajax concept. Here i'm trying to insert the user details(signup form) into the database. it inserted the datas into the db succesfully. But, ajax is my problem.
1) i didn't get any error message if form fields are empty. you can see my below codes i've done validation on post.php page. but, it doesn't return the error values. 2) it stores the empty values into database. 3) if datas stored successfully i want to get the success message & if datas failed to store in db i want to get the error message. How should i do these all things?
Ajax.js
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function(msg) {
if(msg=='error_n')
{
$("#e_name").html('Name required');
}
if(msg=='error_m')
{
$("#e_mobile").html('Mobile required');
}
//success and error alert
if(data="inserted")
{
alert("insertion success");
}
else
{
alert("falid to insert into database");
}
}
});
e.preventDefault();
});
});
Post.php
<?php
include_once('config.php');
$name = trim($_POST["name"]);
$mobile = trim($_POST["mobile"]);
if($name == "")
{
echo 'error_n';
}
if($mobile == "")
{
echo 'error_m';
}
try
{
$stmt = $conn->prepare("INSERT INTO sample ( Name, Mobile ) VALUES ( ?, ? )");
$conn->errorInfo();
$stmt->bindParam('1', $name, PDO::PARAM_STR);
$stmt->bindParam('2', $mobile, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database' .$e->getMEssage();
}
?>
Homepage.php
<p>register here</p>
<div id="light" class="white_content">
Close
<form>
<input type="hidden" name="form" value="values" />
name : <input name="name" id="name" type="text" /><span id="e_name"></span> <br />
mobile : <input name="mobile" id="mobile" type="text" /><span id="e_mobile"></span> <br />
<input type="submit" value="submit" />
</form>
</div>
<div id="fade" class="black_overlay"></div>
After your error messages are returned, you need to stop the script execution. Your current code still tries to add the values and hence overrides your custom error messages. Most probably then your PHP returns your exception message and which is not what your JavaScript is expecting.
if($name == "")
{
echo 'error_n';
die(); // Stop here
}
if($mobile == "")
{
echo 'error_m';
die(); // Stop here
}
Also add echo 'inserted'; when your database insert is successful.