Insert data through ajax into mysql database - php

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

Related

Displaying a success message after form submission

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

Using jquery ajax to serialize data and submit into mysql database

The problem i have is that whenever it inserts the data into the database it doesn't redirect the user to the invoice.php page. Please guys i really need your help.
This is the html code:
<form method="POST" action="">
<input type="text" name="resident_address" id="resident_address"/>
<input type="text" name="price" id="status"/>
<input type="hidden" name="status" id="status" value="0"/>
</form>
This is the jquery code:
var dataString = $('#applyform').serialize();
$.ajax({
type: "POST",
url: "applyform.php",
cache: false,
data: dataString,
beforeSend: function()
{
$(".apply_error").hide();
},
success: function(html) {
if (html == "true")
{
// You can redirect to other page here....
window.location.href = 'invoice.php';
}
else
{
//window.location.href = 'apply.php';
$("div.apply_error").html("Wrong details").show();
}
}
});
this is the php which is the applyform.php:
if(isset($_POST['Submit']))
{
$result = mysql_query("INSERT INTO mytable (resident_address, price, status) VALUES ('$addressfields', '$price', '$status')");
if($result){
echo "true";
}
}
you are not posting a POST var called "Submit" so your
if(isset($_POST['Submit']))
will always evaluate to false and your mysql query is never executed.

how to insert value in database using php, jquery and ajax

I am struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...this is a msg.php page when i have submit data sometimes post submit in database`
mostly not so i want to know that why it s happening i am new in this field
<?
php $id=$_GET['id'];
$id1=$_SESSION['id'];
?>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="<?php echo $id1;?>" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" onClick="sendChat()">
</div>
</form>
function sendChat()
{
$.ajax({
type: "POST",
url: "msg_save.php",
data: {
senderid:$('#senderid').val(),
rcvrid:$('#rcvrid').val(),
msg: $('#msg').val(),
},
dataType: "json",
success: function(data){
},
});
}
msg_save.php file
<?php
require_once('include/util.php');
$rcvrid=$_POST['rcvrid'];
$senderid=$_POST['senderid'];
$msg=$_POST['msg'];
$sql="insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysql_query($sql);
?>
$.ajax({
type: "POST",
url: "msg_save.php",
data: " senderid="+$('#senderid').val()+"rcvrid="+$('#rcvrid').val()+"msg="+$('#msg').val(),
dataType: "json",
success: function(data){
},
});
please try this code and send data ,and use post method in php to get data,it will work
if you are trying chat application check this, it is old but just for idea:
http://www.codeproject.com/Articles/649771/Chat-Application-in-PHP
use mysqli_query instead of mysql_query recommended
<?php
$id=$_GET['id'];
//$id1=$_SESSION['id']; COMMENTED THIS AS I AM NOT IN SESSION. HARDCODED IT IN THE FORM AS VALUE 5
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="5" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" >
</div>
</form>
<script>
$("#msgfrm").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "msg_save.php",
data: $(this).serialize(),
success: function(data) {
$("#chatbox").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
</body>
</html>
msg_save.php
<?php
//require_once('include/util.php');
$rcvrid = $_POST['rcvrid'];
$senderid = $_POST['senderid'];
$msg = $_POST['msg'];
echo $rcvrid.$senderid.$msg;
$con = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysqli_query($con,$sql);
mysqli_close($con);
echo "successful"
?>
check that whether you have inserted jquery file or not.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Then include your function sendChat() inside <script> tags.
On submit button
<button type="submit" id="button">SAVE</button>
<script>
$(document).ready(function(){
$("#button").click(function(){
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
$.ajax({
url:'dbConfigAndInsertionQuery.php',
method:'POST',
data:{
firstname:firstname,
lastname:lastname,
email:email
},
success:function(data){
alert(data);
}
});
});
});
</script>

ajax update to database

I am trying to add data to a database and for some reason it does not always work. I'd say 80% of the time it will work and I'll see the result in the database but sometimes its like the script won't run.
here is the ajax :
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('.error').hide();
$("#success").hide();
$(".button").click(function () {
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: $("input#name"),
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
});
});
});
});
</script>
here is the html:
<div id = "contact_form">
<form name ="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="send" />
</fieldset>
<span id="success"> the name has been updated successfully!</span>
</form>
</div>
<div id ="upd"></div>
and here is the proccess.php file:
<?php
$va = $_POST["name"];
$dbconnection = mysql_connect('adatabase','someuser','somepw');
if(!mysql_select_db('some_database', $dbconnection)) {
echo mysql_error();
}
else
{
echo 'connection success';
}
$sql = "INSERT INTO some_db(text) VALUES ('$va')";
$result = mysql_query($sql) or die('erreur sql!'.mysql_error());
if(!$result) {
echo "not working";
}
else {
echo "working";
}
?>
so how come it does not always insert into the database?
and is there a way to get the result from the php if(!$result) to show in the success part of the ajax?
You're actually passing a jQuery-Object to your PHP-File.
$.post("class/proccess.php", {
name: $("input#name").val() //Pass val() not the whole jQuery-Object!
}, function() {
/* success */
});
While you're debugging, make sure MySQL errors are enabled.
In your Javascript for the Ajax success handler, show an alert with the text returned from the call. That way if there's an error with MySQL you'll see it.
Another thing is, could the "text" field be set in the database as UNIQUE? Trying to insert a new record with a duplicate string would fail in that case.
And... the name of the field isn't really 'text' is it? I would recommend avoiding field names that are the same as the basic data types for MySQL. Just to avoid confusion if no other reason.
If it is not working sometimes, you need to check the returned string for errors. The right way to do this using AJAX is as follows.
You can include a parameter in your success callback which will fetch the page-result from the PHP.
Instead of
success: function () {
...
}
use
success: function (data) {
alert(data);
}
Change your ajax call to:
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: {name : $("input#name").val()},
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
So that $_POST['name'] is set to the value of your input box.
Also, as suggested, you should change your mysql functions to mysqli functions to help protect against sql injections.

Passing Data from form with Ajax

Wondering if someone could help me. I have next to no knowledge with Ajax, and after many attempts at trying to pass my User1_id and Text through to my insert.php I've had no luck with inserting the data I want to my database.
As my profile.php and insert.php stands, the form submits to the database, but when the user submits the form it navigates to the insert.php and would rather have the Ajax send the data and stay on the Profile.php at all times, I feel this is a much better approach when creating such functions.
I'm wondering if someone can guide me in the right direction on how I'd go about doing this.
Profile.php Form
<form id="FormId" action="" method="get">
<input type="hidden" value="<? echo $user1_id ?>">
<textarea placeholder="Whats New??" id="FormId" name="status"></textarea>
<input type="submit" name="Submit" value="Submit">
</form>
Insert.php
<?
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
include "db_connect.php";
if (isset($_GET['status'])) {
$status = $_GET['status'];
}
$user1_id=$_SESSION['id'];
if ($_GET['status']) {
$query = mysql_query("INSERT INTO feed (status,user1_id) VALUES ('$status', '$user1_id')") or die (mysql_error());
if($query){
echo "Posted Into Database";
}
exit();
}
?>
I know I need something similiar to this.. But I think I'm stuck more on the var/data part.
$("form#myFormId").submit(function() {
var mydata = $("form#myFormId").serialize();
alert(mydata); // it's only for test
$.ajax({
type: "GET",
url: "insert.php",
data: mydata,
success: function(response, textStatus, xhr) {
alert("success");
},
error: function(xhr, textStatus, errorThrown) {
alert("error");
}
});
return false;
});
But don't know how to go about it.
Any guidence is appreciated. Not asking anyone to write the code out for me. But good direction is welcomed.
Thanks.
Change your ajax part to:
$("form#myFormId").submit(function(e) {
e.preventDefault(); //prevent default submit
........
Your hidden input should have name
<input name="userId" type="hidden" value="<? echo $user1_id ?>">
And in php,
$userId = $_GET["userId"];
Change id of textarea, its same to your formid and ids need to be unique,
so change your textarea id, and You can try passing data as:
$.ajax({
type: "GET",
url: "insert.php",
data:"status="+$("#yourTextareaId").val()+"&userId="+$("#yourHiddenInputId").val(),
......
Just like to say thank you to both of you for your time and help. I re-wrote the code and have now got it working.
Here is the final code
PROFILE.PHP/JS
<script type="text/javascript">
function createstatus(content){
$.post("insert.php", { user1_id: content } );
refreshstream();
}
function createwallpost(content,user1_id){
$.ajax({
type: "POST",
url: "insert.php",
data: "status="+content+"&user1_id="+user1_id,
success: function(){
document.location = document.location;
}
});
}
</script>
<form action="insert.php" method="POST" target="ifr1" class="form_statusinput">
<input type="hidden" name="user1_id" value="<?php echo $user1_id ?>">
<input type="text" name="status" id="status" class="homescreen_status_input" placeholder="Say something">
<iframe name="ifr1" id="ifr1" style="display:none;"></iframe>
</form>
INSERT.PHP
<?
session_start();
include "db_connect.php";
if (isset($_POST['status'])) {
$status = $_POST['status'];
}
$user1_id = $_POST['user1_id'];
if ($_POST['status']) {
$query = mysql_query("INSERT INTO feed (status,user1_id) VALUES ('$status', '$user1_id')") or die (mysql_error());
if($query){
echo "Posted Into Database";
}
exit();
}
?>
I decided to go with post instead of the GET method, as I feel its securer and passes more information through smoothly.
Thanks again.

Categories