Ajax, PHP/MySQL search request keeps crashing - php

I have built a mobile application for Android using Phonegap, the data is stored within a MySQL table and the data is fetched via ajax request, this works fine however, when trying to create a search query to filter the data literally after typing 2 letters my application is crashing? - Any idea?
<!-- Remote call to Server -->
<script type="text/javascript">
// Call the server for content
$.ajax({
url: 'https://www.ppl-support.co.uk/ratchetserver/getdata', // URL -> load the data
crossDomain: true,
success: function(data){
$(".list").html(data).show();
}
});
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='') {
$.ajax({
type: "POST",
url: "https://www.ppl-support.co.uk/ratchetserver/newgetdata.php",
data: dataString,
cache: false,
success: function(data) {
$(".list").html(data);
}
});
}else{
$.ajax({
url: 'https://www.ppl-support.co.uk/ratchetserver/getdata.php', //load data
success: function(data){
$(".list").html(data);
}
});
}
return true;
});
});
function Reload(){
location.reload(); // Reload the page onclick
}
// Send user to Home Screen
function Home(){
location.assign('index.html');
}
</script>
</head>
<body class="is-ump"><br><br>
<div id="users">
<!-- Load abbreviations markup -->
<ul class="table-view" style="padding-left:0px;" id="theList">
<ul class="list" style="padding-left:0px;">
<li class="table-view-cell media" >
<a class="navigate-right">
<img class="media-object pull-left" src="img/P1.png" style="width:50px;" alt="" >
<div class="media-body">
<h4 align="center">
Downloading contents, please wait...
</h4>
</div>
</a>
</li>
</ul>
</ul>
<!-- Search functionality --->
<div class="ump">
<div class="ump-widget-container">
<div class="ump-widget ump-search-widget ump-hidden" id="ump-search-widget">
<form action="#" method="POST">
<input class="search" style="font-family:exo;" value="" placeholder="Search Abbreviations.." /><!--
<button class="ump-button" style="color:white;background:#ffda00;font-family:exo;font-shadow:white;">Search</button> -->
</form>
</div>
<div class="ump-clear"></div>
</div>
<!-- navigational panel -->
<div class="ump-bar">
<div class="ump-clear">
Pocket Pilot
<div class="ump-icons">
<i class="fa fa-envelope"></i>
<i class="fa fa-search"></i>
<div class="ump-clear"></div>
</div>
</div>
<div class="ump-overlay"></div>
</div>
<nav>
<div class="ump-nav-container">
<div class="ump-header">
<img src="img/1.png" alt="" class="ump-header-background-image">
<a href="#" title="UMP - Ultra Menu Pro">
<img src="img/logo.png" alt="">
</a>
</div>
<div class="ump-nav">
<ul class="ump-default">
<li>
<a><h4 onclick="Home()">Home</h4></a>
</li>
<li>
<a><h4>About</h4></a>
</li>
</ul>
<ul class="ump-social">
<li>
<i class="fa fa-facebook"></i>
</li>
<li>
<i class="fa fa-google-plus"></i>
</li>
<li>
<i class="fa fa-twitter"></i>
</li>
<li>
<i class="fa fa-instagram"></i>
</li>
<li>
<i class="fa fa-youtube-play"></i>
</li>
</ul>
</div>
</div>
<a class="ump-toggle">
<i class="fa fa-times ump-close"></i>
<i class="fa fa-bars ump-open"></i>
</a>
</nav>
</div>
</div>
</body>
And this is my PHP file (Search)
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
$str = '';
if($_POST['search'] && $_POST['search'] != "") {
$q = $_POST['search'];
include_once('dbconnection.php');
$sql = "SELECT * FROM `co_abbreviation` WHERE `acronym` LIKE = '%$q%'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$str .= "<div class='card' style='border-radius:0px;'>
<ul class='table-view'>
<ul class='list' style='padding-left:0px;'>
<li class='table-view-cell media'>
<a class='navigate-right'>
<div class='media-body'>
<h3 class='name'>
<b>
".$row['acronym']."
</b>
</h3>
<h4 class='born' style='color:#1e404e;'>
<i>
".$row['meaning']."
</i>
</h4>
<p class='mean' align='left'>
CAA Source: ".$row['source']."
</p>
</div>
</a>
</li>
</ul>
</ul>
</div>";
}
}
echo $str;
?>
App screen

You may just return the array in a formatted form(ex. in json format) and return it. When you create the HTML code in server and send it to client, then create the HTML code in JS function in client. Sending HTML code takes a lot bigger time than sending the result array( as you said there is approximately 1k data) .Moreover it will creates more data traffic also.

Related

Ajax returns only first result in a PHP while loop

I am building a chat application and when I click the available users list (which is generated from a php while loop) the chat area is supposed to carry the information of that user and previous chat history (if any). However, for some reason ajax onclick keeps returning just the first user on the list into the chat area.
I have tried different methods of getting each user's id from the users-list (a separate php file) and passing it to the active-chat area (another php file) using ajax. I believe I'm missing something or doing something wrong. Every suggestion or different approach will be very much appreciated.
User's List PHP Code:
<?php
// this php is an include in another php file if certain conditions are met.
while($users = mysqli_fetch_assoc($sql)){
// the list of users generated into the home page
$output .= '<li id="contact" class="get-user-chats">
<input type="hidden" id="getUserId" value="'.$users['user_id'].'"/>
<span class="avatar"><img src="'.$users['display_pic'].'" height="42" width="42" alt="Generic placeholder image" />
<span class="'.$users['online_status'].'"></span>
</span>
<div class="chat-info flex-grow-1">
<h5 class="mb-0">'.$users['full_name'].'</h5>
<p class="card-text text-truncate">
This is just a test message to see if the truncate feature works
</p>
</div>
<div class="chat-meta text-nowrap">
<small class="float-end mb-25 chat-time">4:14 PM</small>
<span class="badge bg-danger rounded-pill float-end">3</span>
</div>
</li>';
}
?>
Ajax Code:
$(document).ready(function(){
$('.users-list').click(function(){
//users-list is a class from the home page where the users list displays in a div
var $container = $(this).find(".get-user-chats");
var chatid = $container.find("#getUserId").val();
$.ajax({
url: './code/active-chat.php',
type: 'POST',
data: {
chatuserid: chatid
},
success: function(response){
//alert(chatid)
$('.get-active-chat-user').html(response);
},
dataType: 'text'
});
});
});
active-chat.php
<?php
// active-chat.php
session_start();
define('BASEPATH', true);
require "../../../../private/engine.php";
$chatid = $_POST['chatuserid'];
$sql = "SELECT * FROM users WHERE user_id = '{$chatid}'";
$fetchdata = mysqli_query($connection, $sql);
while($sub = mysqli_fetch_array($fetchdata)){
?>
<header class="chat-header">
<div class="d-flex align-items-center">
<div class="sidebar-toggle d-block d-lg-none me-1">
<i data-feather="menu" class="font-medium-5"></i>
</div>
<div class="avatar avatar-border user-profile-toggle m-0 me-1">
<img src="<?php echo $sub['display_pic']; ?>" alt="avatar" height="36" width="36" />
<span class="<?php echo $sub['online_status']; ?>"></span>
</div>
<h6 class="mb-0"><?php echo $sub['full_name'] ?></h6>
</div>
<div class="d-flex align-items-center">
<i data-feather="phone-call" class="cursor-pointer d-sm-block d-none font-medium-2 me-1"></i>
<i data-feather="video" class="cursor-pointer d-sm-block d-none font-medium-2 me-1"></i>
<!-- <i data-feather="search" class="cursor-pointer d-sm-block d-none font-medium-2"></i> -->
<div class="dropdown">
<button class="btn-icon btn btn-transparent hide-arrow btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i data-feather="more-vertical" id="chat-header-actions" class="font-medium-2"></i>
</button>
<div class="dropdown-menu dropdown-menu-end" aria-labelledby="chat-header-actions">
<a class="dropdown-item" href="#">View Contact</a>
<a class="dropdown-item" href="#">Mute Notifications</a>
<a class="dropdown-item" href="#">Block Contact</a>
<a class="dropdown-item" href="#">Clear Chat</a>
<a class="dropdown-item" href="#">Report</a>
</div>
</div>
</div>
</header>
<?php } ?>
Screenshot of the Chat Screen:
Chat Screen
I have researched on related topics but none of them seems to address my specific issue.

Jquery accordion does not collapse

the issue I encounter is a Jquery accordion which does not collapse anymore after I have invoked an AJAX request. The testpage (index.php) I created has 2 main items called Header 1 and Header 2. Header 1 had 4 subitems called item 1...4 - Header 2 has also 4 subitems called item 5...8.
When clicking the Header items, the accordion opens up and the sub-items appears, so far so good.
Once the header-item is clicked an AJAX GET request is launched towards a second page which is called get_data.php. On that page, I get all the data I need to fill in into a DIV on my index.php page with the ID responsecontainer. As such I can get data without posting on my initial page.
the issue I encounter is that - once the data is displayed on the index.php page - I'm not able anymore to close the Header items of the accordion
A test can be seen at this location : https://smultocht.be/test/
This is how the accordion looks :
<section class="hero">
<div class="container">
<div class="row">
<div class="col-lg-3">
<div class="panel-group accordion" id="group_accordion">
<div class="panel panel-default">
<!-- 1 -->
<div class="panel-heading" style="border-width:0px;border-radius:5px; background-color:#CCC">
<h4 class="panel-title" style="color:#FFF">
<a class="main_item" data-toggle="collapse" data-parent="#accordion" href="#collapse1" id="1">header 1</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse">
<ul class="list-group">
<li class="list-group-item">Item 1</li>
<li class="list-group-item">Item 2</li>
<li class="list-group-item">Item 3</li>
<li class="list-group-item">Item 4</li>
</ul>
</div>
<!-- 2 -->
<div class="panel-heading" style="border-width:0px;border-radius:5px; background-color:#CCC">
<h4 class="panel-title" style="color:#FFF">
<a class="main_item" data-toggle="collapse" data-parent="#accordion" href="#collapse2" id="2">header 2</a>
</h4>
</div>
<div id="collapse2" class="panel-collapse collapse">
<ul class="list-group">
<li class="list-group-item">Item 5</li>
<li class="list-group-item">Item 6</li>
<li class="list-group-item">Item 7</li>
<li class="list-group-item">Item 8</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-lg-9" style="border-color:#000; border-width:0px; border-style:solid;">
<div class="hero__search" >
<div class="hero__search__form">
<form action="#">
<input id="hello" type="text">
<button type="submit" class="site-btn">Zoek</button>
</form>
</div>
<div class="hero__search__phone" >
<div class="hero__search__phone__icon">
<i class="fa fa-phone"></i>
</div>
<div class="hero__search__phone__text" style="padding-top:5px;">
<h4></h4>
</div>
</div>
</div>
<div class="hero__text" id="responsecontainer" style="border-color:#000; border-width:0px; border-style:solid;">
</div>
</div>
</div>
</div>
</div>
</div>
</section>
The AJAX request looks like this :
<script type="text/javascript">
$('.main_item').on('click', function () {
$id = ($(this).attr('id'));
$.ajax({ //create an ajax request
type: "GET",
url: "gather_data.php?id="+$id,
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
</script>
the get_data.php page looks like this :
<?php
$group_item_nr = $_GET['id'];
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<?
$art_result = mysqli_query($_SESSION['db'], "SELECT * FROM artikel_tabel WHERE artikel_actief='1' AND artikel_hoofd_tabel_id = ".$group_item_nr." ORDER BY artikel_benaming ASC");
//Show all articles in responsecontainer on index.page
$num_mysql_rows = mysqli_num_rows($art_result);
$counter = 0;
echo('<div class="set-bg row" style="border-color:#000; border-width:0px; border-style:solid; text-align:center;">');
while ($counter < $num_mysql_rows)
{
$art_array = mysqli_fetch_array($art_result);
echo('
<div class="art_item col-md-2 col-sm-3" id="'.$art_array['artikel_id'].'"
style="padding:2px; margin:5px; text-align:center; border-color:#CCC; border-width:1px; border-style:solid; position: relative;">
<img src="fotos_artikelen/'.$art_array['artikel_foto_url'].'">
<br>'.
utf8_decode($art_array['artikel_benaming']."<br>"."(".$art_array['artikel_hoeveelheid']." ".$art_array['artikel_eenheid']).')
'.$is_reclame_yes_no.'
</div>');
$counter++;
}
echo('</div>');
?>
<body>
</body>
any help will be gratefull appreciated, txs

Simple food tracker using ajax and jquery

I am trying to implement a simple food tracker for my restaurant website which updates food status. What I want to do is that whenever I update the food status for an order, the icon becomes green for that stage. I need to perform a query from my website and get the food status value and update it without page refresh. How do I do that? Please help me, it is very important
<div class="progressbar">
<ul >
<li>
<img style="width:130px;height:130px;margin-left:100px"src="foodStatusImages/waiting.png">
<i style="margin-left:150px" class="fa fa-check" id="iconstatus"></i>
<h5 style="margin-left:80px;display: inline-block;white-space: nowrap;">Waiting for
confirmation</h5>
</li>
<li>
<img style="width:130px;height:130px;margin-left:200px;"src="foodStatusImages/confirmed.png">
<i style="margin-left:250px" class="fa fa-check" id="iconstatus"></i>
<h5 style="margin-left:190px;display: inline-block;white-space: nowrap;">Order Confirmed</h5>
</li>
<li>
<img style="width:130px;height:130px;margin-left:350px"src="foodStatusImages/preparing.png">
<i style="margin-left:400px"class="fa fa-check" id="iconstatus"></i>
<h5 style="margin-left:350px;display: inline-block;white-space: nowrap;">In preparation...
</h5>
</li>
<li>
<img style="width:130px;height:130px;margin-left:530px;"src="foodStatusImages/Ready.png">
<i style="margin-left:590px" class="fa fa-check" id="iconstatus"></i>
<h5 style="margin-left:520px;display: inline-block;white-space: nowrap;">Your order is
ready</h5>
</li>-->
<ul>
</div>
<script>
$(document).ready(function()
{
$(function()
{
$("ul li:nth-child(1) i.fa").css("background","#148e14");
var icons = $('#iconstatus'); //does not work
console.log(icons);
$.ajax({
url:"action.php",
data:{icons:icons},
cache:false,
method:"POST",
sucess:function(result)
{
}
});
}
);
});
</script>

Laravel posting and comments , i cannot comment after i created a new post using ajax

when i refresh the page using the browser everything is working fine i could still comment and i could also add new post but the problem is when i create a new post(which means a post like a facebook post) i cannot comment anymore on any post. here is my Homeview :
<div class="All-Post-Display" id="PostRefresh">
<div class="container">
#foreach($latest as $late)
<div class="row">
<div class="col-md-5 col-md-offset-2">
<div class="outside-pannel">
<div class="person">
<img src="/styleimage/facebook.jpg">
<h2>{{$late->user->name}} {{$late->user->lastname}}</h2><br>
<h4>{{$late->created_at->diffForHumans()}}</h4>
</div>
<div class="body-of-post">
<p>{{$late->body}}</p>
</div>
<div class="like-comment-share">
<form>
<ul>
<li><i class="fa fa-thumbs-up"></i>Like</li>
<li><i class="fa fa-comments-o"></i>Comment</li>
<li><i class="fa fa-share"></i>Share</li>
</ul>
</form>
</div>
<div class="comment-section" >
<div class="total-likes">
<h3>3 likes your post</h3>
</div>
<div class="comment-form">
#foreach($late->comments as $comment)
<div class="display-comments">
<div class="comment-img">
<img src="/styleimage/facebook.jpg">
</div>
<div class="comment-container">
<div class="comment-content">
<a name="postername" href="#">rd</a> <span></span>
<div class="reply-like">
<ul>
<li>Like</li>
<li>Reply</li>
<li><h6>just now</h6></li>
</ul>
</div>
</div>
</div>
</div>
#endforeach
<div>
<div class="commenting-container">
<img src="/styleimage/facebook.jpg">
<textarea rows="1" id="comment-body{{$late->id}}" name="body" placeholder="Write a comment..."></textarea>
<input type="text" name="commentable" id="posting-id{{$late->id}}" value="{{$late->id}}" style="display: none;">
<div class="emojis">
<ul>
<li><i class="fa fa-smile-o"></i></li>
<li><i class="fa fa-camera-retro"></i></li>
<li><i class="fa fa-bookmark"></i></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$( document ).ready(function() {
$('#comment-body{{$late->id}}').keypress(function (e) {
if (e.which == 13) {
var comment = $('#comment-body{{$late->id}}').val();
var postCommentedId = $('#posting-id{{$late->id}}').val();
$.ajax({
url: '/comment',
type: 'post',
data: {'commentable_id':postCommentedId,'body':comment,'_token':$('input[name=_token]').val()},
success: function (data) {
console.log('success');
$('#comment-body{{$late->id}}').val(null);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('errorThrown');
}
});
}
});
});
</script>
#endforeach
</div>
</div>
</div>
{{csrf_field()}}
<script>
$( document ).ready(function() {
$('#ButtonPost').click(function (event) {
var thebody = $('#bodyPost').val();
$.ajax({
url: 'index',
type: 'post',
data: {'body':thebody,'_token':$('input[name=_token]').val()},
success: function (data) {
$('#PostRefresh').load(location.href + ' #PostRefresh');
$('#bodyPost').val(null);
}
});
});
});
</script>
after running this AJAX at the bottom the AJAX inside my #foreach doesn't work , id="PostRefresh" is gonna be refreshed when i make new post. im also using id="{{id of post}}" to make them unique in every post, Please Help Thank you...
Instead of this
$('#ButtonPost').click(function (event) ...
Try to use
$(document).on('click','#ButtonPost',(function (event) ...
Here the problem is, once you create new DOM then you don't have id of new element created to your jquery id not working.
But with this code you will get jquery code linked to every element of if #buttonPost.

playing songs with jplayer from mysql database using php and jquery ajax

I am developing a music streaming site and I am using jplayer to play songs on my site. I customized jplayer to better suit my site.
I created a database for my site and now want to play songs from database by using jplayer.
since I only know little about php and mysql, I can't figure it out how to do that? some how I am able to play a random song from a msql table with jplayer
but I want to generate links of each mp3 file and echoed them in an html lists so when get clicked loaded into jplayer and playing! simple is that!
getsong.php
<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
include_once "ez_sql_core.php";
include_once "ez_sql_mysql.php";
$db = new ezSQL_mysql('root','','amr','localhost');
$song = $db->get_row("SELECT * FROM tracks ORDER BY RAND() LIMIT 1");
$artist = $song->album_id;
$songname = $song->name;
$track_url = $song->track_url;
$separator = '|';
echo $track_url.$separator.$artist.$separator.$songname;
}
?>
jplayer-interface.php
> <script type="text/javascript">
$(document).ready(function(){
$("#jquery_jplayer_1").jPlayer({
ready: function () {
var data = $.ajax({
url: "../js/getsong.php",
async: false
}).responseText;
var string = data.split('|');
$(this).jPlayer("setMedia", {
mp3: string[0]
});
$('#artist').html(string[1]);
$('#songname').html(string[2]);
},
ended: function (event) {
var data = $.ajax({
url: "../js/getsong.php",
async: false
}).responseText;
var string = data.split('|');
$(this).jPlayer("setMedia", {
mp3: string[0]
});
$('#artist').html(string[1]);
$('#songname').html(string[2]);
},
swfPath: "../js/jPlayer",
supplied: "mp3, ogv, m4v, oga",
useStateClassSkin: true,
autoBlur: false,
smoothPlayBar: true,
keyEnabled: true,
audioFullScreen: false,
enableRemoveControls: false,
autoPlay: false,
loopOnPrevious: false,
shuffleOnLoop: true,
displayTime: 'slow',
addTime: 'fast',
removeTime: 'fast',
shuffleTime: 'slow'
});
});
</script>
>
>
>
> <footer class="j-player">
<div id="jp_container_1">
<div class="jp-type-playlist">
<div class="playlist_items jp-playlist"><!--start jp-playlist-->
<ul>
<!-- The method Playlist.displayPlaylist() uses this
unordered list -->
<li> </li>
</ul>
</div><!--end jp-playlist-->
<div class="lyrics-contents jp-lyrics"><!--start jp-lyrics-->
<ul>
<!-- The method Playlist.displayPlaylist() uses this unordered
list -->
<li> </li>
</ul><!--end jp-lyrics-->
</div>
<div id="jplayer_N" class="jp-jplayer hide"></div>
<div class="jp-gui">
<div class="jp-video-play hide">
<a class="jp-video-play-icon">play</a>
</div>
<div class="jp-interface">
<div class="jp-controls">
<div><div id="jquery_jplayer_1" class="jp-jplayer">
</div> <!--#jquery_jplayer_1--></div>
<div class="previous-button"><a class="jp-previous"><i
class="arcd-controller-jump-to-start"></i></a></div>
<div class="play-button">
<a class="jp-play"><i class="flaticon-play62"></i>
</a>
<a class="jp-pause hid"><i class="flaticon-pause35">
</i></a>
</div>
<div class="next-button"><a class="jp-next"><i
class="arcd-controller-next"></i></a></div>
<div class="hide"><a class="jp-stop"><i class="fa fa-
stop"></i></a></div>
<div class="jp-current-time"></div>
<div class="jp-progress hidden-692">
<ul class="jp-details">
<li class="jp-title" id="songname" aria-
label="title"> </li>
<li class="jp-artist" id="artist" aria-
label="artist"> </li>
</ul>
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
<div class="jp-duration"></div>
<div class="volume-speaker">
<a class="jp-mute" title="mute"><i class="arcd-
music1432"></i></a>
<a class="jp-unmute hid" title="unmute"><i
class="arcd-mute10"></i></a>
</div>
<div class="jp-volume">
<div class="jp-volume-bar vol-bar-bg">
<div class="jp-volume-bar-value vol-bar-seek">
</div>
</div>
</div>
<div class="shuffle-button">
<a class="jp-shuffle" title="shuffle"><i
class="arcd-shuffle shuffle-on"></i></a>
<a class="jp-shuffle-off hid" title="shuffle off"><i
class="arcd-shuffle shuffle-off"></i></a>
</div>
<div class="repeat-button">
<a class="jp-repeat" title="repeat"><i class="arcd-
loop repeat-on"></i></a>
<a class="jp-repeat-off hid" title="repeat off"><i
class="arcd-loop repeat-off"></i></a>
</div>
<div class="playlist-button jp-toggles">
<a class="show-playlist" title="playlist-on"><i
class="arcd-lyrics1"></i></a>
</div>
<div class="lyrics-button">
<a class="jp-show-lyrics" title="Lyrics"><i
class="arcd-note25"></i></a>
</div>
<div class="hide">
<a class="jp-full-screen" title="full screen"><i
class="fa fa-expand"></i></a>
<a class="jp-restore-screen" title="restore screen">
<i class="fa fa-compress"></i></a>
</div>
</div><!--/ .jp-controls1-->
</div><!--/ .jp-interface-->
</div><!--/ .jp-gui-->
<div class="jp-no-solution hide">
<span>Update Required</span>
To play the media you will need to either update your browser to
a recent version or update your <a
href="http://get.adobe.com/flashplayer/"
target="_blank">Flash plugin</a>.
</div>
</div><!--/ .jp-type-playlist-->
</div><!--/ .jp_container_1-->
</footer>
Any help will be really appreciated!

Categories