Insert record into mysql using json - javascript

I want to insert the record using json into mysql and the system could display the new record without refreshing the page.
My code is shown as below:
Part 1, the script get two values from form and convert it into json, passing them to action.php
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = {'content': textcontent, 'name': name};
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'json',
cache: true,
success: function(html){
$("#show").html(html);
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<input type="submit" value="Add Comment" name="submit" class="submit_button"/>
</form>
</div>
<?php
$host="localhost";
$username="Practical4";
$password="1234";
$db_name="Practical4";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from comment where name='$name'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json[] = $row[1];
}
}
mysql_close($con);
echo implode('<br />', $json);
?>
<div class="space" ></div>
<div id="flash"></div>
<div id="show" ></div>
Part2, action.php, which insert the record into mysql database.
<?php
$DBServer = 'localhost'; // e.g 'localhost' or '192.168.1.100'
$DBUser = 'Practical4';
$DBPass = '1234';
$DBName = 'Practical4';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$v1="'" . $conn->real_escape_string($_POST['content']) . "'";
$v2="'" . $conn->real_escape_string($_POST['name']) . "'";
$sql="INSERT INTO comment (content,name) VALUES ($v1,$v2)";
if($conn->query($sql) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$last_inserted_id = $conn->insert_id;
$affected_rows = $conn->affected_rows;
echo '<div class="showbox">'.$v1.'</div>';
}
?>
So far the code can insert new data, but it won't display the new record dynamically without refreshing page. Any idea to fix that?

Change your dataType to html since this parameter tells the server what kind of response it will accept in return:
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'html',
cache: true,
success: function(data){
$("#show").html(data);
$("#flash").hide();
$("#content").focus();
}
});
In the above case the return value should be plain html:
print '<div class="showbox">' . $v1 . '</div>';
You then add it to your page using:
$('#show').html(data);
If you still would like to use json you could encode your response using something like this:
print json_encode(array('html' => '<div class="showbox">' . $v1 . '</div>'));
Then you would need to parse this value:
$("#show").html(data.html);
In the above example it seems clearer to name the success functions argument to something like data since it won't contain just html in the case.

Related

How to make AJAX request to SQL, and change what's displayed on the DOM?

I have this code to display a user's name:
<div><?php echo 'My name is ' . '<span id="output">' . $_SESSION['firstname'] . '</span>' ?></div>
I'd like to change what's displayed in <span id="output"></span> when a user changes their profile.
This is what I use to change their profile data in the database (shortened to only include what's needed):
<form action="" method="POST">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname">
<button type="submit" name="submit">Submit</button>
</form>
if (isset($_POST['submit'])) {
$username = $_SESSION['username'];
$query = "SELECT * FROM `users` WHERE username='$username'";
$result = mysqli_query($connect, $query) or die(mysqli_error());
$profile = mysqli_fetch_assoc($result);
$update = "UPDATE users SET firstname = '$firstname' WHERE username = '$username'";
$result2 = mysqli_query($connect, $update);
if (mysqli_query($connect, $update)) {
$_SESSION['firstname'] = $firstname;
echo 'Profile updated successfully';
}
}
The thing is, I don't know how to change the "output" to the new $_SESSION['firstname'] without refreshing the page.
I would assume that I'd need to use JQuery's ajax function, but I'm not sure how to specifically use this function to get it done.
A lot of things are wrong with the code. Besides that point here is a simple ajax request.
$('.submit').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'yourscript.php',
data: {firstname: $('#firstname').val()},
success: function(data){
$('#firstname').html(data);
}
});
})
And for PHP:
# 'yourscript.php',
if(isset($firstname = $_POST['firstname'])){
// do your stuff.
echo 'your new data you want to display';
} else {
echo 'something went wrong';
}

How to link my simple jQuery Input with PHP script and Store data into a MYSQL DB?

What I'm trying to do is very simple.
Have a simple input, that allows me to input a name+link, add it to a list and save it to a DB so it's saved.
In my HTML file I currently have:
<form id="form">
<input id="create-input" type="text" placeholder="To do">
<input id="create-link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
In my JS file I have:
$(function(){
$('#submit').on('click', addListItem);
});
function addListItem() {
// Grab Input Data
var text = $('#create-input').val();
var link = $('#create-link').val();
// Creating To Do List
$('#todo').append('<li>' +text+' - '+link+ ' <button class="delete">Edit</button> <button class="delete">Delete</button> <button class="delete">Bukkaked!</button></li>');
$('#create-input').val('');
$('#create-link').val('http://');
}
In my PHP file (connecting to DB) I have:
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
// Check for Success
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Now I know I need to somehow pass the vars (text and link) through to the PHP file:
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
But I have no idea how.
Any tips?
Why do you need JQuery you can pass values using php only
here is a change in your code:-
<form id="form" method="post" action="process.php">
<input id="create-input" name="item" type="text" placeholder="To do">
<input id="create-link" name="link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
<ul>
<?php include('conn.php');
$sql = "SELECT * FROM bucketlist";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li>Item-'. $row["item"].' & Link-'. $row["link"].'</li>';
}
} else {
echo "<li>No List</li>";
}
?>
</ul>
conn.php
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
process.php
<?php
include('conn.php');
$item = $_POST['item'];
$item = $_POST['link'];
$sql = "INSERT INTO bucketlist (item, link) VALUES ($item,$link)";
// Check for Success
if (mysqli_query($conn, $sql)) {
header('location:yourpage.php');
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Hope this helps.
Use ajax to post the values of the item and link in your html form to your PHP script.
Something like :
var myItem = $('#create-input').html();
var myLink = $('#create-link').html();
$.ajax({
type: 'POST',
url: 'https://yoururl/api/post.php',
data: {item:myItem,link:myLink},
success: SuccessCall,
error : FailureCall,
cache:false,
async:true,
dataType: 'html'
});
function SuccessCall(data,status){
alert("response from server is "+data);
}
function FailureCall(data,status){
alert("Server connection error");
}
Use the PHP script posted by SYB to retrieve the values of item and link that were sent from your html form.

How to pass a value to the same page when a form submitted? Using Ajax

Basically, the form has to send data to my database and my database informations should be shown at the same page when user submit the form without refreshing the page. I did something wrong and couldn't find how to fix this. And looked at all the questions but couldn't figure it out. Thanks for the help.
<div id="tweetSpace">
<form id="formTweet" method="post" >
<textarea id="areaTweet" name="message" rows="2" cols="120" placeholder="Write your tweet here..."></textarea>
<br>
<input id="sendTweet" type="submit" value="Send">
</form>
</div>
<div id="txtHint"></div>
<script>
$("#sendTweet").on("submit", function(e){
var tweet = $('areaTweet').val();
var update = $('#txtHint');
$.ajax({
type: 'POST',
url: 'tweet2.php',
data: , tweet,
success:function(html){
update.html(html);
}
});
});
</script>
tweet2.php file
<?php
include 'connect.php';
session_start();
$tweet=$_POST['tweet'];
$email =$_SESSION['login_user'];
$sqlr = "INSERT INTO tweets(tweet,member_email) VALUES ('$tweet','$email')";
$rqu = mysqli_query($conn,$sqlr);
$x=0;
$arrayName = array();
$sql= "SELECT tweet FROM tweets WHERE member_email= '$email' "
$rq = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($rq)) {
$arrayName[$x] = $row["tweet"];
$x=$x+1;
}
<?php for($k = 0; $k < $x; $k++) {?>
<p><?php echo $arrayName[$k]; ?></p>
<?php } ?
?>
Here is the working code...Note all changes did in 2 files..
HTML
<html>
<head>
<title>Tweets</title>
</head>
<body>
<div id="tweetSpace">
<form id="formTweet" method="post" >
<textarea id="areaTweet" name="message" rows="2" cols="120" placeholder="Write your tweet here..."></textarea>
<br>
<input id="sendTweet" type="button" value="Send">
</form>
</div>
<div id="txtHint"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$("#sendTweet").click(function(e){
var tweet = $('#areaTweet').val();
var update = $('#txtHint');
$.ajax({
type: 'POST',
data: {'tweet':tweet},
url: 'tweet2.php',
success:function(html){
update.html(html);
}
});
});
</script>
</body>
</html>
tweet2.php
<?php
session_start();
include 'connect.php';
/*
$servername = "localhost";
$username = "root";
$password = "";
$db = "sflow";
$conn = mysqli_connect($servername, $username, $password, $db);
*/
$tweet = $_POST['tweet'];
$email = /*"sample#s.com";//*/$_SESSION['login_user'];
$sqlr = "INSERT INTO tweets(tweet,member_email) VALUES ('$tweet','$email')";
$rqu = mysqli_query($conn,$sqlr);
$x=0;
$arrayName = array();
$sql= "SELECT tweet FROM tweets WHERE member_email= '$email'";
$rq = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($rq)) {
$arrayName[$x] = $row["tweet"];
$x=$x+1;
}
for($k = 0; $k < $x; $k++)
echo '<p>'.$arrayName[$k].'</p>';
?>
Sample Table
CREATE TABLE IF NOT EXISTS `tweets` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`tweet` varchar(255) NOT NULL,
`member_email` varchar(255) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `sid_2` (`tweet`),
KEY `sid` (`tweet`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `tweets`
--
INSERT INTO `tweets` (`ID`, `tweet`, `member_email`) VALUES
(1, 'sasa', 's#g.com'),
(2, 'fgfg', 'sample#s.com');
is that an extra comma in your ajax before tweet? data: , tweet,
if so it wont work. should be data: tweet,
You don't want to refresh page ,so must use preventDefault but its only work with form id .So need to change submit button id with form id .Second thing is your data format function must like json {key : value}
$("#formTweet").on("submit", function(e){
e.preventDefault(); //prevent refresh page
var tweet = $('#areaTweet').val();
var update = $('#txtHint');
$.ajax({
type: 'POST',
url: 'tweet2.php',
data: {tweet:tweet},
success:function(html){
update.html(html);
}
});
});
I think you need to modify your tweet2.php
<?php
include 'connect.php';
session_start();
$tweet=$_POST['tweet'];
$email =$_SESSION['login_user'];
$sqlr = "INSERT INTO tweets(tweet,member_email) VALUES ('$tweet','$email')";
$rqu = mysqli_query($conn,$sqlr);
$sql= "SELECT tweet FROM tweets WHERE member_email= '$email' ";
$rq = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($rq)) {
echo "<p>".$row["tweet"]."</p>";
}
?>
Make sure to set exit(); at the end of tweet2.php file. Then only you will able to get response back. Moreover, You should define data in the form of data: {tweet:tweet} format. tweet Variable will go with the ajax to your php file.
$("#sendTweet").on("submit", function(e){
var tweet = $('areaTweet').val();
var update = $('#txtHint');
$.ajax({
type: 'POST',
url: 'tweet2.php',
data: {tweet:tweet},
success:function(html){
update.html(html);
}
});
});
UPDATED
Instead of this
var tweet = $('areaTweet').val();
use
var tweet = $('#areaTweet').val();

File and text upload from php page using ajax and store in mysql

Hi i'm currently developing a php page which has an file upload feature. my form sends over 2 hidden values which is an order id and sender id and the file. I have to use ajax as i can't make it refresh after upload. The file upload has to be in my upload/files folder and i need to store the order id , sender id and filename in mysql.My ajax is getting the order id and sender id when i serialize but not the file. i tried seraching on this site for solutions and came acrross FormData object way to no success and also few other methods. the error in my console is always undefined sender_id, file order_id. It doesnt get the values from the html form. Thanks for helping.
MY php, html form
<form method="POST " id="form1" name="form1" enctype='multipart/form-data' >
<input type="hidden" name="sender_id" value="<?php echo $_SESSION['user_session']?>">
<input type="hidden" name="order_id" value="<?php echo $_GET['oid']?>">
<?php //echo var_dump($sellerinfo);?>
<div>
<div>
<textarea name="comments" placeholder="Leave Comments Here..." style="width:800px; height:100px;"></textarea>
<div class="row">
<input type="file" id="file" name="fileupload">
<input type="reset" value="Reset">
<a type="file" href="" class="button" id="fileupload" name="fileupload"> UPLOAD FILE </a>
<br>
<a id="comment" href="" class="button">Post</a>
<input type="reset" value="Reset">
</form>
File.js (ajax file)
$("#fileupload").click(function(e){
alert("inside ajax");
var formData = $("#form1").serialize()
alert(formData);
var formData = new FormData();
var file_data = $('#file').prop('files')[0];
formData.append('file', file_data);
alert(formData);
$.ajax({
url: '../modules/Comment/fileupload.php',
type: 'POST',
dataType:"json",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
error: function (result) {
console.log(result);
alert('ERROR RUNNING INSERTSCRIPT');
},
success: function (result) {
alert(result)
if (result['result'] == true) {
alert("success");
order_id = document.form1.order_id.value;
$('#comment_logs').load("../modules/comment/file_logs.php?",{oid:order_id} );
}
else if (result['result'] == false) {
alert('ERROR');
}
},
});
});
My php script that is supposed to upload and insert data inside database.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
require('commentclass.php');
$connect = new connect(); // new connect class OBJECT
$conn = $connect->get_connection(); // getting Connection from Connect Object
$sender_id=$_POST['sender_id'];
$order_id=$_POST['order_id'];
$Filename=basename( $_FILES['Filename']['name']);
define ('SITE_ROOT', realpath(dirname(__FILE__)));
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], '../../uploads/files/' . $_FILES['file']['name'])) ;
{
echo "The file " . basename($_FILES['Filename']['name']) . " has been uploaded, and your information has been added to the directory";
$sql = "INSERT INTO files(order_id,send_by,file_name) VALUES ('" . $order_id . "','" . $sender_id . "','" . $Filename . "')";
$result = mysqli_query($conn, $sql);
$data = array();
if ($result) {
$data['result'] = true;
echo json_encode($data);
}
else
{
$data['result'] = true;
echo json_encode($data);
}
}
}
?>
Sorry for the long post, hope someone can help . Thanks in advance

My pdo ajax code for search is not working

What I want to do is: when a user types their email, my ajax code will run and show the user pass in the password inputbox.
The problem is that while my ajax code is sending the email to search.php, my search.php isn't giving the data to my ajax to show.
I think the problem is in my search.php because when i go to search.php after i type an email in my index the search.php is just blank no data is showing.
Index (Form):
email <input type="text" id="query" name="myemail" class="search_textbox" /><br />
Your Password <input type="text" id="mypass" name="mypass" readonly="readonly" /><br />
<script>
$(document).ready(function(){
$('.search_textbox').on('blur', function(){
$('#query').change(updateTextboxes);
updateTextboxes()
})
$('.search_textbox').on('keydown', function(){
$('#query').change(updateTextboxes);
updateTextboxes()
})
$('#query').change(updateTextboxes);
var $mypass = $('#mypass');
function updateTextboxes(){
$.ajax({
url:"search.php",
type:"GET",
data: { term : $('#query').val() },
dataType:"JSON",
success: function(result) {
var ii = 1;
for (var i = 0; i < result.length; i++) {
$mypass.val(result[i].value).show().trigger('input');
ii++;
}
}
});
};
});
</script>
search.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_GET['term'])) {
$q = $_GET['term'];
$sql = "SELECT password FROM students WHERE email = :term";
$query = $dbc->prepare($sql);
$query->bindParam(':term', $q);
$results = $query->execute();
$data = array();
while ($row = $results->fetch()) {
$data[] = array(
'value' => $row['password']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
I noticed header('Content-type: application/json');. I don't think it is necessary. Remove the line and try again. I am not sure but I think php header is needed for a new page. Since you have echo json_encode($data); and in your AJAX call, you are already processing the return data as json, the header(...) is not needed.
EDIT
$q = $_GET['term'];
$sql = "SELECT password FROM students WHERE email = :term";
$query = $dbc->prepare($sql);
$query->bindParam(':term', $q);
if($query->execute() && $query->rowCount()){
echo json_encode($query->fetch(PDO::FETCH_ASSOC));
}
SCRIPT
function updateTextboxes(){
$.ajax({
url:"search.php",
type:"GET",
data: { term : $('#query').val() },
dataType:"JSON",
success: function(result) {
//check here if you have a result, if yes than...
$("#mypass").val(result.password);
}
}

Categories