I am gtting data from database, but it's printed again and again. There is get coding of index page.
var lastmsgid = 0;
function getChat() {
$.ajax({
type: "POST",
url: "view_msg.php",
data: "sid=<?php echo $id; ?>&lastmsgid="+lastmsgid,
async: false,
datatype: "json",
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var uname=row['uname'];
var msg=row['msg'];
$('#chatbox').append("<b>"+uname+"</b> : </b>"+msg).append("<hr />");
lastmsgid=row['id'];
}
}
});
}
Here is my view_msg.php page:
<?php
header('Content-type: application/json');
require_once('include/util.php');
$sid = $_POST['sid'];
$lastmsgid = $_POST['lastmsgid'];
$sql = "SELECT m.`id`, m.`msg`, u.`uname` FROM `message` as m JOIN `userdata` as u ON (m.`senderid`=u.`id`) WHERE m.`rcvrid` = ".$_SESSION['id']." OR m.`rcvrid` =$sid AND `senderid` = $sid OR `senderid` =".$_SESSION['id']." AND m.`id` > $lastmsgid order by m.`id` DESC limit 0,2" ;
$result = mysql_query($sql);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
if (!empty($data)) {
echo json_encode($data);
}
exit;
?>
You should check your SQL query.. You need to use brackets in where condition because you are using OR.. I don't know the conditions for your desired result but it may be like below:
$sql="SELECT m.`id`,m.`msg`,u.`uname` FROM `message` as m JOIN `userdata` as u ON (m.`senderid`=u.`id`) WHERE ((m.`rcvrid` = ".$_SESSION['id']." OR m.`rcvrid` =$sid) AND (`senderid` = $sid OR `senderid` =".$_SESSION['id']." ) ) AND m.`id` > $lastmsgid order by m.`id` DESC limit 0,2" ;
Related
My database columns as shown below:
`matDes1` varchar(255) DEFAULT NULL,
`matCost1` int(255) DEFAULT NULL,
`matDes2` varchar(255) DEFAULT NULL,
`matCost2` int(255) DEFAULT NULL,
`matDes3` varchar(255) DEFAULT NULL,
`matCost3` int(255) DEFAULT NULL,
`matDes4` varchar(255) DEFAULT NULL,
`matCost4` int(255) DEFAULT NULL,
`matDes5` varchar(255) DEFAULT NULL,
`matCost5` int(255) DEFAULT NULL,
I have a dynamic table with add and remove rows inside my HTML file.
Inside this table I have textarea and input, whenever I start typing will show me suggestions, and if I select one, will automatically populate other fields.
Here below my textarea and input:
<textarea id='codeANCILLARY_1' class='codeANCILLARY' name="codeANCILLARY[]"></textarea>
<input type="text" id="mat50ANCILLARY_1" class="mat50ANCILLARY" name="mat50ANCILLARY[]" />
textarea Searching through matDes1 to matDes5. so no problem here.
the problem is when selecting to populate both field, only accepting matDes1 and matCost1 not the rest.
is there a way to use say something like if statement and say:
if (matDes1 selected) {
show matDes1 with matCost1
} else if (matDes2 selected){
show matDes2 with matCost2
}
and
so
on
i really dont know anymore what must i do. :(
The full jQuery and PHP files are:
$(document).on('keydown', '.codeANCILLARY', function () {
var id = this.id;
var splitid = id.split('_');
var count = splitid[1];
$('#' + id).autocomplete({
source: function (request, response) {
$.ajax({
url: "../../MY_PHP_PAGE",
type: 'post',
dataType: "json",
data: {
search: request.term,
request: 1
},
success: function (data) {
response(data);
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label);
var id = ui.item.value;
// AJAX
$.ajax({
url: '../../MY_PHP_PAGE',
type: 'post',
data: {
id: id,
request: 2
},
dataType: 'json',
success: function (takesAnyVaribale) {
var len = takesAnyVaribale.length;
if (len > 0) {
var codeANCILLARY = takesAnyVaribale[0]['codeANCILLARY'];
var mat50ANCILLARY = takesAnyVaribale[0]['mat50ANCILLARY'];
var unitsANCILLARY = takesAnyVaribale[0]['unitsANCILLARY'];
$('#codeANCILLARY_' + count).val(codeANCILLARY);
$('#mat50ANCILLARY_' + count).val(mat50ANCILLARY);
$('#unitsANCILLARY_' + count).val(unitsANCILLARY);
}
}
});
return false;
}
});
});
"MY_PHP_PAGE"
include "config.php";
$request = $_POST['request'];
if ($request == 1) {
$search = $_POST['search'];
$query1 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes1 like'%".$search."%'";
$query2 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes2 like'%".$search."%'";
$query3 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes3 like'%".$search."%'";
$query4 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes4 like'%".$search."%'";
$query5 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes5 like'%".$search."%'";
$result1 = mysqli_query($con, $query1);
$result2 = mysqli_query($con, $query2);
$result3 = mysqli_query($con, $query3);
$result4 = mysqli_query($con, $query4);
$result5 = mysqli_query($con, $query5);
if ($result1 || $result2 || $result3 || $result4 || $result5) {
while ($row = mysqli_fetch_array($result1)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes1']);
}
while ($row = mysqli_fetch_array($result2)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes2']);
}
while ($row = mysqli_fetch_array($result3)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes3']);
}
while ($row = mysqli_fetch_array($result4)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes4']);
}
while ($row = mysqli_fetch_array($result5)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes5']);
}
}
echo json_encode($response);
exit;
}
if ($request == 2) {
$id = $_POST['id'];
$sql = "SELECT * FROM MY_COMPONENTLIST WHERE id=".$id;
$result = mysqli_query($con, $sql);
$AncillaryPricing_arr = array();
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$codeANCILLARY = $row['matDes1'];
$mat50ANCILLARY = $row['matCost1'];
//***************************
//***************************
$codeANCILLARY = $row['matDes2'];
$mat50ANCILLARY = $row['matCost2'];
.and
.so on
.until 5
//***************************
//***************************
$unitsANCILLARY = $row['units'];
$AncillaryPricing_arr[] = array(
"id" => $id,
"codeANCILLARY" => $codeANCILLARY,
"mat50ANCILLARY" => $mat50ANCILLARY,
"unitsANCILLARY" => $unitsANCILLARY
);
}
echo json_encode($AncillaryPricing_arr);
exit;
}
You really need a better database layout for exactly this reason. Split the matdes and matcost columns out into a separate table, linked by the component ID. You can have as many as you want, then, and it's much easier to search them. Instead of all your separate queries, you'd have something like
SELECT * FROM MY_COMPONENTLIST_MAT WHERE matDes like'%".$search."%' and component_id = " . $id
(except as a prepared statement) and it would find any of them. You can use a JOIN to get the rest of the information from the main component list.
When I send an ajax post request to my getMessages.php file it doesn't return anything.
I've tried manually setting the array values and printing them in the console and that seems to work.
getMessages.php
<?php
require_once "mysqli.php";
$data = array();
if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
$username = $_SESSION["username"];
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_array($result)) {
$data['startuser'] = $row['msg_startuser'];
$data['msg'] = $row['msg'];
}
}
echo json_encode($data);
exit;
?>
js ajax
function getChat() {
$.ajax({
url: 'getMessages.php',
type: 'POST',
data: {getChat: 'yes'},
dataType: 'JSON',
success: function(data) {
// testing
console.log(data.startuser, data.msg);
}
})
}
I want it to print out in the console for testing.
Hi you can try this way:
The php script :
<?php
require_once "mysqli.php";
session_start();// start the session
$data = array();
if (isset($_SESSION["username"])) {
if (isset($_POST["endUser"]) && isset($_POST["action"])) {
$case = $_POST["action"];
$endUser = $_POST["endUser"];
$username = $_SESSION["username"];
switch (case) {
case 'getChat':
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = '{$endUser}'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = '{$endUser}' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_assoc($resultado)) {
if (isset($row['msg_startuser']) && isset($row['msg'])) {
$temp = array(
"user"=>$row['msg_startuser'],
"msg"=>$row['msg']
);
}
$data[] = $temp;
}
echo json_encode($data);
break;
}
}
}else {
echo "error-403";
}
?>
The javascript :
function getChat() {
return $.ajax({
url: 'getMessages.php',
type: 'POST',
data: {action: 'getChat',endUser:'mariokiller470'},
dataType: 'JSON'
})
}
getChat()
.done(function(response){
console.log(response);
})
Hope it Helps
data is overwritten in the loop again and again, I guess you would like to do something like this:
$x = 0;
while ($row = mysqli_fetch_array ($result)) {
$data[$x]['startuser'] = $row['msg_startuser'];
$data[$x]['msg'] = $ row['msg'];
$x++;
}
Ooops!
I forgot to start the session!
Thanks PatrickQ!
This will solve the problem since you are returning response as objects
An Updates:
You will need to initialize session
and data parameters for an array should be inside the the if statements
Try code below
<?php
require_once "mysqli.php";
session_start();
if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
$username = $_SESSION["username"];
$data = array();
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_array($result)) {
$startuser = $row['msg_startuser'];
$msg = $row['msg'];
$data = array("startuser" =>$startuser, "msg" =>$msg);
}
echo json_encode($data);
exit;
}
?>
so in ajax console. this line of code will work fine
console.log(data.startuser, data.msg);
I'm creating a comment facility for a blog post using PHP and ajax to post the comment so the page does not refresh after a comment is posted.
This is the code that displays the comments when the page is visited. If there are no comments for the post it displays a notice. This all works.
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $row["comment"];
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
}
}else{
$comments = "<div class='alert alert-primary' role='alert'>Be the first to comment</div>";
}
When the comment form is submitted it calls this function.
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
success: function (response) {
document.getElementById("all_comments").innerHTML=response+document.getElementById("all_comments").innerHTML;
$("#summernote").summernote("reset");
},
});
}else {
alert('Please enter a comment');
}
return false;
});
This is the post_comment.php page
if(isset($_POST['comment'])){
$comments = "";
$comment=$_POST['comment'];
$member_id =$_POST['member_id'];
$post_id =$_POST['post_id'];
if(isset($comment)) {
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = $entry_id
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $comment;
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
echo $comments ;
};
exit;
}
}
}else {
header("location: /blog");
exit;
}
If you are the first to comment on a post the comment displays but the "Be the first to comment" notice is still displaying until the page is refreshed.
Try return the response from the server as json. Plus remove the exit and header on your server side.
<script type="text/javascript">
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
dataType : "json",
encode : true,
success: function (data) {
$.each(data, function(index, element){
$('#all_comments').append("<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by " +element.comment_author + "on " + element.post_date+"</p>"+element.comment+"<hr /></div></div>");
});
$("#summernote").summernote("reset");
$('.alert').empty();
},
});
}else {
alert('Please enter a comment');
}
return false;
});
</script>
Then your server side.
<?php
if (isset($_POST['comment'])) {
$comment = $_POST['comment'];
$member_id = $_POST['member_id'];
$post_id = $_POST['post_id'];
$commentsArray = array();
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = ?
ORDER BY comm.comment_date DESC");
$sql->bind_param("ii", $post_id, $entry_id);
$sql->execute();
$sql_result = $sql->get_result();
if ($stmt_result->num_rows > 0) {
while ($row = $stmt_result->fetch_assoc()) {
$comment_date = date_create($row['comment_date']);
$commentsArray[] = array(
'comment' => $comment,
'post_date' = date_format($comment_date, ' l jS F Y H:i');
'comment_author' => $row['member_screen_name']
);
}
}
echo json_encode($commentsArray);
}
Also use the network tab on your browser console to see the response coming from the server.
it is normal for him to behave like this, and at no time will you ask the notification not to appear after the comment.
update your code after the success
$('.alert-primary').hide()
I have a form in that I am trying to do inline editing and adding using AJAX call.
Firstly I am displaying data in HTML table. And then if enter data into text boxes and click on add button record adding displaying data in HTML table. After I click edit button data showing in the textboxes fine.
But I am getting the ajax response as null.
I couldn't figure it out.
This is my AJAX code PHP file:
$(function() {
$(".scrollingTable tbody a").click(function() {
//debugger;
var link = $(this).attr('href');
var arr = link.split('=');
var id = arr[1];
//alert(id);
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
cntid: id
},
success: function(datas) {
var data = $.parseJSON(datas);
$("#num").val(data.id);
$("#namegr").val(data.vndr_cntname);
$("#designation").val(data.designation);
$("#mobilegr").val(data.vndr_cntmobile);
$("#maildgr").val(data.vndr_cntmail);
}
});
});
});
$(function() {
$('.txtcbt a').click(function() {
debugger;
var cntname, designation, mobile, email, vndrid, id, cid;
cid = $("#num").val();
cntname = $("#namegr").val();
designation = $("#designation").val();
mobile = $("#mobilegr").val();
email = $("#maildgr").val();
vndrid = "<?php echo $selectid; ?>";
//alert(cid);
if (cntname == "" || designation == "" || mobile == "" || email == "") {
alert("fields should not be empty");
} else {
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
id: cid,
name: cntname,
dgnation: designation,
mobileno: mobile,
emailid: email,
vid: vndrid
},
success: function(html) {
var dat = $.parseJSON(html);
alert(html);
alert("it came to success");
$("#num").val("");
$('#namegr').val("");
$('#designation').val("");
$('#mobilegr').val("");
$('#maildgr').val("");
}
});
}
});
});
This is file AJAX is calling:
<?php
require('Assests/connection/connection.php');
error_reporting(0);
$vcntlist = "";
if (!empty($_POST['cntid'])) {
$id = $_POST['cntid'];
$result = mysqli_query($conn, "SELECT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,`vndr_id` FROM `vndr_cntdtls`where id=$id");
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_array($result);
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
if (!empty($_POST['name']) && !empty($_POST['dgnation']) &&
!empty($_POST['mobileno']) && !empty($_POST['emailid']) &&
!empty($_POST['vid'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$degination = $_POST['dgnation'];
$mobile = $_POST['mobileno'];
$email = $_POST['emailid'];
$vndrid = $_POST['vid'];
if (empty($_POST['id'])) {
$query = mysqli_query($conn, "INSERT INTO `vndr_cntdtls`(`vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`, `vndr_id`) VALUES ('$name','$degination','$mobile','$email',$vndrid)");
} else {
$update1 = mysqli_query($conn, "UPDATE `vndr_cntdtls` SET `vndr_cntname`='$name',`designation`='$degination',`vndr_cntmobile`='$mobile',`vndr_cntmail`='$email' WHERE id=$id") or die(mysqli_error($conn));
}
$result = mysqli_query($conn, "SELECT DISTINCT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,vc.vndr_id FROM `vndr_cntdtls` vc INNER JOIN vendors v ON vc.vndr_id=$vndrid") or die(mysqli_error($conn));
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
}
echo json_encode($row);
?>
There could be a lot of ways it is not working.
First:
You need to put a application/json in your php so it can be compatible with the browser you are using.
header('Content-Type: application/json');
echo json_encode($row);
Second:
Why are you doing a while loop and assigning it into an unused variable?
You can simplify it by doing:
$row = mysqli_fetch_array($result);
header('Content-Type: application/json');
echo json_encode($row);
Unless it is multiple rows then:
$rowcount = mysqli_num_rows($result);
$rows = array();
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($row);
Third
null values usually appears when a variable you are trying to use is not initialized. By having the error_reporting turned off it does not display the error.
error_reporting(true);
Fourth
Check also the logs for database error, I assume it has something to do with MySQL query not having to reach the $row initialization.
Fifth
I believe you need to have it fetched as associative array for it to be useful
$row = mysqli_fetch_assoc($result);
I am using the following ajax script to run my MySQL query and then only want the jquery to fade out my div and fade in another if the query returned true otherwise if the query returned false don't do anything.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "include/fade_to_do_list.php",
data: "theOption=" + $(this).attr("id"),
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("success") >-1 ){
setTimeout(
function() {
$("#to_do_list").fadeOut();
}, 3500
);
setTimeout(
function() {
$("#compliance_list").fadeIn();
}, 500
);
}
}
});
});
</script>
PHP/MYSQL:
<?php
session_start();
include 'config.php';
$query = "SELECT * FROM supplier_stats WHERE complete_count = > 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
if($result2) {
$return['res'] = 'success';
} else {
}
}
echo json_encode($return);
?>
Please can someone show me where I am going wrong? I currently get no error and my jquery just doesnt execute. Thanks
mysql_query() always return you something. You need to count number of affected row.
Also problem is with equal to greater then operator it is used as >=
$query = "SELECT * FROM supplier_stats WHERE complete_count >= 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
$total=mysql_affected_rows();
if($total >0) {
$return['res'] = 'success';
} else {
}