Displaying a success message after form submission - php

I'm trying to understand jquery and particularly inserting and displaying data in a mysql table using ajax.
I have been experimenting with this code which inserts and displays records from a mysql database. I'm now trying to get it to display the success message in the div with the id "info" whilst also displaying all the records. I seem to only do one but never both. Many thanks.
form.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function showComment(){
$.ajax({
type:"post",
url:"process_ajax.php",
data:"action=showcomment",
success:function(data){
$("#comment").html(data);
}
});
}
showComment();
$("#button").click(function(){
var username=$("#username").val();
var review=$("#review").val();
$.ajax({
type:"post",
url:"process_ajax.php",
data:"username="+username+"&review="+review+"&action=addcomment",
success:function(data){
$("#info").html(data);
}
});
});
});
</script>
</head>
<body>
<form>
Username : <input type="text" name="username" id="username"/>
</br>
Review : <input type="text" name="review" id="review" />
</br>
<input type="button" value="Send Comment" id="button">
</form>
<div id="info" />
<ul id="comment"></ul>
</body>
</html>
Process_ajax.php
<?php
include_once("db_conx.php");
$action=$_POST["action"];
if($action=="showcomment"){
$show="Select * from user_reviews ORDER by date desc";
$result = $db_conx->query($show);
while($row=mysqli_fetch_array($result)){
echo "<li><b>$row[username]</b> : $row[review]</li>";
}
}
else if($action=="addcomment"){
$username= ($_POST['username']);
$review= ($_POST['review']);
$stmt = $db_conx->prepare('INSERT user_reviews SET username = ?, review=?');
$stmt->bind_param('ss', $username, $review);
$stmt->execute();
if ($stmt->errno) {
echo "There was an error in saving your review. Please try again." . $stmt->error;
}else{
echo "Your review has been saved";
}
}
?>

Save the record data as an array and the message as a normal var and create a json:
$list = '';
while($row=mysqli_fetch_array($result)){
$list .= "\n<li><b>$row[username]</b> : $row[review]</li>";
}
if ($stmt->errno) {
$msg = "There was an error in saving your review. Please try again." . $stmt->error;
}else{
$msg = "Your review has been saved";
}
echo json_encode(["list"=>$list, "msg"=>$msg]);
Remember to put in the dataType into the Ajax:
type:"post",
dataType: "json"
Then in your success function, you can access the vars: data.list and data.msg

Related

Want to run PHP query when submit button submitted using AJAX

I want to run insert.php query if button name with "addUser" is submitted i don't know how to pass addUser name parameter using AJAX to insert.php file where it check if button is submitted or not .
if i remove if statement in insert.php file this is inserting users to database but if directly visit insert.php its inserting empty records in table
i want to prevent entry of empty records in table if i visit insert.php directly .
index.html
<form method="post" id="addForm">
Username :<input type="text" name="username" id="userName" />
Passkey :<input type="password" name="passkey" id="passKey"/>
<br/>
<input type="submit" name="addUser" id="submitBtn" value="Inser New User"/>
</form>
<script>
$("#addForm").submit(function(e){
let userNameZ = $("#userName").val();
let passKeyZ = $("#passKey").val();
$.ajax({
url:'insert.php',
type:'POST',
data: {userName:userNameZ,passKey:passKeyZ},
success: function(resp) {
if(resp == "inserted") {
$("#addForm").trigger("reset");
alert("New user inserted");
} else {
alert("Something went wrong");
}
}
});
});
</script>
insert.php
<?php
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");
if(isset($_POST['addUser'])){
$userName = trim($_POST['userName']);
$passKey = trim($_POST['passKey']);
$query = "INSERT INTO users (username,passkey) VALUES (:userName,:passKey)";
$stmt = $conn->prepare($query);
$stmt->execute(array(':userName'=>$userName, ':passKey'=>$passKey));
if($stmt) {
echo "inserted";
} else {
echo "not inserted";
}
}
?>
Change this if(isset($_POST['addUser'])){
to
if(isset($_POST['userName']) && isset($_POST['passKey'])){
OR in ajax, change
data: {userName:userNameZ,passKey:passKeyZ,addUser:1},
Notice: ,addUser:1
Adding answer to your comment
what if i have more than 10 values to be submit
.
You can use $("#addForm").serialize() and pass directly to data. Like
data: $("#addForm").serialize(),

Pop-up message after submitting a form with php

I'm trying to get a pop-up message saying if it was successfully submitted or not without having to go to a different page.
Now chrome gives me the pop-up message but it redirects me to a blank page after.
Here is my current code.
<?php
include "header.php";
include "conexao.php";
echo "<h1 align='center'>Pagina para alterar produtos</h1><div class='container'><hr>";
$referencia=$_GET['id'];
$sql = "SELECT * ";
$sql = $sql . " FROM tb_produto ";
$sql = $sql . " WHERE pr_codigo='".$referencia."'";
$produtos = $db->query($sql);
foreach ($produtos as $produto) {
$referencia = $produto["pr_codigo"];
$nome = $produto["pr_descricao"];
$preco = $produto["pr_preco"];
$disponivel = $produto["disponivel"];
}
echo "<h2>Referencia: ".$referencia."</h2>";
echo "<h2>Nome: ".$nome."</h2><hr>";
?>
<form action="confirmaAlterar.php">
<div class="form-group">
<label>Referencia</label>
<input class="form-control" type="text" name="referencia" value="<?php echo $referencia?>">
</div>
<div class="form-group">
<label>Nome</label>
<input class="form-control" type="text" name="nome" value="<?php echo $nome?>">
</div>
<div class="form-group">
<label>Preço</label>
<input class="form-control" type="text" name="preco" value="<?php echo $preco?>">
</div>
<button class="btn btn-primary">Alterar</button>
</form>
Here is where it submits the information of the form.
<?php
include "header.php";
include "conexao.php";
$nome=$_GET['nome'];
$referencia=$_GET['referencia'];
$preco=$_GET['preco'];
$sql="UPDATE tb_produto SET pr_descricao='".$nome;
$sql.="', pr_preco=".$preco;
$sql.= " WHERE pr_codigo='".$
try{
$comando=$db->prepare($sql);
$comando->execute();
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header( "refresh2;Location:index.php" );
}
catch (PDOException $e){
echo "A";
}
To pass values using ajax. Form:
<form id="form">
<input type="text" value="test" name="akcija">
</form>
All inputs fields values in your form will be passed.
Ajax:
jQuery(function(){
$('#form').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'yoururl.php', //URL of page where u place query and passing values
data: $('#form').serialize(), //seriallize is passing all inputs values of form
success: function(){ //on success function
$("#input").attr("disabled", true); //example
$("#input").removeClass('btn-primary').addClass('btn-success');//example
},
});
}
});
And on the ajax page you can get values by
$akcija = $_POST['akcija']
for this Problem you must use ajax method .
1- create html form and all input Required .
<form id="contactForm2" action="/your_url" method="post">
...
</form>
2- add jQuery library file in the head of html page .
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
...
3- add this method Under the jQuery library
<script type="text/javascript">
var frm = $('#contactForm2');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data == 'pass')
alert('ok');
else(data == 'fail')
alert('no');
}
});
ev.preventDefault();
});
</script>
4- in your_url .php file
<?php
$a = ok ;
if( $a == 'ok' ){
echo 'pass';
}else{
echo 'fail';
}
?>
this top answer is easy management form with jquery , but you need managment Complex form better use this library http://jquery.malsup.com/form/

Insert data through ajax into mysql database

Newsletter:
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<span><span class="style2">Enter you email here</span>:</span>
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit" onclick="return fun()" />
</form>
<?php
mysql_connect("localhost","","");
mysql_select_db("");
error_reporting(E_ALL && ~E_NOTICE);
$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
if(!$sql)
die(mysql_error());
mysql_close();
?>
But I want to insert my E-Mail to database through Ajax. I don't want my page to get redirected, because every time the page got refreshed, null value got inserted to the database..
I just want my E-mail got inserted to database through Ajax, and after that the email box
i.e.
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit" onclick="return fun()" />
should get disappeared and there should be the line "you've been successfully subscribed" ..
Any brief code will be very useful.. thank u in advance :)
Try this:
$(document).on('click','#save',function(e) {
var data = $("#form-search").serialize();
$.ajax({
data: data,
type: "post",
url: "insertmail.php",
success: function(data){
alert("Data Save: " + data);
}
});
});
and in insertmail.php:
<?php
if(isset($_REQUEST))
{
mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);
$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
}
?>
Don't use mysql_ it's deprecated.
another method:
Actually if your problem is null value inserted into the database then try this and here no need of ajax.
<?php
if($_POST['email']!="")
{
mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);
$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
//echo "You have been successfully subscribed.";
setcookie("msg","You have been successfully subscribed.",time()+5,"/");
header("location:yourphppage.php");
}
if(!$sql)
die(mysql_error());
mysql_close();
}
?>
<?php if(isset($_COOKIE['msg'])){?>
<span><?php echo $_COOKIE['msg'];setcookie("msg","",time()-5,"/");?></span>
<?php }?>
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<span><span class="style2">Enter you email here</span>:</span>
<input name="email" type="email" id="email" required/>
<input type="submit" value="subscribe" class="submit"/>
</form>
The ajax is going to be a javascript snippet that passes information to a small php file that does what you want. So in your page, instead of all that php, you want a little javascript, preferable jquery:
function fun()
{
$.get('\addEmail.php', {email : $(this).val()}, function(data) {
//here you would write the "you ve been successfully subscribed" div
});
}
also you input would have to be:
<input type="button" value="subscribe" class="submit" onclick="fun();" />
last the file addEmail.php should look something like:
mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);
$email=mysql_real_escape_string($_GET['email']);
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
if(!$sql)
die(mysql_error());
mysql_close();
Also sergey is right, you should use mysqli. That's not everything, but enough to get you started.
Why use normal jquery ajax feature. Why not use jquery ajax form plugin, which post the form data by ajax to the form action link.
Check it here:
http://malsup.com/jquery/form/#getting-started
It is very easy to use and support several data formats including json, html xml etc. Checkout the example and you will find it very easy to use.
Thank you
ajax:
$(document).on('click','#mv_secure_page',function(e) {
var data = $("#m_form1").serialize();
$.ajax({
data: data,
type: "post",
url: "adapter.php",
success: function(data){
alert("Data: " + data);
}
});
});
php code:
<?php
/**
* Created by PhpStorm.
* User: Engg Amjad
* Date: 11/9/16
* Time: 1:28 PM
*/
if(isset($_REQUEST)){
include_once('inc/system.php');
$full_name=$_POST['full_name'];
$business_name=$_POST['business_name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$message=$_POST['message'];
$sql="INSERT INTO mars (f_n,b_n,em,p_n,msg) values('$full_name','$business_name','$email','$phone','$message') ";
$sql_result=mysqli_query($con,$sql);
if($sql_result){
echo "inserted successfully";
}else{
echo "Query failed".mysqli_error($con);
}
}
?>
The available answers led to the fact that I entered empty values into the database. I corrected this error by replacing the serialize () function with the following code.
$(document).ready(function(){
// When click the button.
$("#button").click(function() {
// Assigning Variables to Form Fields
var email = $("#email").val();
// Send the form data using the ajax method
$.ajax({
data: "email=" + email,
type: "post",
url: "your_file.php",
success: function(data){
alert("Data Save: " + data);
}
});
});
});
I will tell you steps how you can insert data in ajax using PHP
AJAX Code
<script type="text/javascript">
function insertData() {
var student_name=$("#student_name").val();
var student_roll_no=$("#student_roll_no").val();
var student_class=$("#student_class").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data.php",
data: {student_name:student_name,student_roll_no:student_roll_no,student_class:s
tudent_class},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
PHP Code:
<?php
include('db.php');
$student_name=$_POST['student_name'];
$student_roll_no=$_POST['student_roll_no'];
$student_class=$_POST['student_class'];
$stmt = $DBcon->prepare("INSERT INTO
student(student_name,student_roll_no,student_class)
VALUES(:student_name, :student_roll_no,:student_class)");
$stmt->bindparam(':student_name', $student_name);
$stmt->bindparam(':student_roll_no', $student_roll_no);
$stmt->bindparam(':student_class', $student_class);
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
?>
You can customize it according to your needs. you can also check complete steps of AJAX Insert Data PHP

Ajax won't post form data to PHP script

I got a form with some data that needs to be sent and I want to do it with ajax. I got a function that respond on an onclick event of a button. When I click the button I got some post data in firebug but it just doesn't reach my PHP script. Does anyone know what's wrong?
JS:
function newItem() {
var dataSet = $("#createItem :input").serialize();
confirm(dataSet); //Below this code box is the output of this variable to check whether it is filled or not
var request = $.ajax({
type: "POST",
url: "/earnings.php",
data: dataSet,
dataType: "json"
});
request.done(function(){
$('.create_item').children(".row").slideUp('100', 'swing');
$('.create_item').children("h2").slideUp('100', 'swing');
confirm("succes");
});
request.fail(function(jqXHR, textStatus) {
confirm( "Request failed:" + textStatus );
});
}
dataSet result when the form is completly filled in:
id=123&date=13-09-2013&amount=5&total=6%2C05&customer=HP&invoicenumber=0232159&quarter=1&description=Test
The PHP:
<?php
include('includes/dbconn.php');
function clean_up($string){
$html = htmlspecialchars($string);
$string = mysql_real_escape_string($html);
return $string;
}
if($_POST){
$date = clean_up($_POST['date']);
$amount = clean_up($_POST['amount']);
$total = clean_up($_POST['total']);
$customer = clean_up($_POST['customer']);
$invoicenumber = clean_up($_POST['invoicenumber']);
$quarter = clean_up($_POST['quarter']);
$description = clean_up($_POST['description']);
$sql = ("INSERT INTO earnings (e_date, e_amount, e_total, e_customer, e_invoicenumber, e_quarter, e_description)
VALUES ($date, '$amount', '$total', '$customer', $invoicenumber, $quarter, '$description')");
echo $sql;
if($mysqli->query($sql) === true){
echo("Successfully added");
}else{
echo "<br /> \n" . $mysqli->error;
}
}
?>
The form works fine without the ajax but with it it just doesn't work.
Your help is appreciated!
Try this snippet code bro...
<form id="F_login">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: '/earnings.php',
data: parm,
success: function (data,status,xhr) {
console.info("sukses");
},
error: function (error) {
console.info("Error post : "+error);
}
});
});
Reply me if you try this...
prevent your form submitting and use ajax like this:
<form id="createItem">
<input id="foo"/>
<input id="bar"/>
<input type="submit" value="New Item"/>
</form>
$('#createItem).on("submit",function(e){
e.preventDefault;
newItem();
});
Try this
<input type="text" id="foo"/>
<input type="text" id="bar"/>
<input type="button" id="btnSubmit" value="New Item"/>
<script type="text/javascript">
$(function() {
$("#btnSubmit").click(function(){
try
{
$.post("my php page address",
{
'foo':$("#foo").val().trim(),
'bar':$("#bar").val().trim()
}, function(data){
data=data.trim();
// alert(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>

Display records on load page using jquery ajax in php

I want to load data when page is loaded but if i try doing that then delete function doesn't work and whenever I insert the effect should be seen in table without refreshing page Please check my code what changes to be done in this
index.php
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#Submit").click(function(e) {
var name = $('#name').val();
var message=$('#message').val();
if($(":text").val().length==0)
{
$(":text").after('<span class="error">Field cannot be empty</span>');
$('#name').addClass('error');
$('#message').addClass('error');
return;
}
else{
$('#name').removeClass('error');
$('#message').removeClass('error');
//$('#propspectDiv').removeClass('error');
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');
$.ajax({
url : 'data.php',
data:{
"name" : name,
"message" : message
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
},
complete:function(){
$('#myform').each(function(){
this.reset();
});
}
});
}
});
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
});
</script>
</head>
<body>
<form id="myform">
<div id="wrapper">
Name : <input type="text" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Submit" id="Submit" />
<div id="propspectDiv"></div>
<table id="data" border="1" style="display:none;"></table>
</div>
</form>
</body>
data.php
<?php
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
include('connection.php');
$sql = "INSERT INTO login (username,message) VALUES ('$name','$message')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td id=td1>
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
echo '</tr>';
$i++;
}
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: index.php");
}
?>
Looks like your grabbing the ID attribute of the link, but not setting it...
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
There is no ID attribute on your existing delete link:
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
Also - you probably don't need to have the link href pointing to delete.php as its irrelevant when the jquery click event does all the work.
Also, because you are inserting the html (including the delete method) via jquery you may need to use the "on" event
I'm doing this off the cuff so the code may have some minor bugs but I believe this is the path you want to take...
Revised it might look like this:
JQUERY
$("a").on("click", function(e) {
e.preventDefault();
$.post('delete.php',{ id: $(this).attr("id")});
return false;
});
LINK
echo"<td id=td1>
<a id='".$row['id']."' href='#'>Delete</a>";
echo '</tr>';
couple things to note...
1 - above i'm not actually VERIFYING the record was deleted before I remove the appropriate table row - you may want to implement something to check this
2 - an alternative to removing the table row would be to just update the table in general by repulling the data and outputting it - if you know what i mean

Categories