I have written a php script that is used to download any youtube video, it works on 2 buttons, first button is used to create the formats and second button starts downloading,
I want that if i press, first button, 2nd button, automatically did its work, and start download on single click,
Here is the code for first button,
<button id="videoDownloadButton" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" onClick="downloadVideo();">MP4 Quality</button>
Javssript on that button is....
function downloadVideo() {
var videoID = player.getVideoData()['video_id']
document.getElementById("downloadFormatList").innerHTML="Please wait. Processing...";
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp3 = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("downloadFormatList").innerHTML=xmlhttp3.responseText;
}
}
//keyword = keyword.replace(/ /g, '%2B');
xmlhttp3.open("GET","TMB/download.php?videoid="+videoID,true);
xmlhttp3.send();
}
and after that PHP script will work and produce that second button, Which is a HTML tag,
if(isset($_REQUEST['videoid'])) {
$my_id = $_REQUEST['videoid'];
if(strpos($my_id,"https://youtu.be/") !== false)
{
$my_id = str_replace("https://youtu.be/","",$my_id);
}
}
<?php
//$my_video_info = 'http://www.youtube.com/get_video_info?&video_id='. $my_id;
$my_video_info = 'http://www.youtube.com/get_video_info?&video_id=' . $my_id . '&asv=3&el=detailpage&hl=en_US'; //video details fix *1
$my_video_info = curlGet($my_video_info);
/* TODO: Check return from curl for status code */
$thumbnail_url = $title = $url_encoded_fmt_stream_map = $type = $url = '';
parse_str($my_video_info);
?>
<?php
$my_title = $title;
$cleanedtitle = clean($title);
if (isset($url_encoded_fmt_stream_map)) {
/* Now get the url_encoded_fmt_stream_map, and explode on comma */
$my_formats_array = explode(',', $url_encoded_fmt_stream_map);
if ($debug) {
echo '<pre>';
print_r($my_formats_array);
echo '</pre>';
}
} else {
echo '<p>No encoded format stream found.</p>';
echo '<p>Here is what we got from YouTube:</p>';
echo $my_video_info;
}
if (count($my_formats_array) == 0) {
echo '<p>No format stream map found - was the video id correct?</p>';
exit;
}
/* create an array of available download formats */
$avail_formats[] = '';
$i = 0;
$ipbits = $ip = $itag = $sig = $quality = '';
$expire = time();
foreach ($my_formats_array as $format) {
parse_str($format);
$avail_formats[$i]['itag'] = $itag;
$avail_formats[$i]['quality'] = $quality;
$type = explode(';', $type);
$avail_formats[$i]['type'] = $type[0];
$avail_formats[$i]['url'] = urldecode($url) . '&signature=' . $sig;
parse_str(urldecode($url));
$avail_formats[$i]['expires'] = date("G:i:s T", $expire);
$avail_formats[$i]['ipbits'] = $ipbits;
$avail_formats[$i]['ip'] = $ip;
$i++;
}
echo '<div class="format_list">';
echo '<br>';
echo '<table>';
/* now that we have the array, print the options */
for ($i = 0; $i < 1; $i++) {
if ($config['VideoLinkMode'] == 'direct' || $config['VideoLinkMode'] == 'both')
?> <tr><td><?php
echo $avail_formats[$i]['type'];
?></td>
<td><small>(<?php
echo $avail_formats[$i]['quality'];
?>)</small> </td>
<td><small><span class="size"><?php
echo formatBytes(get_size($avail_formats[$i]['url']));
?></span></small>
</td>
<td><a href="<?php
echo $avail_formats[$i]['url'];
?> '&title='<?php
echo $cleanedtitle;
?>'" class="downloadButton">Record Video</a></td>
</tr>
<?php
}
?>
This is the button, that i want to did its work automatically
<a href="<?php
echo $avail_formats[$i]['url'];
?> '&title='<?php
echo $cleanedtitle;
?>'" class="downloadButton">Record Video</a>
try this instead of your second button code.
header('Location:' .$avail_formats[$i][url]. '&title=' .$cleanedtitle);
Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user:
$( "#foo" ).on( "click", function() {
alert( $( this ).text() );
});
if($("required-button").length>0){
$( "#foo" ).trigger( "click" );
}
here is the reference to reference of my example
Related
I'm trying to delete data from database but when I click on delete button then its delete the first row not where I'm clicking.
my PHP Code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
And this is my ajax code:
function deleteproduct(){
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
http.onreadystatechange = function(){
if(http.readyState == 4 && http.status == 200){
document.getElementById("alerts").innerHTML = http.responseText;
}
}
var delid = document.getElementById("productid").value;
var file = "assets/php/addproduct_deletedata.php";
var senddata = "productid="+delid;
http.open("POST",file,true);
http.setRequestHeader("content-type","application/x-www-form-urlencoded");
http.send(senddata);
}
I want that when I click on delete button then it delete the row where I clicked not others.
FIRST OF ALL YOU CANNOT ASSIGN THE SAME ID TO MORE THAN ONE ELEMENTS ON A PAGE.
The browser won't mind it but It makes the HTML invalid. You can use class attribute for this purpose.
You can validate your HTML online here
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
For your requirement, you can use anchor tag instead of using a form with a hidden input field to reduce the DOM size and call the function on click and pass the function the productId as a parameter.
Here's the code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr id='row-".$rows["id"]."'>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><a href='#' onclick='return deleteproduct(".$rows["id"].")'>Delete</a></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
JavaScript:
function deleteproduct( delId ){
var tableRowId = 'row-'+delId;
// you got delId and tableRowId to remove the table row
// do ajax stuff here...
return false;
}
Let me know how it went.
because its "value" and not "vlaue" ;)
input type='hidden' id='productid' vlaue='".$rows["id"]."'
2.
you're iterating over your resultset and printing out an input-field with the id "productid".
In your code, EVERY column has the SAME id. Thats the reason your javascript isn't working as expected. An ID needs to be unique.
You need to send the value (product id) as the function parameters. Do it like this:
<input type="hidden" onclick="deleteproduct(this.value)" value="$yourRowId"/>
or
<input type="hidden" onclick="deleteproduct($yourRowId)" />
and this is how you can retrieve the value in JS:
<script type="text/javascript">
function deleteproduct(id)
{
alert(id); // your product ID
}
</script>
I have a file, where i use a button, called MP4 Quality, When i click on that button, it opens a pop-up and ask for another button to press, to download the video, There is javascript with first button, and when it clicks, open the pop-up and give the second button, from where PHP is used, now i want it to download on single click,
Following is the code for first button...
<button id="videoDownloadButton" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" onClick="downloadVideo();">MP4 Quality</button>
and when it click, the following javascript code will run
function downloadVideo() {
var videoID = player.getVideoData()['video_id']
document.getElementById("downloadFormatList").innerHTML="Please wait. Processing...";
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp3 = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("downloadFormatList").innerHTML=xmlhttp3.responseText;
}
}
//keyword = keyword.replace(/ /g, '%2B');
xmlhttp3.open("GET","TMB/download.php?videoid="+videoID,true);
xmlhttp3.send();
}
and after that PHP code will run, PHP code is this...
if(isset($_REQUEST['videoid'])) {
$my_id = $_REQUEST['videoid'];
if(strpos($my_id,"https://youtu.be/") !== false)
{
$my_id = str_replace("https://youtu.be/","",$my_id);
}
}
<?php
//$my_video_info = 'http://www.youtube.com/get_video_info?&video_id='. $my_id;
$my_video_info = 'http://www.youtube.com/get_video_info?&video_id=' . $my_id . '&asv=3&el=detailpage&hl=en_US'; //video details fix *1
$my_video_info = curlGet($my_video_info);
/* TODO: Check return from curl for status code */
$thumbnail_url = $title = $url_encoded_fmt_stream_map = $type = $url = '';
parse_str($my_video_info);
?>
<?php
$my_title = $title;
$cleanedtitle = clean($title);
if (isset($url_encoded_fmt_stream_map)) {
/* Now get the url_encoded_fmt_stream_map, and explode on comma */
$my_formats_array = explode(',', $url_encoded_fmt_stream_map);
if ($debug) {
echo '<pre>';
print_r($my_formats_array);
echo '</pre>';
}
} else {
echo '<p>No encoded format stream found.</p>';
echo '<p>Here is what we got from YouTube:</p>';
echo $my_video_info;
}
if (count($my_formats_array) == 0) {
echo '<p>No format stream map found - was the video id correct?</p>';
exit;
}
/* create an array of available download formats */
$avail_formats[] = '';
$i = 0;
$ipbits = $ip = $itag = $sig = $quality = '';
$expire = time();
foreach ($my_formats_array as $format) {
parse_str($format);
$avail_formats[$i]['itag'] = $itag;
$avail_formats[$i]['quality'] = $quality;
$type = explode(';', $type);
$avail_formats[$i]['type'] = $type[0];
$avail_formats[$i]['url'] = urldecode($url) . '&signature=' . $sig;
parse_str(urldecode($url));
$avail_formats[$i]['expires'] = date("G:i:s T", $expire);
$avail_formats[$i]['ipbits'] = $ipbits;
$avail_formats[$i]['ip'] = $ip;
$i++;
}
echo '<div class="format_list">';
echo '<br>';
echo '<table>';
/* now that we have the array, print the options */
for ($i = 0; $i < 1; $i++) {
if ($config['VideoLinkMode'] == 'direct' || $config['VideoLinkMode'] == 'both')
?> <tr><td><?php
echo $avail_formats[$i]['type'];
?></td>
<td><small>(<?php
echo $avail_formats[$i]['quality'];
?>)</small> </td>
<td><small><span class="size"><?php
echo formatBytes(get_size($avail_formats[$i]['url']));
?></span></small>
</td>
<td><a href="<?php
echo $avail_formats[$i]['url'];
?> '&title='<?php
echo $cleanedtitle;
?>'" class="downloadButton">Record Video</a></td>
</tr>
<?php
}
?>
after the click on first button, this button will appear,
Record Video
Now i want it on single click, how can i do...??
Try adding this in the bottom of your pop-up page:
<script>
window.location = '<?php echo $avail_formats[$i]['url']; ?>';
</script>
According to your php code, the "second button" term is not correct.
You might have a count of second buttons which have different quality.
This is why the php code and second click exist.
If you want to download your video immediately, replace your foreach loop in php code
foreach ($my_formats_array as $format) {
parse_str($format);
$avail_formats[$i]['itag'] = $itag;
$avail_formats[$i]['quality'] = $quality;
$type = explode(';', $type);
$avail_formats[$i]['type'] = $type[0];
$avail_formats[$i]['url'] = urldecode($url) . '&signature=' . $sig;
parse_str(urldecode($url));
$avail_formats[$i]['expires'] = date("G:i:s T", $expire);
$avail_formats[$i]['ipbits'] = $ipbits;
$avail_formats[$i]['ip'] = $ip;
$i++;
}
on the
if (isset($my_formats_array[0])) {
parse_str($my_formats_array[0]);
header("Location: " . urldecode($url) . '&signature=' . $sig);
die();
}
And get rid of other unnecessary things
Hello, I want to be able to change only part of the div in my view i
have tried to write the codes but they are not working perfectly. how
it works is when i click the button it suppose to sent the value to a
js then using js to sent data to the controller.
SCRIPT:
function getValue(datas){
alert(datas) ;
var mydiv = datas;
$.Ajax({
type:"post",
url:<?php echo base_url('/mama/load_view/');?>
data:{"mydiv":mydiv},
success:function(data){
$('#mang_server').html(data);
}
});
}
PHP:
foreach($student_prof as $row){
$gen = "GeneralInformation";
echo '<input type="submit" value="GeneralInformation" class="btn btn-primary active" name="general" id="submit" onclick="getValue("'.$gen.'")">';
echo '</div>';
}
The Controller code
public function load_view(){
$data1 = $this->input->post('mydiv');
if($data1 == "GeneralInformation"){
$this->load->view('student/profile_view');
}
else {
$this->load->view('student/profile_view');
}
}
use jquery load function.
function getValue(datas){
var mydiv = datas;
url = "<?php echo base_url('/mama/load_view');?>/" + mydiv;
$('#mang_server').load(url);
}
Controller
public function load_view($data1){
if($data1 == "GeneralInformation"){
$this->load->view('student/profile_view');
}
else {
$this->load->view('student/profile_view');
}
}
to load your view in div using ajax use echo
echo $this->load->view('student/profile_view', $data1, TRUE);
public function load_view(){
$data1 = $this->input->post('mydiv');
if($data1 == "GeneralInformation"){
echo $this->load->view('student/profile_view', $data1, TRUE);
}
else {
echo $this->load->view('student/profile_view', $data1, TRUE);
}
}
change you php code to this
foreach($student_prof as $row){
$gen = "GeneralInformation";
$output .='<div>';
$output .= '<input type="submit" value="GeneralInformation" class="btn btn-primary active" name="general" id="submit" onclick="getValue("'.$gen.'")">';
$output .= '</div>';
}
echo $output;
I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket
I have a Ajax PHP Show More feature like youtube and Live search scripts but I can't get them to work together. For example my live search works but then the show more feature doesn't work with it on the search results and when I use the show more then the live search doesn't work.
They don't seem to be messing with each other. Can anyone help me out? I am new to this website so I will try my best to show my code and explain it.
INDEX.PHP
<?php
include_once("connect.php");
$sql = "SELECT COUNT(*) FROM database";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
$item_per_page = 3;
$total_rows = mysqli_fetch_array($query);
$pages = ceil($total_rows[0]/$item_per_page);
?>
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Show More Scripted
$(document).ready(function() {
var track_click = 0;
var total_pages = <?php echo $pages; ?>;
$('#news-table-wrap').load("showmore_search.php", {'page':track_click}, function() {track_click++;});
$(".load_more").click(function (e){
$(this).hide();
$('.animation_image').show();
if(track_click <= total_pages){
$.post(showmore_search.php',{'page': track_click}, function(data) {
$(".load_more").show();
$("#news-table-wrap").append(data);
$("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);
$('.animation_image').hide();
track_click++;
}).fail(function(xhr, ajaxOptions, thrownError){
alert(thrownError);
$(".load_more").show();
$('.animation_image').hide();
});
if(track_click >= total_pages-1){
$(".load_more").attr("disabled", "disabled");
}
}
});
});
// Live Search Script
function searchNews(value) {
$.post("showmore_search.php", {newsResult:value}, function(data){
$("#news-table-wrap").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="search" id="search" class="search-box" onKeyUp="searchNews(this.value)" placeholder="Search News">
<table id="news-table-wrap" class="news-table-wrap" cellpadding="0" cellspacing="0">
</table>
<div align="center">
<div class="load_more" id="load_more_button">Show More</div>
<div class="animation_image" style="display:none;"><img src="/files/ajax-loader.gif"></div>
</div>
</body>
</html>
SHOWMORE_SEARCH.php
<?php
include_once("connect.php");
$newsResult = $_POST['newsResult'];
$item_per_page = 3;
$page_number = $_POST["page"];
$position = ($page_number * $item_per_page);
$sql = "SELECT * FROM database WHERE headline LIKE '%$newsResult%' OR post LIKE '%$newsResult%' ORDER BY date DESC LIMIT $position, $item_per_page";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)){
$headline = $row['headline'];
$author = $row['author'];
$date = $row['date'];
$post = $row['post'];
$name = $row['name'];
echo "<tr class='news-preview-wrap'>";
echo "<td><div class='news-preview-content'><div class='news-preview-headline'><a href='news_post?name=".$name."'>".$headline."</a></div>
<div class='news-preview-date'>Written by ".$author." on ".$date."</div>
<div class='news-preview-post'>".$post."</div></div>
<div class='news-more'><a href='news_post?name=".$name."'>Read More</a></div></td>";
echo "</tr>";
} else {
echo "<div class='search-error'>No search results were found...</div>";
}
?>
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
})
;
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}