I want to pass variables from post.php to addcomment.php through the AJAX request. I have tried the code below but it does not seem to work. It reloads the page but nothing happens nor is data inserted in database
post.php
//variables to pass
$userid = $row['userid'];
$uid = $row['uid'];
$postid = $row['postid'];
<form method='post' name='form' action='' class='commentbox'>
<textarea name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit' class='comment_button'/>
</form>
<script type="text/javascript" >
var userfrom = '<?php echo $uid ?>';
var userto = '<?php echo $userid ?>';
var postid = '<?php echo $postid ?>';
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
dataString: dataString,
userfrom: userfrom,
userto: userto,
postid: postid
}
cache: false,
success: function(html){
$(".display").show(html);
}
});
}
return false;
});
});
</script>
addcomment.php
if (isset($_POST['dataString'], $_POST['userto'], $_POST['userfrom'], $_POST['postid'])) {
$userid = $_POST['userto'];
$uid = $_POST['userfrom'];
$postid = $_POST['postid'];
$comment = $_POST['dataString'];
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, post) VALUES (:comment, :userto, :userfrom, :post)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':post'=>$postid));
}
Create hidden fields for userid, uid and postid and assign the values.
Get the values as var userfrom = $("#uid").val(); in script (post.php). It will Work
Please try below code, just replace below code.
your page is reloaded because of add button type submit, for ajax event you need to set type button, Please check below code :
<?php
//variables to pass
$userid = $row['userid'];
$uid = $row['uid'];
$postid = $row['postid'];
?>
<form method='post' name='form' action='' class='commentbox'>
<textarea name='content' id='content'></textarea><br />
<input type='button' value='Comment' name='submit' class='comment_button'/>
</form>
<script type="text/javascript" >
var userfrom = '<?php echo $uid ?>';
var userto = '<?php echo $userid ?>';
var postid = '<?php echo $postid ?>';
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
dataString: dataString,
userfrom: userfrom,
userto: userto,
postid: postid
},
cache: false,
success: function(html){
$(".display").show(html);
}
});
}
return false;
});
});
</script>
Related
I have fetch(placing in inputboxes) the customer name and Dob from database through Customer phone . I am done the work but if I put the wrong customer number(there is no number in database) there will be show a alert box...that didn't know to me for how to do that...Can you please anyone solve my code...
<input type="text" class="search">phone
<input type="text" id="cname">name
<input type="text" id="cdob">date of birth
This is the script tag
<script>
$(document).ready(function() {
$('.search').keyup(function() {
var mobile_no = $(this).val();
$.ajax({
url: "get_customer_info.php",
method: "POST",
dataType: "json",
data:{
search : mobile_no
},
success:function(data){
$.each(data,function(id, val){
$("#cname").val(val.cname);
$("#cdob").val(val.cdob);
});
}
});
});
});
</script>
and this is query page
<?php
include("config.php");
$mobile=$_POST['search'];
$sql="SELECT * FROM `cm` WHERE cphone ='$mobile'";
$result = mysqli_query($conn,$sql,true);
if($result===true)
{
$mainarray=array();
while($row=$result->fetch_assoc())
{
$row['cm_id'];
$row['cname'];
$row['cdob'];
array_push($mainarray, $row);
}
echo json_encode($mainarray);
}
else
{
echo 'There is no data';
}
?>
Front end file:
<input type="text" class="search">phone
<input type="text" id="cname">name
<input type="text" id="cdob">date of birth
Your Script file:
<script>
$(document).ready(function() {
$('.search').keyup(function() {
var mobile_no = $(this).val();
if(mobile_no.length >= 10 ){
$.ajax({
url: "get_customer_info.php",
method: "POST",
dataType: "json",
data:{
search : mobile_no
},
success:function(responce){
if($.trim(responce)){
$.each(responce,function(id, val){
$("#cname").val(val.cname);
$("#cdob").val(val.cdob);
});
} else{
alert("no data");
}
}
});
}
});
});
</script>
This is your get_customer_info.php file
<?php
include("config.php");
$mobile=$_POST['search'];
$sql="SELECT * FROM `cm` WHERE cphone ='$mobile'";
$result = mysqli_query($conn,$sql,true);
if($result==true)
{
$mainarray=array();
while($row=$result->fetch_assoc())
{
$row['cm_id'];
$row['cname'];
$row['cdob'];
array_push($mainarray, $row);
}
echo json_encode($mainarray);
}
else
{
echo 'There is no data';
}
?>
I am trying to update userlevel when click on button. i have a page where it will display all users there i have change level button.by default every user will be in normal level(means 3) so when i click on a button it has to change to 5(lead
) and if i click again it has to change to 9(admin)
here is my view page code:
<div class="col-md-4">
<form method="post" class="change_userlevel" action="" onclick="getConfirmation(9);">
<input type="hidden" name="id" value="<?php echo $user->id; ?>">
<button type="submit" class="widget-icon" name="login"><span class='icon-arrow-up'></span></button>
</form>
</div>
<td>
<?php
if($usertype==9)
{
echo 'Admin';
}
elseif($usertype==5)
{
echo 'Teamlead';
}
else
{
echo 'Normal';
}
?>
</td>
Here is my script code with ajax:
<script type='text/javascript'>
function getConfirmation(id){
$.ajax({
url: "User/change_status",
type: "post",
data: id,
success: function (response) {
location.reload();
}
});
}
</script>
Here is my controller code method change_status:
function change_status(){
$id = $this->input->post('id');
$status = $this->db->query("select userlevel from users where id=9")->row()->userlevel;
if($status==3){
$status = 5;
} else {
$status = 9;
}
$data=array('userlevel'=>$status);
$this->db->where('id','id');
$this->db->update('users',$data);
}
I dont know where i have done mistake it is not working.
can anyone help me how to solve this.
Thanks in advance.
Hope this will help you :
Your ajax code should be like this :
<script type='text/javascript'>
function getConfirmation(id)
{
if (id != '')
{
$.ajax({
url: "<?=site_url('User/change_status');?>",
type: "post",
data: {'id' : id},
success: function (response) {
alert('success');
//location.reload();
}
});
}
}
</script>
Your method change_status should be like this :
function change_status()
{
$id = $this->input->post('id');
$status = $this->db->select('userlevel')->where('id', $id)->get('users')->row()->userlevel;
if($status == 3)
{
$status = 5;
} else
{
$status = 9;
}
$data = array('userlevel' => $status);
$this->db->where('id', $id);
$this->db->update('users',$data);
echo TRUE;exit;
}
I want to organize the selection query from index.php to action, so i can be able to call the file with ajax to show the data on the page.(index.php). So, the activity I want to do is to able to submit data of the form to the database and to display result on the same page(index.php) without refreshing the page. Help please
Here's my files
1.action.php
2.index.php
3.maker.js
//-----------------------action.php-----------------------------
<?php
include ("db_connect.php"); // Connecting to the database
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$action = $_REQUEST['action'];
if ($action=="add")
{
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
?>
//index.php
<div id="table_content"></div>
<script type="text/javascript" src="maker.js">
<?php
function ShowForm($AnswerCommentId)
{ ?>
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/>
<button type='button' OnClick=SendComment()>Comment</button>
</form>
<?php
}
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0)
{
global $AnswerId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
?>
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) { echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0])
{
?><div id="InnerDiv"><?php ShowForm($AnswerId); ?></div>
<?php
}
?> </div> <?php
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable, 0);
?>
//maker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
clean_form();
}
});
return false;
}
So you are basically trying to make ajax based comment system, From what i see, your code organization is not clear based on there tasks, specifically your index.php file so here is what you can do to simplify things :
your action.php should hanlde all php database releted tasks
Move your html code to some other file (Create Template)
Here is the modified code that i have come up with (This is just for your reference, you should modify this accoring to you needs, and as Xorifelse suggested in comment you should always use prepared statements in production system because of security concerns):
Action.php
<?php
include ("db_connect.php"); // Connecting to the database
$action = $_REQUEST['action'];
if ($action=="add")
{
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$text = $_REQUEST['text'];
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
if ($action=="get")
{
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
$mytable = array();
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
tree($mytable, 0, $AnswerId);
}
function tree($treeArray, $level, $ansId, $pid = 0)
{
$AnswerId = $ansId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
include('comments.template.php');
tree($treeArray, $level+1,$AnswerId, $item[0]); // Recursion
}
}
}
?>
index.php
<html>
<head>
<title>Test page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="maker.js"></script>
</head>
<body onload="loadComments();">
<div id="table_content">
</div>
</body>
</html>
comments.template.php
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60); ?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) {
echo 'Reply';
}
echo 'Delete';
?>
</div>
<?php if ($AnswerId == $item[0]) { ?>
<div id="InnerDiv"><?php include('commentForm.template.php'); ?></div>
<?php } ?>
commentForm.template.php
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerId);?>"/>
<button type='button' OnClick="SendComment()">Comment</button>
</form>
marker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "action.php",
data: "AnswerId="+id+"&action=get",
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
return false;
}
function loadComments (){
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "action=get",
success: function(html){
$("#table_content").html(html);
//clean_form();
}
});
return false;
}
I am trying to update mysql database table with button click. But database is not getting updated...
HTML Code :
<tr >
<td>Advt Heading :</td>
<td>
<input type="hidden" name="idnew" id="idnew" value="<?=$member_data['id']?>"> //retrieved from mysql database
<input type="text" name="advt_headingnew" id="advt_headingnew" value="<?=stripslashes($member_data['advt_heading']);?>" /> //retrieved from mysql database ...**I want to edit its previus retreived value...and update database**
<input name="submit" type="button" id="submit" value="Update" />
</td>
</tr>
SCRIPT :
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#submit').click(function(){
var advt_headingnew = $("#advt_headingnew").val();
var idnew = $("#idnew").val();
$.ajax({
type:'POST',
url:'update-advt-heading.php',
data: "advt_headingnew="+advt_headingnew+"&idnew="+idnew,
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
});
});
</script>
PHP - update-advt-heading.php CODE :
<?
$user_name = "databaseusername";
$password = "databasepassword";
$database = "databasename";
$server = "localhost";
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
$heading = $_POST['advt_headingnew'];
$id=$_POST["idnew"];
if (isset($_POST['submit'])){
$queryStr = "UPDATE tablename SET advt_heading='$heading' WHERE id='$id'";
if ( mysql_query($qyeryStr)){
return "success!";
}else{
return "failed!";
}
}
?>
Change your js code to this
$(document).ready(function () {
$('#submit').click(function(){
var advt_headingnew = $("#advt_headingnew").val();
var idnew = $("#idnew").val();
var submitval = $(this).val();
$.ajax({
type:'POST',
url:'update-advt-heading.php',
data: "advt_headingnew="+advt_headingnew+"&idnew="+idnew+"&submit="+submitval,
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
});
});
I have changed
var advt_headingnew = $("#advt_headingnew").val();
var idnew = $("#idnew").val();
To
var advt_headingnew = document.getElementsByName("advt_headingnew")[0].value;
var idnew = document.getElementsByName("idnew")[0].value;
NOW IT IS WORKING..
I made a simple sample on how to insert using AJAX and retrieving it then append it in a <div> after getting it. But I am having trouble on getting all the content of the table, it's returning a null values.
<div id="wrap-body">
<form action method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
jQuery:
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$('#info').append("<p> you are:"+data.username+"</p> <p> your message is:"+data.mesg);
}
});
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$return = $row['user_name'];
$return = $row['message'];
}
echo json_encode($return);
?>
Your while should create array and then do json_encode
Try below code
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message']
);
}
echo json_encode($data);
exit
Now write your javascript success handler as below
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$.each(data, function(i, item) {
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
});
}
});
There are several issues you have to fix, but you have to start with returning the same type as expected by the ajax call:
$return = array()
if ($row = mysql_fetch_array($result))
{
$return['username'] = $row['user_name'];
$return['mesg'] = $row['message'];
}
echo json_encode($return);