Passing Data from form with Ajax - php

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.

Related

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.

Complete form submit action without reloading the page

I want the form-data to be sent to my php file after submitting it without loading the php file page. Then the data sent must fade in the feeds after processing. Can anyone help me? Here are my codings:
home.php:
<script>
$(document).ready(function(){
$('#content').load('feeds.php');
}, 1000
);
</script>
feeds.php:
<?php
//after connecting to my database and all
$sql = mysql_query("SELECT * FROM `posts` ORDER BY `post_id` DESC");
while($row = mysql_fetch_assoc($sql)) {
echo '<div id="post">' . $row['post'] . '</div><br />';
}
?>
Here's the form for submitting the post
<form id="post" action="post.php" method="POST">
<textarea name="post" width=300 height=150></textarea>
<input type="submit" value="Post" id="submit">
</form>
post.php:
//after connecting to the database
$post = $_POST['post'];
if($post != '') {
mysql_query("INSERT INTO `posts` (`post`) VALUE('$post')");
}
else {
echo 'Form is empty!';
}
#content:
<div id="content"></div>
nothing else.
Please help me by modifying this code! Thanks in return!
change this from
<form id="post" action="post.php" method="POST">
<textarea name="post" width=300 height=150></textarea>
<input type="submit" value="Post" id="submit">
</form>
to
<form id="form1">
<textarea id="post" width=300 height=150></textarea>
<input type="button" value="Post" id="submit">
</form>
And put this script on javascript area :
$('#submit').click(function(event) {
event.preventDefault(); /* Stops default form submit on click */
var post = $('#post').val();
$.ajax({
url: "post.php?",
data: 'post=' + post,
type: "POST",
success: function(data){
$('#content').empty();
$('#content').load('feeds.php');
}
});
});
I did not test it , but it should be something like this.
Hope this help.
The best solution should be JQuery along with AJAX. Send the data to any page using AJAX and based on the response you can fade the data.
Here is sample implementation:
jQuery(function($){
$("#post").submit(function(){
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(){
alert("data sent");
}
});
return false;
});

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>

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

Getting data from PHP page on form submit

I have index.php with a form. When it gets submitted I want the result from process.php to be displayed inside the result div on index.php. Pretty sure I need some kind of AJAX but I'm not sure...
index.php
<div id="result"></div>
<form action="" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
</form>
process.php
<?php
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
?>
You really don't "need" AJAX for this because you can submit it to itself and include the process file:
index.php
<div id="result">
<?php include('process.php'); ?>
</div>
<form action="index.php" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
<input type="submit" name="submit" value="Submit">
</form>
process.php
<?php
// Check if form was submitted
if(isset($_GET['submit'])){
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
}
?>
Implementing AJAX will make things more user-friendly but it definitely complicates your code. So good luck with whatever route you take!
This is a jquery Ajax example,
<script>
//wait for page load to initialize script
$(document).ready(function(){
//listen for form submission
$('form').on('submit', function(e){
//prevent form from submitting and leaving page
e.preventDefault();
// AJAX goodness!
$.ajax({
type: "GET", //type of submit
cache: false, //important or else you might get wrong data returned to you
url: "process.php", //destination
datatype: "html", //expected data format from process.php
data: $('form').serialize(), //target your form's data and serialize for a POST
success: function(data) { // data is the var which holds the output of your process.php
// locate the div with #result and fill it with returned data from process.php
$('#result').html(data);
}
});
});
});
</script>
this is jquery Ajax example,
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
How about doing this in your index.php:
<div id="result"><?php include "process.php"?></div>
Two ways to do it.
Either use ajax to call your process.php (I'd recommend jQuery -- it's very easy to send ajax calls and do stuff based on the results.) and then use javascript to change the form.
Or have the php code that creates the form be the same php code that form submits to, and then output different things based on if there are get parameters. (Edit: MonkeyZeus gave you specifics on how to do this.)

Categories