I googled abit and found a script, to reload a division.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
setInterval("$('#downshow').load('message.php');", 5000);
</script>
here downshow is my division where contents need to be refreshed. its like chat app, and messages between me and my friend needs to continoulsy reload.
My division downshow is something like below...
$getmessages= mysql_query("SELECT * FROM pvt_messages WHERE (user_from='$active_username' && user_to='$username') || (user_from='$username' && user_to='$active_username') ORDER BY id ASC ") or die(mysql_error());
while ($row = mysql_fetch_assoc($getmessages ))
{
$body = $row['msg_body'];
$date_send = $row['date'];
$opened = $row['opened'];
$whosent= $row['user_from'];
$whoreceived= $row['user_to'];
$seen=$row['opened'];
/////////////////////////////////////////////////////
$get_user_info = mysql_query("SELECT * FROM users WHERE (username='$whosent')");
////////////////////////////////////////////////////
$get_info = mysql_fetch_assoc($get_user_info);
$profilepic_info = $get_info['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./images/default_pic.jpg";
}
else
{
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
echo "
<div style='float: left;padding-top:5px; padding-left:20px;'>
<img src='$profilepic_info' height='50' width='40'>
</div>
<div style='margin-left:50px;padding-top:5px;'>
<a href='$whosent' style='color:black'> $whosent</a> $body
</div></br>
<div style=' margin-left:30px;'>
<font size='2px'>sent on: $date_send</font>
<br />
</div>
<hr />
";
}
I would have kept the content of this division in some other page i.e. message.php and then include it just as
<div id='downshow' style='bottom:0px;'class='see_message'>
<?php include("message.php"); ?>
</div>
But if i do this, there will be lots of problem like, session_start() issues, variable $active_username ll be obtained easily by $active_username=$_SESSION['username'] bt couldnt obtain varibale $username in message.php.
so instead of including the division content as "message.php". i want that code to be in main php file itself.
so want to as instead of
setInterval("$('#downshow').load('message.php');", 5000);
how can i use
setInterval("$('#downshow').load('????????????');", 5000);
load the division itself?????????????
Thankyou in advance :)
Try this..
setInterval(function(){ $('#downshow').load('message.php');
}, 5000);
This is not the best way to do this
You should look at AJAX and create a template for the HTML.
This way you can send information to the server (such as requesting items since a particular time, or from a particular 'room') and only send back the important data (send it back as JSON) and populate your template.
This will reduce traffic and load on your server and will reduce latency in your application as you are only sending back the important data - not the HTML to go with it!
Additionally use classes for each of the items instead of inline styles as it will make your code easier to maintain.
Related
I have made use of the AJAX live search tutorial as seen on https://codeforgeek.com/2014/09/ajax-search-box-php-mysql/. This is dependent on typeahead.min.js as well as JQuery and Bootstrap.
The problem is, that it is not always getting the href link (it's buggy), as well as the fact that upon clicking on a result, it fills in the input field with the entire href link, which I do not want. I only want to navigate to that page. I feel like my issue may be JQuery / JS related. Please see the screenshot below.
I have modified the PHP to use the PEAR extension for DB calls, and extended it to include links in the returned results.
Below is some of the PHP file for processing the search.
$key=$_GET['key'];
$search_results_array = array();
$sql = "SELECT * FROM `Product_Data` WHERE `Product_Name` LIKE '%{$key}%' OR `Product_Tags` LIKE '%{$key}%' ORDER BY `Product_Sequence` ASC";
$q = $db->query($sql);
if (PEAR::isError($q)) {
showError ($q);
exit;
}
$numRows = $q->numRows();
while ($row = $q->fetchRow()) {
$product_name = $row['Product_Name'];
$product_id = $row['Product_ID'];
$search_results_array[] = "<a href='/index.php?page=purchase&product_id=$product_id' class='livesearch_link'>$product_name</a>";
}
print json_encode($search_results_array);
The HTML:
<div class="col-md-6">
<div class="panel panel-default">
<div class="bs-example">
<input type="text" name="typeahead" class="typeahead tt-query" autocomplete="off" spellcheck="false" placeholder="Search">
</div>
And the JQuery (Which is where I suspect the issue may lie):
<script>
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote: '/manage/process_ajax_search.php?key=%QUERY',
limit : 10,
});
});
$(document).on('click','.tt-suggestion .livesearch_link',function(e){
e.preventDefault();
var href = $(this).attr('href');
window.location.replace(href);
return false;
});
Please help me!
I have a list of scientific publications displayed on a website and would like to load additional content as the user arrives at the end of a list of 10 publications, and presses a button to load another 10 publications.
I make an Ajax call to load the next 10 publications
I am trying to display html code that is echo-ed from php script but I cannot appear to display the html. In the console, I am getting '1' as a value for my HTML. I do not understand:
1. why I am getting the value of '1';
2. Also, is it good practice to echo HTML to be displayed via javascript?
JS (AJAX call):
var resp = xmlhttp.responseText;
var respArray = resp.split('|');
var response = respArray[1];
var publicationList = respArray[0];
var currentHTML = document.getElementById('showPubs').innerHTML;
if(response == '1'){
console.log('more publications available');
var currentHTML = document.getElementById('showPubs').innerHTML;
document.getElementById('showPubs').innerHTML += publicationList;
}else{
document.getElementById('showPubs').innerHTML += '<div id="noMorePub">No more publications</div>';
}
PHP:
$recentPublications .= '
<div id="pub'.$articleID.'" class="pub20">
<div class="divImg">'.$avatarPathHTML.'</div>
<div class="contentPub">
<div class="datepub">
<div class="fullName"><a class="sfullNme" href="2profile.php?username='.$articleUsername.'">'.$fullname.'</a></div>
<div class="date">'.$submitDate.'</div>
</div>
<div class="divLink">
'.$articleTitle.'
</div>
<div class="authorString">'.$author_string.'</div>
</div>
<hr class="pubSeparator">
</div>
';
echo $recentPublications.'|1';
I guess better idea is not use this dirty hack
echo $recentPublications.'|1';
and
var respArray = resp.split('|');
var response = respArray[1];
var publicationList = respArray[0];
if(response == '1'){
You can just check length of response. if length of response is equal 0 bytes then other publications are not available.
The good practice is to separate concerns. Therefore, in your example, server-side script should only provide data to be displayed (ex. JSON via), and frontend should make AJAX call to specific endpoint.
I have a gif with a loading animation.
in my code I use mysqli_query() to fetch data from a server.
Because, the table is very large it takes time until I see the results.
I am trying to show a "loading" animation while the PHP function is fetching data.
This is my PHP code,
if (isset($_GET['variable'])) {
$_SESSION['variable'] = $_GET['variable'];
$results = mysqli_query($mysqli,"select q1.variable, t3.label, q1.numvalue, description, num_cases from (select variable, numvalue, count(variable) as num_cases from nhws.num_all_{$_SESSION['country']} where variable = '{$_SESSION['variable']}' group by variable, numvalue) q1 inner join (select * from nhws.luvalues where source = '{$_SESSION['country']}' and variable = '{$_SESSION['variable']}') t2 on q1.numvalue=t2.numvalue inner join (select * from nhws.luvariables where source = '{$_SESSION['country']}' and variable = '{$_SESSION['variable']}') t3 on q1.variable=t3.variable;");
echo "<h5>Counts</h5>";
echo '<div id="container" ><img src="ajax-loader.gif" alt="Searching" /></div>';
if ($results->num_rows > 0) {
echo "<table><tr><th>Variable</th><th>label</th><th>Numvalue</th><th>Description</th><th>Num Cases</th></tr>";
// output data of each row
while($row = $results->fetch_assoc()) {
echo "<tr><td>" . $row["variable"]. "</td><td>" . $row["label"]. "</td><td>" . $row["numvalue"]. "</td><td>" . $row["description"]. "</td><td>" . $row["num_cases"]. "</td></tr>";
}
echo "</table>";
} else {echo "0 results";}
}
I am assuming that the function mysqli_query() is the one that takes time because, in my browser it says in the bottom right "waiting for (IP address of the server)"
I tried several methods with AJAX but it did not work while the website was waiting for the server. It did work when the website was waiting for itself and not for a query.
This is my script,
<script>
function makeLoadingGifDisappear() {
document.getElementById('myLoadingGif').style.display = 'none';
}
</script>
And this my HTML code which I replaced before my PHP code,
<img src="ajax-loader.gif" id="myLoadingGif">
Any suggestions?
Thanks!
Try putting a check in a while loop which will check (mysqli_num_rows($result)==0) which means that if table has returned any data back. But, use an if statement inside loop so that you don't put loader everytime loop runs. Once you get back the data the loop going to quit and you can proceed with data.
:D
Place the animated image tag in a div positioned with CSS to cover the portion of the screen you wish to cover and make sure it is the first thing loaded into the page body:
<div class="animated">
<img src="ajax-loader.gif" id="myLoadingGif">
</div>
You can now hide the animated div when the page finishes loading by adding the following just before the closing body tag (shown for reference):
<script type="text/javascript">
window.onload = function() {
document.getElementsByClassName('animated').style.display = 'none';
};
</script>
</body
So, what I did to solve this problem is to hide the GIF with <img src="ajax-loader.gif" id="myLoadingGif" style= "display: none;">
And where the user needs to pick and send the variable to make the query run I added onchange='showDiv()'
Which activates the function below,
function showDiv(){
document.getElementById('myLoadingGif').style.display = "block";
}
And after the query finishes to run the GIF automatically switched to display: none; which is perfect!
I have a php array which I displaying with a while loop and it gets the data from a sql database, at the moment everything in the array appears instantly, but would it be possible to get them to display with a half second delay? Would i have to use Javascript?
You can put a <div> around your array, like this:
<div id="myElementID" style="display:none;">
MY ARRAY
</div>
and it will not be visible. With Javascript you can make it visible after, for instance, a 1000 milliseconds, with:
function showElement(id)
// make hidden element visible
{
document.getElementById(id).style.display = "";
}
window.setTimeout("showElement('myElementID')",1000);
No other libraries are needed for this.
If you need to do multiple rows you can wrap a <div> around each row, or use the <tr> tag if your're using tables, like this:
<div id="myRow1" style="display:none;">
ROW 1
</div>
<div id="myRow2" style="display:none;">
ROW 2
</div>
<div id="myRow3" style="display:none;">
ROW 2
</div>
.......
<div id="myRowN" style="display:none;">
ROW N
</div>
And in your script:
for (i = 1; i <= N; i++) {
window.setTimeout("showElement('myRow"+i+"')",500);
}
You would still need the showElement() function.
If you want to do this in your PHP you can call a javascript function with a timeout. Make sure you included the jQuery libary first en defined the method to call. It will be something like the code below. You can change the $delay variable for more or less delay between the different elements.
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
function makeVisible(id, delay)
{
setTimeout(function(){
$('#'+id).fadeIn();
}, delay);
}
</script>
<?php
$delay = 500;
$array = array(1,2,3,4,5);
$counter = 0;
foreach($array as $value)
{
$uniqueId = 'aClassName'.$counter;
echo '<div style="display:none;" id="'.$uniqueId.'">'.$value.'</div>';
echo '<script>makeVisible("'.$uniqueId.'", '.($counter++*$delay).')</script>';
}
?>
Yes you need javaScript. Just use jQuery. Use CSS to hide the content container before the page loads and show the content (fadeIn()) after the desired time interval using setTimeout().
Here's a fiddle : http://jsfiddle.net/tnzqv4fx/
A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.