Index page comments not inserting into database using AJAX - php

I'm trying to insert a comment into a database but I keep getting an Object object alert whenever trying to submit it and it never makes it to the database. The files are all in the same folder.
Any help is appreciated, thanks in advance.
index.php
<?php require_once('include/header.php'); require_once('include/browser.php'); ?>
<div class="content">
<section>
<div class="article">
<?php
$userNameQuery = "SELECT * FROM (SELECT * FROM `tbl_posts` ORDER BY 'post_id' DESC)
t ORDER BY `post_id` DESC
LIMIT 3";
$result = mysqli_query($connection, $userNameQuery)
or die("Error in query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result)){
$post_id = $row ['post_id'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['post_title']; ?></h1>
</div>
<div class="textcontainer">
<?php echo $row['post_content']?>
</div>
<?php
if (!empty($row['imagePath'])) //This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="<?php echo $row['imagePath']; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['post_timestamp']; ?>
<b>Author :</b> Admin
</div>
<?php
//Selecting comments which correspond to the post
$selectCommentQuery = "SELECT * FROM `tbl_comments`
LEFT JOIN `tbl_users`
ON tbl_comments.tbl_comments_users_id = tbl_users.id
WHERE tbl_comments.tbl_comments_post_id ='$post_id'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
//showing the comments
echo '<div class="comment-block_' . $post_id .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Comment by: <?php echo $commentRow['username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['comment_content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['comment_timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['cleanUsername']) )
{
?>
<form method="POST" class="post-form" action="index.php" >
<label>New Comment</label>
<textarea name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $post_id ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once('include/footer.php'); ?>
comments.js
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('.comment',form);
if (comment.val().length > 1)
{
$.ajax({
url: 'postComments.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data so we can enter into database
beforeSend: function(){
//Changing submit button value text and disabling it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Please fill the field!");
}
});
});
postComments.php
<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
session_start();
require_once('ajaxconnection.php');
$connection2 = connectToMySQL();
$userId = $_SESSION['userID'];
$username = $_SESSION['cleanUsername'];
$comment = $_POST['comment'];
$postId = $_POST['post_id'];
$date_format = " Y-m-d g : i : s";
$time = date ($date_format);
$insertCommentQuery = "INSERT INTO `tbl_comments`
(`comment_content`,`tbl_comments_users_id`,`tbl_comments_post_id`)
VALUES ('$comment', $userId, $postId)";
$result = mysqli_query($connection,$insertCommentQuery);
$obj = array();
$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
<div class="commentusername"><h1> Username :'.$username.'</h1></div>
<div class="commentcontent">'.$comment.'</div>
<div class="commenttimestamp">'.$time.'</div>
</div>';
echo json_encode($obj);
connectToMySQL(0);
endif?>
ajaxconnection.php
<?php
function connectToMySQL()
{
$connection2 = mysqli_connect("localhost","root","","ascaniobajada2ed8s")
or die('Error connecting to the database');
return $connection2;
}
?>

JQuery .Ajax returns error like this (jqXHR, textStatus, errorThrown). So use it like this to see the real error and not just object object
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}

Related

Select results from live search ajax

I am new to this so an early sorry if my question useless... :) I want to be able to click on a result of a search output (the same as a dropdown menu except it's with a search bar) I have looked on internet but nothing could interest me. Thank you. PS: the connection of my database is in an other code but that shouldn't be useful.
Here is my code so far :
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche" class="search" onkeypress="showdiv()">
</div>
<div class="resultat" id="resultat" id="resultat" style="display: none;">
<a>Please continue typing...</a>
<br>
<br>
<br>
<br>
</div>
<script type="text/javascript">
function showdiv() {
document.getElementById("resultat").style.display = "block";
}
</script>
PHP:
<?php
include 'connect.php';
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$sql = "SELECT name FROM smartphone WHERE name LIKE '%" . $motclef . "%' LIMIT 5";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
} else {
echo "Aucun resultat trouvé pour: " . $motclef;
}
}
?>
jQuery:
$(document).ready(function(){
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#recherche').keyup(function() {
delay(function(){
var recherche = $('#recherche').val();
if (recherche.length > 1) {
$("#resultat").html("");
$.get( "fetch.php", { motclef: recherche} )
.done(function( data ) {
$("#resultat").html(data);
});
}
}, 1000 );
});
});
First-page.php
<?php
global $wpdb;
$supplier_prod_table=$wpdb->prefix.'supplier_product_post';
$sup_query=$wpdb->get_results("SELECT * FROM $supplier_prod_table");
$supp_name_chek=$user_info->user_login;
?>
<div class="form-group">
<input name="keysearch" value="<?php if($supp_name_chek!='') { echo $supp_name_chek; }?>" placeholder="name" id="keysearch" type="text" class="form-control">
<input type="hidden" value="" id="supplier_id">
<span id="loading">Loading...</span> </div>
db page
if(isset($_POST['keysearch']))
{
include('../../../../wp-load.php');
global $wpdb;
$search = $_POST['search'];
$table_name= $wpdb->prefix.'users';
$data = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `user_nicename` like '%$search%' OR `display_name` like '%$search%'");
foreach($data as $key)
{
$user_id=$key->ID;
$user = new WP_User( $user_id );
$role=$user->roles[0];
if($role=='supplier'){
$username = $key->user_login;
?>
<div class="search_show" align="left" id="<?php echo $user_id ?>"><?php echo $username; ?></div>
<?php
// echo "<div class='show' onclick='select_supp()'>".$username."</div>";
}
}
}
JS Code
jQuery(document).ready(function(){
jQuery('#keysearch').on('keyup', function(){
var ajax_search_url=search_url;
var key = jQuery('#keysearch').val();
if (key && key.length > 2)
{
jQuery('#loading').css('display', 'block');
jQuery.ajax({
url : ajax_search_url,
type : 'POST',
cache : false,
data : {
keysearch : key,
},
success : function(data)
{
console.log(data)
if (data)
{
jQuery('#loading').css('display', 'none');
jQuery("#search_result").html(data).show();
}
jQuery('#search_result .search_show').click(function() {
var text = jQuery(this).text();
var sid = jQuery(this).attr('id');
jQuery('#keysearch').val(text)
jQuery('#supplier_id').val(sid);
jQuery('#search_result').fadeOut(1000);
});
}
});
}
else
{
jQuery('#loading').css('display', 'none');
jQuery('#search_result').css('display', 'none');
}
});
});

unexpected end of input php jQuery

I have written same code at one machine and it is working fine but on other machine same code is giving error unexpected end of input. This is driving me crazy as why it is happening. Anybody who can help, please. These are my files with which I am working.
edit: I am making a small online test application for learning purpose. As the test start, the first question appears, on clicking next button the url changes to what it should be but next question does not appear and the error in the console says unexpected end of input. Since all my brackets are ok, I am not able to find error. Please help!!
TestStart.php
<?php
session_start();
if(isset($_SESSION['TestId']))
{
$TestId = $_SESSION['TestId'];
}
include('Config.php');
include('Reference.php');
$query = "select * from testquestions where testid='".$TestId."'";
$res = mysql_query($query);
if(mysql_num_rows($res) > 0)
{
$z = array();
while($fetch = mysql_fetch_array($res))
{
$z[]=$fetch['QId'];
}
$y = implode(",", $z);
$_SESSION['QIds']=$z;
}
else{
echo mysql_error();
}
?>
<body>
<div class="container">
<div class="row">
<div class="col-md-12" id="resultDiv">
<div class="col-md-12" id="qtext"></div>
<div class="col-md-12">
<div class="col-md-3">
<div class="col-md-12">
<input type="radio" id="optionA"name="options" value="A"><span id="optA"></span>
</div>
<div class="col-md-12">
<input type="radio" id="optionB" name="options" Value="B"><span id="optB"></span>
</div>
</div>
<div class="col-md-3">
<div class="col-md-12">
<input type="radio" id="optionC" name="options" value="C"><span id="optC"></span>
</div>
<div class="col-md-12">
<input type="radio" id="optionD" name="options" value="D"><span id="optD"></span>
</div>
</div>
</div>
<div id="nextbuttondiv"></div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
<?php
if(isset($_GET['qno'])&&isset($_GET['qindex']))
{
$qno = $_GET['qno'];
$qindex = $_GET['qindex'];
}
else{
$qno = '1';
$qindex = '0';
}
?>
var qno = <?php echo $qno;?>;
var qindex = <?php echo $qindex;?>;
var qidsarrCm = '<?php echo $y;?>';
var arrQid = qidsarrCm.split(",");
var totalQuestions = arrQid.length;
$.ajax({
type : "post",
url : "GetQuestionForTest.php",
data : {
"quId" : arrQid[qindex]
},
dataType : "json",
success : function(data){
alert('xy');
console.log(data);
$.each(data, function(){
var qText = this.questiontext;
var optionA = this.OptionA;
var optionB = this.OptionB;
var optionC = this.OptionC;
var optionD = this.OptionD;
var nxtBtn = this.NextButton;
$('#qtext').text(qText);
$('#optA').text(optionA);
$('#optB').text(optionB);
$('#optC').text(optionC);
$('#optD').text(optionD);
$('#nextbuttondiv').html(nxtBtn);
});
},
error: function(data, statusCode, xhr){
alert(statusCode);
console.log(data);
console.log(xhr);
}
});
$('input[type=radio]').on('click',function(){
$('.nxtbtn').removeAttr('disabled');
});
$('body').on('click','.nxtbtn', function(){
$.ajax({
type : "post",
url : "SaveTestAnswers.php",
data : {
"qid" : arrQid[qindex],
"ansId" : $('input[name=options]:checked').val(),
"stuId" : <?php echo $_SESSION['CurrentUser'];?>,
"testId" : <?php echo $TestId;?>
},
dataType : "json",
success : function(data){
if(data.toString() == "true"){
qindex = qindex + 1;
qno = qno + 1;
if(qno > totalQuestions){
window.location.href="TestFinish.php";
}
else{
window.location.href="TestStart.php?qno="+qno+"&qindex="+qindex;
}
}
else{
alert(data + "Please resubmit the answer");
}
},
error : function(data, statusCode, xhr){
alert(statusCode);
console.log(data);
console.log(xhr);
}
});
});
});
</script>
</body>
GetQuestionForTest.php
<?php
$questionid = $_POST['quId'];
include('Config.php');
$query = "select * from questionstable where questionid = '".$questionid."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
$someArray = [];
while($fetch = mysql_fetch_array($result))
{
array_push($someArray,[
'questiontext' => $fetch['questiontext'],
'OptionA' => $fetch['optionA'],
'OptionB' => $fetch['optionB'],
'OptionC' => $fetch['optionC'],
'OptionD' => $fetch['optionD'],
'NextButton' => '<button class="btn btn-success nxtbtn" disabled >Next</button>'
]);
}
$someJSON = json_encode($someArray);
echo $someJSON;
}
else{
echo mysql_error();
}
?>
SaveTestAnswers.php
<?php
$qid = $_POST['qid'];
$ansId = $_POST['ansId'];
$stuId = $_POST['stuId'];
$testId = $_POST['testId'];
include('Config.php');
$query = "insert into testattemptedanswers(StudentId,TestId,QuestionId,AnswerGiven) values('".$stuId."','".$testId."','".$qid."','".$ansId."')";
$res = mysql_query($query);
if($res){
echo 'true';
}
else{
echo 'false'.mysql_error();
}
?>
Missing quotes -
var qno = <?php echo $qno;?>;
var qindex = <?php echo $qindex;?>;
Change them to -
var qno = '<?php echo $qno;?>';
var qindex = '<?php echo $qindex;?>';
And here also -
data : {
"qid" : arrQid[qindex],
"ansId" : $('input[name=options]:checked').val(),
"stuId" : '<?php echo $_SESSION['CurrentUser'];?>',
"testId" : '<?php echo $TestId;?>'
},

Select-option breaks the mark-up and doesn't post

I'm trying to implement live-table edit, but I'm having some trouble with my select options. The input type="text" is fully functional though.
Ever since I tried to add select, it seemed to brake my entire lay-out. First there were multiple rows and columns displayed on the page. But now there's only one and the columns show up empty after the one that contains select.
And the second problem is that ajax doesn't post the table edit since I added select to the mark-up. I'm thinking that this is because the mark-up breaks, but I'm not sure.
If anybody knows what to do, I'd appreciate it.
Markup
<?php
$query = ("select * from projectlist");
$resultaat = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($resultaat, MYSQL_ASSOC)){
$id = $row['projectid'];
?>
<tr class="predit">
<form action="" method="post">
//Working input
<td>
<span id="klant_<?php echo $id; ?>" class="text"><?php echo $row["Klant"]; ?></span>
<input type="text" class="ip" id="klant_ip_<?php echo $id; ?>" value="<?php echo $row["Klant"]; ?>">
</td>
//Same approach, but with select instead of input
<td>
<span id="project_<?php echo $id; ?>" class="text"><?php echo $row["Project"]; ?></span>
<select id="project_ip_<?php echo $id; ?>" class="ip">
<?php
//Fetch select options from another table
$query = ("select * from projecten");
$resultaat = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($resultaat, MYSQL_ASSOC)){
$listid = $row["projectcode"];
$projectnaam = $row["projectnaam"];
?>
<option value="<?php echo $projectnaam; ?>" id="<?php echo $listid; ?>"><?php echo $projectnaam; ?></option>
<?php
}
?>
</select>
</td>
</tr>
</form>
<?php
}
?>
JQuery Ajax
$(document).ready(function(){
//Projeclist
$(".predit").click(function(){
var ID=$(this).attr('id');
$("#klant_"+ID).hide();
$("#project_"+ID).hide();
$("#klant_ip_"+ID).show();
$("#project_ip_"+ID).show();
}).change(function(){
var ID=$(this).attr('id');
var klant=$("#klant_ip_"+ID).val();
var project=$("#project_ip_"+ID).val();
var dataString = 'id='+ ID
+'&Klant='+klant
+'&Project='+project;
//alert(dataString);
var project_txt = $("#project_ip_"+ID+" option:selected").text();
$.ajax({
type: "POST",
url: "post_table.php",
data: dataString,
cache: false,
success: function(html){
$("#project_"+ID).html(project_txt);
$("#klant_"+ID).html(klant);
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
});
});
$(".ip").mouseup(function() {
return false
});
$(document).mouseup(function(){
$(".ip").hide();
$(".text").show();
});
});
post_table.php
<?php
include('config.php');
$klant = $_POST['Klant'];
$project = $_POST['Project'];
$id = $_POST['id'];
$query = "update projectlist
set Klant='$klant',
Project='$project'
where projectid='$id'";
mysql_query($query, $con);
?>

when try to add more field and select then its conflict first row

When i am trying to select option value form row one there's no problem but if i add more and select optional value in second row then its getting conflict first. Every time when you select optional value then only first row conflict i want first row change while changing first select option . Second row select change only second row values.
index.php
<?php
if(!empty($_POST["save"])) {
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$itemCount = count($_POST["item_name"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
if(!empty($_POST["item_name"][$i]) || !empty($_POST["item_price"][$i])) {
$itemValues++;
if($queryValue!="") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_name"][$i] . "', '" . $_POST["item_price"][$i] . "')";
}
}
$sql = $query.$queryValue;
if($itemValues!=0) {
$result = mysql_query($sql);
if(!empty($result)) $message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
function addMore() {
$("<DIV>").load("input.php", function() {
$("#product").append($(this).html());
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php if(isset($message)) { echo $message; }?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index:item_index},`
success:function(result){
alert(result);
$('#div1').html(result);
}
});
}
</script>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV>
<DIV class="float-left"><select name="item_index" id="item_index" class="required input-small" onchange="salesdetail(this.value);" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$result = mysql_query("select * from item");
while($row=mysql_fetch_assoc($result))
{
echo "<option>".$row['item_name']."</option>";
}
?>
</select>
</DIV>
<DIV class="float-left" id="div1"><input type="text" id="unit_price" name="unit_price" /></DIV>
</DIV>
and getsaleinfo.php
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$supplier= $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
if($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini" value="<?php echo $row['item_price'];?>" >
</div>
<?php }
?>
database
CREATE TABLE IF NOT EXISTS `item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_name` varchar(255) NOT NULL,
`item_price` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `item` (`id`, `item_name`, `item_price`) VALUES
(1, 'hello', 21),
(2, 'hi', 22);
try this...
$('body').on('change','#item_index',function() { //works for ajax loaded contents
var id = $("#item_index").val();
var formid = new FormData();
formid.append('item_index',id);
$.ajax({
url : 'getsaleinfo.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formid,
type : 'post',
success : function(data){
alert(result);
$('#div1').html(result);
//document.getElementById("div1").innerHTML=data;
}
});
}
insted of onchange call this will do...
When you change the selection in the dropdown list, it sends the request to the server:
getsaleinfo.php with item_index:'hello'
That executes
select * from item where item_name='hello' (one line)
That sends
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini"
value="<?php echo $row['item_price'];?>" >
</div>
back to the caller.
The javascript puts that whole thing inside #div1 replacing whatever was there.
From what I'm gathering, addMore() is loading the whole of input.php every time and appending it to #product.
First of all that means you're repeated adding the jquery and function definition, but secondly (and the main problem) - each one adds a NEW div with ID=div1.
When you call
$('#div1').html(result)
in your salesdetail function, that just refers to the first one (since according to HTML you can only have one instance of each ID and the others are ignored.
/*------------------------index.php--------------------------*/
<?php
if (!empty($_POST["save"])) {
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$itemCount = count($_POST["item_index"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for ($i = 0; $i < $itemCount; $i++) {
if (!empty($_POST["item_index"][$i]) || !empty($_POST["unit_price"][$i])) {
$itemValues++;
if ($queryValue != "") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_index"][$i] . "', '" . $_POST["unit_price"][$i] . "')";
}
}
$sql = $query . $queryValue;
if ($itemValues != 0) {
$result = mysql_query($sql);
if (!empty($result))
$message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
var cnt = 1;
function addMore() {
$("<DIV>").load("input.php?cnt=" + cnt, function() {
$("#product").append($(this).html());
cnt++;
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item) {
jQuery(':checkbox', this).each(function() {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php
if (isset($message)) {
echo $message;
}
?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
/*------------------------input.php--------------------------*/
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index, item_id)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index: item_index, item_id: item_id},
success: function(result) {
alert(result);
$('#div_' + item_id).html(result);
}
});
}
</script>
<?php $_REQUEST['cnt'] = (isset($_REQUEST['cnt'])) ? $_REQUEST['cnt'] : 0; ?>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_ind[]" id="item_ind_<?php echo $_REQUEST['cnt']; ?>" /></DIV>
<DIV class="float-left"><select name="item_index[]" id="item_index_<?php echo $_REQUEST['cnt']; ?>" class="required input-small" onchange="salesdetail(this.value, '<?php echo $_REQUEST['cnt']; ?>');" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$result = mysql_query("select * from item");
while ($row = mysql_fetch_assoc($result)) {
echo "<option>" . $row['item_name'] . "</option>";
}
?>
</select></DIV>
<DIV class="float-left" id="div_<?php echo $_REQUEST['cnt']; ?>"><input type="text" id="unit_price_<?php echo $_REQUEST['cnt']; ?>" name="unit_price[]" /></DIV>
</DIV>
getsaleinfo.php
/*------------------------getsaleinfo.php--------------------------*/
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$supplier = $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
$_REQUEST['item_id'] = (isset($_REQUEST['item_id'])) ? $_REQUEST['item_id'] : '';
if ($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<input type="text" name="unit_price[]" id="unit_price_<?php echo $_REQUEST['item_id']; ?>" class="input-mini" value="<?php echo $row['item_price']; ?>" >
</div>
<?php }
?>

How to update my sql table with out page refresh in php?

Hi i want to update my sql table field without page refresh in php how can i achieve i tried but my code is not working i do not know where i am wrong
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'assignlead.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<?php
include('conn.php');
$per_page = 3;
if($_GET)
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$select_table = "select * from clientreg order by id limit $start,$per_page";
$variable = mysql_query($select_table);
?>
<form class="form2" action="" method="POST" name="myForm" id="myForm">
<div style="width:100%;">
<?php
$i=1;
while($row = mysql_fetch_array($variable))
{
?>
<input type="checkbox" name="users[]" value="<?php echo $row["id"]; ?>" >
<?php
}
?>
<div class="buttons"> <span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input class="greybutton" type="submit" value="Send" />
</div>
<?php
$sql = mysql_query("SELECT *FROM login where role=1");
while ($row = mysql_fetch_array($sql)){
?>
<input type="checkbox" name="eid[]" value="<?php echo $row["eid"]; ?>" ><?php echo $row["username"]; ?>
<?php
}
?>
</div>
</form>
</div>
</body>
</html>
assignlead.php
<?php
$conn = mysql_connect("localhost","root","root");
mysql_select_db("helixcrm",$conn);
if(isset($_POST["submit"]) && $_POST["submit"]!="") {
$usersCount = count($_POST["id"]);
for($i=0;$i<$usersCount;$i++) {
mysql_query("UPDATE clientreg set eid='" . $_POST["eid"][$i] . "' WHERE id='" . $_POST["id"][$i] . "'");
}
}
?>
<?php
$rowCount = count($_POST["users"]);
for($i=0;$i<$rowCount;$i++) {
$result = mysql_query("SELECT * FROM clientreg WHERE Id='" . $_POST["users"][$i] . "'");
$row[$i]= mysql_fetch_array($result);
$id=$row[$i]['id'];
?>
<input type="hidden" name="id[]" class="txtField" value="<?php echo $row[$i]['id']; ?>"></td>
<?php
$rowCoun = count($_POST["eid"]);
for($j=0;$j<$rowCoun;$j++) {
$result = mysql_query("SELECT * FROM login WHERE eid='" . $_POST["eid"][$j] . "'");
$row[$j]= mysql_fetch_array($result);
$eid=$row[$j]['eid'];
?>
<input type="hidden" name="eid[]" class="txtField" value="<?php echo $row[$j]['eid']; ?>">
<?php
}
}
?>
i tried a lot but i am not able to get my output
How can i achieve my output
Thanks in advance
Update your javascript like this :
$(document).ready(function(){
$('#myForm').submit(function(){
$.ajax({
url : 'assignlead.php',
data : $(this).serialize(),
type : 'POST',
success : function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
// !important for ajax form submit
return false;
});
});

Categories