Update data function is not updating value in database - javascript

I have created get_data(id) and update_data() function in item.js file and corresponding get_data.php and update_data.php files. In my code get_data(id) function is working perfectly but update_data()is not updating the value in database. It seems like function is not calling update_data.php. I've tried implementing ajax and php for the first time, Please help me to figure out the exact problem in my code. Here is my code
function loadItem(id) {
console.log(id);
$.ajax({
url: "get_data.php",
type: "POST",
data: {'id': id},
success: function (result) {
console.log(result);
var d = JSON.parse(result);
document.getElementById("ib_id").value = d.category[0].ic_id;
document.getElementById("ib_name").value = d.category[0].ic_name;
}
});
}
function updateItem() {
var id = document.getElementById("ib_id").value;
var name = document.getElementById("ib_name").value;
$.ajax({
url: "update_data.php",
type: "POST",
data: {'id': id, 'name': name},
success: function (result) {
console.log(result);
}
});
}
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<h1>Test Page</h1>
<button onclick="loadItem(2);">Load Data</button>
<br/>
<br/>
<br/>
<br/>
<form method="post">
<input type="text" name="ib_id" id="ib_id" class="form-control"
placeholder="id etc." required/>
<input type="text" name="ib_name" id="ib_name" value="" class="form-control"
placeholder="i.e HP, Dell, Sony etc." required/>
<br/> <button onclick="updateItem();">Update Data </button>
</form>
<script type="text/javascript" src="assets/js/jquery.min.js">
</script>
<script type="text/javascript" src="assets/js/item.js"></script>
</body>
</html>
get_data.php
<?php
include 'connection.php';
$id=$_POST["id"];
$category = array();
$temp = array();
$query = mysqli_query($link, "SELECT * FROM item_category WHERE ic_id = ".$id);
//$query = mysqli_query($link, "SELECT * FROM item_category");
while ($row = mysqli_fetch_array($query)) {
$temp['ic_id'] = $row['ic_id'];
$temp['ic_name'] = $row['ic_name'];
array_push($category, $temp);
}
$response['category'] = $category;
echo json_encode($response);
?>
update_data.php
<?php
include 'connection.php';
$id=$_POST['id'];
echo "id is".$id;
$name=$_POST['name'];
$query = mysqli_query($link, "UPDATE item_category SET ic_name = '$name' WHERE ic_id = ".$id);
echo "updated";
?>

Related

How can I insert an Ajax result into an input value?

How can I insert an Ajax result into an input value?
HTML/PHP
<select id="getcategory" name='categoryname' ><option>SELECT---</option>
<?php
$getcat = mysqli_query($con,"SELECT * FROM category ORDER BY categoryname ASC");
while($rec = mysqli_fetch_assoc($getcat)) { ?>
<option><?php echo $rec['categoryname']; ?></option><?php } ?>
</select><br>
<input class='categoryprefix' type='text' name='subcatprefix' />
Ajax
<script type="text/javascript">
$(document).ready(function(){
$("#getcategory").change(function(){
var cprefix = $(this).val();
$.ajax({
url: 'getCategory.php',
type: 'post',
data: {categoryname: cprefix},
success: function(data) {
$(".categoryprefix").append(data);
}
});
});
});
</script>
Note:
File getCategory.php is good

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();

Insert record into mysql using json

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.

Cant make live ajax search work

I'm new to web development sorry but i just don't get problem
I just created this and its not working. please help i don't know whats the problem. i'm not getting any results.
but if i go to search.php it displays all names.
HTML
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<input type="text" onKeyup="getName(this.value)"/><br>
<div id="result"></div>
<script type="text/javascript">
function getName(value){
$.post("search.php", {partialName:value}, function(data){
$("#result").html(data);
});
}
</script>
php(search.php)
<?php
require 'includes/connection.php';
$partialName = $_POST['partialName'];
$query = "SELECT Name FROM Members WHERE Name LIKE '%$partialName%'";
$names = mysqli_query($dbc, $query);
while($namesArray = mysqli_fetch_array($names)){
echo "<div>".$namesArray['Name']."</div>";
}
?>
HTML:
<input type="text" id="search"/><br>
JS:
$("#search").on("keyup", function()
{
var value = $(this).val();
$.ajax({
url: "search.php",
type: "POST",
data: "partialName="+value,
success: function(data)
{
$("#result").html(data);
}
});
});
EDIT: Just as a note, it might be worth escaping the input into your MySQL query:
$partialName = mysqli_real_escape_string( $_POST['partialName'] );
<input type="text" id="search" /><br>
<div id="result"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search').keyup(function(){
var name = $('#search').val();
var datastring = "partialName="+name;
$.ajax({
url: "search.php",
type: "POST",
data: datastring,
success: function(data)
{
$("#result").html(data);
}
});
});
});
</script>
<?php
require 'includes/connection.php';
$partialName = $_POST['partialName'];
$query = "SELECT Name FROM Members WHERE Name LIKE '%".$partialName."%' ";
$names = mysqli_query($dbc, $query);
while($namesArray = mysqli_fetch_array($names)){
echo "<div>".$namesArray['Name']."</div>";
}
?>

load a php query file in an html index page using ajax or jquery

index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="my.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "query.php",
data: data,
beforeSend: function(html) { // this happens before actual
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html)
{ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
$(document).ready(function{
$.ajax({
url: "query.php"
}).done(function(data) {
$('body').html(data);
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "query.php",
dataType: "text",
data: dataString,
success: function (response)
{
alert(response); //alert responce from query.php
},
error:function (xhr, ajaxOptions, thrownError)
{
alert(xhr);
}
});
});
</script>
</head>
<body >
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="query.php" >
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults"></div>
<ul id="results" class="update">
</ul>
</div>
</div>
</body>
</html>
query.php
<?php
$user_name = "root";
$password = "";
$database = "my_db2";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM user WHERE Hometown = 'Quahog'";
//searching for what was entered into the search box
if (isset($_POST['search']))
{
$search_term = mysql_real_escape_string($_POST['search']);
//concatenating the $SQL variable above
$SQL .= "AND id = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND FirstName = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND LastName = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND Age = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND Job = '{$search_term}'";
}
$result = mysql_query($SQL) or die(mysql_error());
?>
<html>
</head>
<body>
<h1> Persons</h1>
<table border = "1" width = "100%" cellpadding = "5" cellspacing = "2">
<tr>
<td><strong>ID</strong></td>
<td><strong>First Name</strong></td>
<td><strong>Last Name</strong></td>
<td><strong>Age</strong></td>
<td><strong>Hometown</strong></td>
<td><strong>Job</strong></td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['FirstName']; ?></td>
<td><?php echo $row['LastName']; ?></td>
<td><?php echo $row['Age']; ?></td>
<td><?php echo $row['Hometown']; ?></td>
<td><?php echo $row['Job']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
I am new to javascript, jquery and ajax and I would like some help on modifying the above code so that when the page loads, I can view the results of a php/mysql query named 'query.php' into the index file of my html page.
Any help will be greatly appreciated.
$(document).ready(function() {
jQuery.ajax({
type: "POST", // this is post request u can also do get request
url: "query.php",
dataType: "text",
success: function (response) // this is the response from url: "query.php",
{
alert(response); //alert responce from query.php and here you can do
// whatever u like with response.
},
error:function (xhr, ajaxOptions, thrownError)
{
alert(xhr); // if any error function.
}
});
});
Use AJAX in yout index.html like this:
$(document).ready(function{
$.ajax({
url: "query.php"
}).done(function(data) {
$('body').html(data);
});
});
More info on AJAX.
Make sure that you have included jQuery in your code.

Categories