The whole code works, but the problem appears when I'm trying to get data from the database:
For fetching data, I'm using PHP:
function chatStory() {
$sql = mysql_query("SELECT * FROM chat WHERE username = '".$_SESSION['username']."' ");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
echo json_encode($rows);
}
Then I'm able to retrieve that data by JavaScript:
$.ajax({
url: 'chat.php?action=chatstory', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var msg = row[0];
var user = row[1];
$("#chat_"+nazwa+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+user+': </span><span class="chatboxmessagecontent">'+msg+'</span></div>');
}
}
});
I can't find my error. Every message is showing. There are 7 messages in the database and I can see 7 messages in the chatbox, but they are appearing as undefined.
Related
I have created a chat website. I send the message with AJAX to PHP and the MySql Database. The messages are fetched using AJAX which runs per second. But this lead to fetch of all the messages (from starting to end). I came with an solution that I will pass the last message ID to the AJAX/JAVA SCRIPT and then fetch only the messages which are more than that.
Here is the Java Script / AJAX
function fetchdata(){
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
data : {cuser:cuser, ouser:ouser},
success: function(read){
$("#readarea").html(read);
}
});
}
Here is the PHP code to get messages:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
$result = mysqli_query($conn, $sql) or ("Query Failed");
while($row=mysqli_fetch_assoc($result)){
if($row["fromid"]==$_POST['cuser']){
echo "<div class='cuser'>".$row["message"]."</div>";
}else{
echo "<div class='ouser'>".$row["message"]."</div>";
}
}
Here I want to get the ID (message) in the Java Script function back from the PHP and use it as a variable for fetching the messages which will be more than it.
You should return JSON from the PHP, instead of HTML. That way you can return an object with properties such as ID, message, etc. Then you can use Javascript to store the latest ID, and also to put the message into your page with the relevant HTML.
Something like this:
PHP:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
if (!empty($_POST["lastid"]) $sql .= " AND id > {$_POST['lastid']}";
$result = mysqli_query($conn, $sql) or ("Query Failed");
$messages = array();
while($row=mysqli_fetch_assoc($result)){
$messages[] = $row;
}
echo json_encode($messages);
JS:
//make this global so it persists beyond each call to fetchdata
var lastMessageID = null;
function fetchdata()
{
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
dataType: "json",
data : { cuser: cuser, ouser: ouser, lastid: lastMessageID },
success: function(read) {
for (var i = 0; i < read.length; i++)
{
var className = "ouser";
if (read[i].fromid == cuser) classname = "cuser";
$("#readarea").append("<div class='" + className + "'>" + read[i].message + "</div>");
lastMessageID = read[i].id;
}
}
});
}
P.S. Please also take note of the comment about about SQL injection and fix your query code, urgently. I haven't done it here for the sake of brevity, but it must not be ignored.
I have the following problem:
I have a working implementation of JQuery UI Autocomplete that gathers results from MYSQL Database and autotomatically fills some input fields based on user's choice.
What I am currently trying to get working is the situation when you type your search and there are no search results. Right now, the last suggested search items stay visible until you click away with mouse button. I would like to be able to hide it once there are no matching results. I have read a lot on this topic but nothing seemed to work for me. This is my Javascript part:
function AutoFill(x) {
var classname = "." + x;
$(document).on('keydown', classname, function(){
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
// Initialize jQuery UI autocomplete
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "get-details.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response(data);
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected value
// AJAX
$.ajax({
url: 'get-details.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var id = response[0]['id'];
var name = response[0]['name'];
var number = response[0]['number'];
// Set value to textboxes
document.getElementById('clientname').value = name;
document.getElementById('clientnumber').value = number;
}
}
});
return false;
}
});
});
}
And this is my PHP file, that searches through the Database:
<?php
include('includes/dbconnection.php');
$request = $_POST['request']; // request
// Get username list
if($request == 1){
$search = $_POST['search'];
$query = "SELECT * FROM tblclients WHERE FullName like'%".$search."%' OR MobileNumber like'%".$search."%'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$response[] = array("value"=>$row['ID'],"label"=>$row['FullName'].' | '.$row['MobileNumber']);
}
// encoding array to json format
echo json_encode($response);
exit;
}
// Get details
if($request == 2){
$userid = $_POST['userid'];
$sql = "SELECT * FROM tblclients WHERE ID=".$userid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['ID'];
$fullname = $row['FullName'];
$number = $row['MobileNumber'];
$users_arr[] = array("id" => $userid, "name" => $fullname,"number" => $number);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
}
I don't know what I'm doing wrong...
I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});
I am creating a webpage having Excel like features to create a Plan.For this i need to fill an initial form and click on submit button , then submit the form using ajax to a server side PHP script which inserts these records to a Mysql table.
But the issue is i can only transfer 1-2 records of table using the POST Query as there is a limit to it.What should i do in this case?Is there any other way of doing it without expanding the POST query limit?
My Front end code(.js)
</script>
buttons.save.addEventListener('click', function() {
var r1 = hot.countRows() - hot.countEmptyRows() - 1;
var c1 = hot.countCols()- 1 ;
var data = String(hot.getData(0,0,r1,c1));
data = data.replace(/,/g,'');
document.getElementById('all_data').value= JSON.stringify(hot.getData(0,0,r1,c1));
document.getElementById('colheaders').value=JSON.stringify(hot.getColHeader());
console.log(hot.getInstance());
var testplan_name = document.getElementById('feature_name').value;
var product = document.getElementById('product').value;
var release = document.getElementById('release').value;
var pv_engg = document.getElementById('pv_engg').value;
var pe_engg = document.getElementById('pe_engg').value;
var rd_engg = document.getElementById('rd_engg').value;
var tp_completion = document.getElementById('tp_completion').value;
var at_completion = document.getElementById('at_completion').value;
var all_headers = document.getElementById('colheaders').value;
var all_data = document.getElementById('all_data').value;
var maker = document.getElementById('maker').innerHTML;
var datastring = 'testplan_name='+testplan_name+'&product='+product+'&release='+release+'&pv_engg='+pv_engg+'&pe_engg='+pe
_engg+'&rd_engg='+rd_engg+'&tp_completion='+tp_completion+'&at_completion='+at_completion+'&headers='+all_headers+'&all_data='
+all_data+'&maker='+maker;
if(testplan_name=="" || pv_engg =='' || pe_engg== '' || rd_engg== '' || product=='' || release=='') {
else if(data=="") {
alert("For creating a testplan , you need to fill this table.");
}
else {
alert(datastring);
$.ajax({
url :"save_create_pro.php",
type :"POST",
data : datastring,
cache : false,
success :function(result) {
console.log(result);
alert(result);
alert("Form Submitted successfully");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
return false;
});
});
</script>
My Backend php code:
<?php
$dbh=mysql_connect('noiwebfarmo','abc','xyz');
if(! $dbh ) {
die('Could not connect: ' . mysql_error());
}
$database=mysql_select_db('testmohit');
$testplan_name=$_POST['testplan_name'];
$product=$_POST['product'];
$release=$_POST['release'];
$pv_engg=$_POST['pe_engg'];
$pe_engg=$_POST['pe_engg'];
$rd_engg=$_POST['rd_engg'];
$tp_completion=$_POST['tp_completion'];
$at_completion=$_POST['at_completion'];
$maker=$_POST['maker'];
$headers=stripslashes($_POST['headers']);
$all_data = stripslashes($_POST['all_data']);# to remove \ before " that occur when parsed through ajax
$headers=preg_replace('/\["/','',$headers);
$headers=preg_replace('/"\]/','',$headers);
$headers=split('","',$headers);
for($j=0;$j<count($headers);$j++) {
$headers[$j]= str_replace(' ','_',strtolower("$headers[$j]"));
}
$date=date('Y-m-d');
$all_data=preg_replace('/\[\["/','',$all_data);
$all_data=preg_replace('/"\]]/','',$all_data);
$rows_data=split('"\],\["',$all_data);
or($i=0;$i<count($rows_data);$i++) {
$data[$i] = split('","',$rows_data[$i]);
}
$result = array();
foreach($data as $key => $val){
$temp = array();
foreach($val as $k => $v){
$temp[$headers[$k]] = $v;
}
$result[] = $temp;
}
#print $all_data;
print count($result);
print_r($result);
for($i=0;$i < count($result);$i++) {
$temp = $result[$i];
$query = "INSERT INTO testplans (testplan_name,product,pro_release,percent_tpcompletion,percent_atcompletion,pv_engineer,rnd_engg,pe_engg,tc_name,cell_name,customer_name,flops,title,status,mfix_ccr,test_scenerio,expected_results,ccr_no,ccr_status,remarks,create_date,maker) VALUES ('$testplan_name','$product','$release','$tp_completion','$at_completion','$pv_engg','$rd_engg','$pe_engg','$temp[testcase_name]','$temp[cell_name]','$temp[customer]','$temp[flops]','$temp[title]','$temp[status]','$temp[mfix_ccr]','$temp[scenerio_brief_description]','$temp[expected_results]','$temp[ccr_no]','$temp[ccr_status]','$temp[remarks]','$date','$maker')";
mysql_select_db('testmohit');
$enter=mysql_query($query,$dbh);
if(! $enter) {
die('Could not enter data: ' . mysql_error());
}
}
# echo "$query Entered data successfully";
mysql_close($dbh);
?>
Please provide a solution to insert large no. of rows of handson table without expanding the size of query string .What can be the solution of this problem.
Thanks in advance.
I'm making a website with different products. When a product is clicked, AJAX call gets the product data from the database. After this, I want to go to a new page, where product-data will be displayed. But there is the problem, when the new page is loaded, the data won't be displayed, because the data were loaded at the previous page.
Javascript:
$('#products').on('click', 'li', function(){
document.location.href = "product.html";
var datapk = $(this).attr('data-pk');
console.log(datapk);
$.ajax({
type: 'POST',
url: 'connection.php',
data: {
'function': 'get_product_data',
'datapk': datapk
},
success: function(data) {
var productData = JSON.parse(data);
displayProductData(productData);
}
});
});
PHP:
function get_product_data(){
$datapk = mysql_real_escape_string($_POST['datapk']);
$query = "SELECT * FROM Products WHERE prod_id = '$datapk'";
$result = mysqli_query($GLOBALS['dbc'], $query) or die('Error querying database.');
$json = array();
if (mysqli_num_rows($result)){
while ($row = mysqli_fetch_row($result)){
$json[] = $row;
}
}
echo json_encode($json);
mysqli_close($db_name);
}
Data-pk is the unique ID in database.
As Rory said..
Either it's document.location.href = "product.html"; or $.ajax({ ... })
However, what's the difference between document.location.href = "product.html and <a href='product.html'>, you might ask yourself.