Retrieving data from database and displaying it by using ajax - php

Okay people, what I am trying actually trying to achieve is, to create a chat box something similar to fb without refreshing the page. I have two tables in my database(phpmyadmin) where the first table, i store 2 users chat id(unique) and later save their message in another table so that i will be able to retrieve their chat history just by their unique id.
So I was able to send their Id(unique) by using get method to send the unique ID to the second div and then run through the database using php and display their conversation.
So how can i do it in ajax so that the page does not refreshes guys ? Some guide on that please ? I have been trying to google for it but i cant find a way simply because i do not know ajax much.
The purpose of me wanting it to not refresh the page is because i am using Jquery to hide and show the chat conversation. When the page refreshes, the conversation disappears. Im sorry if my explanation is not on point, hopefully somebody understands my problem and guide me in this :D
So here are my codes ...
This code is in my first div. It basically displays all the users who I have chatted with before...
<div>
<ul style="list-style-type: none;">
<?php
include 'connectDB.php';
//retrieve all the message history of yours from the PrivateMessage table
$query = "SELECT * FROM `messagecheck` WHERE `sender_a` = '$userId'
OR `sender_b` = '$userId';";
$result = mysqli_query($dbconnect,$query);
if(mysqli_num_rows($result) > 0)
{
//if exist, display the history
while($row = mysqli_fetch_assoc($result))
{
?>
<a href="Item_v1.php?msgId=<?php echo $row['exist']?>">
<li style="color:black; width:100%; padding-top:5px" >
<input id="IDValue" name="IDValue" value="<?php echo $row['exist']?>" >
<?php
//if the sender_a id is not my id, display the name
//if sender_a is my id, then display sender_b
//Because we dont want to see our name in the chat History
if($row['sender_a'] != $userId)
{
$senderName = $row['sender_a'];
include 'connectDB.php';
$nameSearch = "SELECT `fName`, `lName` FROM `register` WHERE `id`='$senderName';";
$Searchresult = mysqli_query($dbconnect,$nameSearch);
$Searchrow = mysqli_fetch_assoc($Searchresult);
echo $Searchrow['fName'] ." ". $Searchrow['lName'];
}
else
{
$senderName = $row['sender_b'];
include 'connectDB.php';
$nameSearch = "SELECT `fName`, `lName` FROM `register` WHERE `id`='$senderName';";
$Searchresult = mysqli_query($dbconnect,$nameSearch);
$Searchrow = mysqli_fetch_assoc($Searchresult);
echo $Searchrow['fName'] ." ". $Searchrow['lName'];
}
?>
</li>
</a>
<?php
}
}
?>
</ul>
</div>
So basically when i click the names which will be in the < li > tag, it should be posting the messages in another div(Which is the div below)...
<!-- //Message Content! -->
<div style="width:100%;max-height: 300;border: 2px solid #1F1F1F;overflow: auto;">
<?php
if($_GET)
{
$msgId = $_GET['msgId'];
}
if(!empty($msgId))
{
include 'connectDB.php';
$collectMsgQuery = "SELECT * FROM `privatemessage` WHERE `existing_id` = $msgId";
$MsgResult = mysqli_query($dbconnect, $collectMsgQuery);
if(mysqli_num_rows($MsgResult) > 0)
{
while($Msgrow = mysqli_fetch_assoc($MsgResult))
{
if($userId == $Msgrow['from_who']){
?>
<h4 class="ifMe"><span class="ifMeDesign"><?php echo $Msgrow['message'] ?></span></h4>
<?php
}else if ($userId == $Msgrow['to_who']) {
?>
<h4 class="notMe"><span class="notMeDesign"><?php echo $Msgrow['message'] ?></span></h4>
<?php
}
}
}
}
?>
</div>
P.S : I'm not really sure how to work with ajax so that is why i am posting it here. Any help would be great! Thanks in advance ! :D

Working with ajax, at the beginning, can be very frustrating. You should start with more simple task, simply to understand what you're working with.
Start with something like this, a simple request that send two numbers to the server and then alert the sum
ajax_request.php
<?php
$num1 = isset( $_GET[ "num1" ] ) ? $_GET[ "num1" ]: 0;
$num2 = isset( $_GET[ "num2" ] ) ? $_GET[ "num2" ]: 0;
echo $num1 + $num2;
index.html
<html>
<head>
<script src="jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function () {
$( "#calculate" ).click(function(e) {
e.preventDefault();
$.ajax({
url: 'ajax_request.php',
data: $( "#form" ).serialize(),
success: function( data ) {
alert( data );
},
error: function() {
alert( "Something went wrong" );
}
});
});
});
</script>
</head>
<body>
<form id="form">
Num1: <input type="text" name="num1" /><br />
Num2: <input type="text" name="num2" /><br />
<input type="submit" id="calculate" />
</form>
</body>
</html>
Open index.html (download the jQuery library), fill the two numbers and click the button.
You can test the "Something went wrong", simply put a wrong url (ajax_requestx.php instead of ajax_request.php).
From here, you can study "ajax" and "jQuery" to understand better how this work.
The concept is this: you stop the form to be sent (e.preventDefault()) and instead send the form in "asyncronous" way, making javascript send the request to the server without changing the page; in the "success" function you can analyze the string sent back from the server and do something with it. All done by javascript

Related

What's wrong with this calculation?

Consider this markup:
<?php
$drill = 0;
$result = '';
$dynamicD = rand(5,15);
$num01 = $dynamicD-4;
$placeholder = $num01.'+4';
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["drill"])){
$humanErr = "Empty";
}
else {
$drill = $_POST["drill"];
if($drill !== $dynamicD) {
$result = "No";
}
else {
$result = "Yes";
}
};
};
?>
<!doctype html>
<html>
<body>
<p>Correct Answer: <?php echo $dynamicD ?></p>
<p>Does this work? <?php echo "$result";?></p>
<form method="post">
<fieldset>
<label for="drill">Can you solve it?</label>
<input type="text" name="drill" id="drill" maxlengh="2" placeholder="<?php echo $placeholder ?>" required="true" />
</fieldset>
<button type="submit" name="check">Check</button>
</form>
</body>
</html>
Basically it generates "random" number, insert it as a drill, and then let the user submit his answer. The problem is that the answer is always "NO"*.
I tried to separate the condition to this:
if($drill > $dynamicD) { $result = "bigger" }
elseif ($drill < $dynamicD) { $result = "smaller" }
and so on - but can't understand the logic of the $result (sometime bigger, sometime smaller, but i ALWAYS enter $dynamicD...).
What am i doing wrong here???
EDIT:
As the comments points, every time the page submit it generates new numbers. The first time the code execute is the only time that correct answer would be equal to the numbers that display. After the first submit there is a gap.
Note for future readers: The above code extracted and simplified from bigger and much complex system. Not something that anyone would want to just copy-paste.
The solution i choose was to store the dynamically created vars on a session and re-declare if the answer is correct.
Would love to hear about other ways (not client side).

form post action into php var

Im in this page: website.php?page=5 and in this page I have this form:
<form method="POST" action="website.php?page=<?php echo $pagenumber; ?>">
<input type="text" name="goto" />
<input type="submit" name="submit" value="goto" />
</form>
If I write something like 3 into the text field and press the goto button (if isset.... my php code get the number and upload into the $pagenumber var)
But the new page isn't the website.php?page=3 what I want. The new page is website.php?page= (there is no number) .and if I press again then goes it to the right page.
I think in the first press when i do the $pagenumber isn't declared. Only when i press second.
How can I fix it? I must use this way i cant use session, cookie etc.
<?php if(isset($_POST['submit']))
{
$kitkeresek = $_POST['goto'];
$becsuletemw = "SELECT * FROM adatok WHERE nev = '$kitkeresek'";
$becsuletem2w = mysql_query($becsuletemw);
while( $becsuletem3w = mysql_fetch_array($becsuletem2w))
$becsuletemw = $becsuletem3w["becsulet"];
$valllamiw = mysql_query("SELECT becsulet FROM adatok WHERE becsulet > '$becsuletemw' ");
$rowsw = mysql_num_rows( $valllamiw );
$kitkeresekw = $rowsw + 1 ;
$intvizsgalat= $kitkeresekw/10;
if (is_int($intvizsgalat))
{ $pagenumber = $intvizsgalat - 1 ; }
else
{$pagenumber = floor($kitkeresekw/10); } ;
}
?>
When you do this :
$intvizsgalat= $kitkeresekw/10;
$intvizsgalat is float, even if the result is int, because it is the result of a division.
You can try var_dump($intvizsgalat) to confirm
try something like this:
$floatParts = $intvizsgalat - floor(intvizsgalat);
if ($floatParts == 0) {
//
} else {
//
}

jQuery show div in PHP While loop

I am having a bit of problems trying to show an information in a div tag using jQuery inside the PHP while loop.
My code looks like this:
$i=1;
while($pack = mysql_fetch_array($packs))
{
$pricepack = $price * $pack['refcount'];
$pricepack = number_format($pricepack,2);
if($users > $pack['refcount'] ) {
$contents .= "
<a class='refbutton' style='text-decoration:none;' onclick=\"document.rent.refs.value='{$pack['refcount']}';document.rent.submit(); return false;\" >{$pack['refcount']}</a>
<div id='refinfo' style='display:none;'>
<span style='font-size:18pt;font-weight:bold;' id='refprice'></span><br />
<span style='color:#D01F1E;'>You don't have enough funds for this package.</span>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.refbutton').hover(
function() {
$('#refinfo').show();
$('#refprice').text(\"$\"+\"$pricepack\");
},
function() {
$('#refinfo').hide()
}
);
});
</script>
";
$i++;
}
}
The problem is that the code is generating a div next to each anchor element. This will cause this when the mouse hovers:
What I am trying to obtain is this on every button hover:
As you can see in the second picture, there isn't any design errors or mix-ups. How can I obtain this?
Thank you.
You need to start by cleaning up your code. You only need one refinfo div, and only one javascript block. The only thing in your loop should be the refbutton, and that tag should contain all the values needed for the javscript hover and click events to do their business. Look into HTML5 custom data attributes http://html5doctor.com/html5-custom-data-attributes/
Something more like this should work and provide a sounder basis on which to debug layout issues if any remain.
<?php
$i=1;
while($pack = mysql_fetch_array($packs)) {
$pricepack = $price * $pack['refcount'];
$pricepack = number_format($pricepack,2);
if($users > $pack['refcount'] ) {
$contents .= "
<a class=\"refbutton\" data-pricepack=\"{$pricepack}\" style=\"text-decoration:none;\" >{$pack['refcount']}</a>";
$i++;
}
}
?>
<div id="refinfo" style="display:none;">
<span style="font-size:18pt;font-weight:bold;" id="refprice"></span><br />
<span style="color:#D01F1E;">You don't have enough funds for this package.</span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.refbutton')
.bind('mouseover',function(event) {
$('#refinfo').show();
$('#refprice').text($(this).data("pricepack"));
})
.bind('click',function(event) {
document.rent.refs.value=$(this).text();
})
.bind('mouseout', function(event){
$('#refinfo').hide();
})
;
});
</script>

pop up window based on php input value

I have an edit_ticket_check.php page like this:
<form name="frm" action="edit_ticket_asso.php" method="post" onSubmit="return validt(frm)">
<table frame=box align=center bgcolor="9966FF">
<b><h2>Enter Ticket Information</h2></b>
</table>
</form>
Then some boxes like this:
<tr><td><font color="BLACK">Ticket Status:</font></td>
<td>
<?php
echo "<select name=\"ticket_status\">";
echo "<option size =15 selected>Select</option>";
if(mysql_num_rows($result4))
{
while($row = mysql_fetch_assoc($result4))
{
echo "<option>$row[ticket_status]</option>";
}
}
else {
echo "<option>No Status Present</option>";
}
?>
</td>
The input values go to a second edit_ticket.php page where it enters the value in a MySQL database.
if($_POST['submit']=="Insert")
{
$ticket_no=$_POST['ticket_no'];
if ( #$_SESSION[username] == 'admin')
{
$assigned_to=$_POST['emp_name'];
}
else
$assigned_to = #$_SESSION[userid][0];
$reassigned_to_team=$_POST['reassigned_to_team'];
$ticket_status=$_POST['ticket_status'];
$comment=$_POST['comment'];
if($ticket_no!=NULL&&$assigned_to!=NULL&&$comment!=NULL)
{
$query1=mysql_query("select count(ticket_no) as total from ticket where ticket_no='$ticket_no';");
$row = mysql_fetch_array($query1);
if ($row["total"]>"0")
{
$query2="UPDATE ticket SET ticket.assigned_to='$assigned_to', ticket.reassigned_to_team='$reassigned_to_team', ticket.ticket_status='$ticket_status', ticket.comment='$comment' WHERE ticket.ticket_no='$ticket_no'";
$result1=mysql_query("$query2");
}
}
}
Now after this I want that if ticket status = 'pending' then a new pop up window will come up and take a time value and then update the time value of ticket by the newly entered time.
For the pop up window I have this code:
<html>
<body>
<p>Click the button to add resolution time with pending ticket.</p>
<button onclick="myFunction()">Pending</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction()
{
var x;
var name=prompt("Please enter Resolution Time","2099-12-31 23:59:59");
if (name!=null)
{
x="resolution_time " + name ;
document.getElementById("demo").innerHTML=x;
}
}
</script>
Now I can't connect these two pages and I'm also unable to pass the values from the new pop up window to old window.
How can i do this?
Since PHP is a server-side language so it can't be dyanamic like JavaScript which is a client-side language, do you have any better idea to do this other way round?
thank you..
Your landing page (the one that your form processor page, edit_ticket.php should redirect to when it's finished) should accept a parameter in the url. Based on that, you can write javascript in the new page to decide whether or not to open the pending window.
For example: at the end of edit_ticket.php,
header("location: landing.php?pending=1");
and then in pending:
<?php
if (isset($_GET['pending']) && $_GET['pending'] ==1){
?><script type='text/javascript'>
window.open('yourpopup.html');
<?php
}
?>

jQuery and PHP search suggestion script

I have a PHP and jQuery script that creates search result suggestions from a text box. However, when you type something in the text box, delete it and try making a different query, no suggestions are displayed. Why could this be?
Here is a copy of my webpage code:
<script type="text/JavaScript">
function lookup(inputString){
if (inputString.length==0){
$('#suggestions').hide();
} else{
$.post("suggestions.php",{
queryString: "" + inputString + ""},
function(data){
$('#suggestions').html(data);
});
}
}
</script>
<form>
<input type="text" size="30" onkeyup="lookup(this.value);">
<div id="suggestions"></div>
</form>
Here is a copy of my PHP code:
<p id="searchresults"><?php
$db=new mysqli('localhost','username','password','database');
if(isset($_POST['queryString'])){
$queryString=$db->real_escape_string($_POST['queryString']);
if(strlen($queryString)>0){
$query = $db->query("SELECT * FROM search s WHERE name LIKE '%" . $queryString . "%'");
if($query){
while ($result = $query ->fetch_object()){
echo '<a href="'.$result->name.'">';
$name=$result->name;
echo ''.$name.'';
}
}
}
}
?></p>
Thanks in advance, Callum
You hide but don't show again.
change your callback function to:
function(data){
$('#suggestions').html(data).show();
}
or a fadeIn() for added cuteness ;)
Add $('#suggestions').show() inside of your else statement.

Categories