I'm building a webshop for a project at university. I have a search bar in header, navigation bar on the left. In both cases I send data with Ajax (from search bar a keyword, from navs a category and subcategory). Ajax response is a PHP script that prints products based on category and subcategory or keyword. At the end of it it prints pagination links and select element for number of products per page. If I submit a keyword or click on a nav, it prints out results fine, but if I then change the page or a number on select element (another Ajax request) , the results default because category/subcategory or keyword are not being sent anymore. This is the code for search bar request:
$("#searchButton").click(function(){
$("#searchBar").blur();
var keyword=$("#searchBar").val();
$.ajax({
type:"GET",
url:"print.php",
data: { keyword:keyword }
}).done(function (data){
$('#content').html(data);
return false;
});
});
and this is the code for pagination:
$(document).on("change", "#paginationSelect", function(){
var productsPerPage=$("#paginationSelect").val();
$.ajax({
type:"GET",
url:"print.php",
data: { productsPerPage:productsPerPage }
}).done(function (data){
$('#content').html(data);
return false;
});
});
I'm wondering what's the best way to save the data sent by last Ajax request so that I can send it again while changing pagination stuff. Should I change the PHP file or Ajax requests and what's the best way to do it?
Edit:
This is the PHP file:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
mysql_connect("localhost", "root", "") or die("Couldn't connect to database.");
mysql_select_db("webshop") or die("Couldn't select a database.");
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
if(isset($_GET["category"]) & isset($_GET["subcategory"])){
$category=$_GET["category"];
$subcategory=$_GET["subcategory"];
$query="SELECT * from proizvod where kategorija='".$category."' and podkategorija='".$subcategory."'";
}
else if(isset($_GET["keyword"])){
$keyword=$_GET["keyword"];
$query="SELECT * from proizvod where ime like '%".$keyword."%'";
}
else{
$query="SELECT * from proizvod";
}
$result=mysql_query($query);
$numProducts=mysql_num_rows($result);
if(isset($_GET["productsPerPage"]))$productsPerPage=$_GET["productsPerPage"];
else if($numProducts>=10) $productsPerPage=10;
else $productsPerPage=$numProducts;
if(isset($_GET["pageNum"]))$pageNum=$_GET["pageNum"];
else $pageNum=1;
if(isset($keyword)) print "<div id=\"keywordMessage\" class=\"col-lg-12\">Traženi pojam: ".$keyword."</div>";
if(mysql_num_rows($result)==0) print "<div class=\"col-lg-12\">Nema rezultata</div>";
for($i=0;$i<($pageNum-1)*$productsPerPage;$i++){
$row=mysql_fetch_array($result, MYSQL_ASSOC);
}
for($i=($pageNum-1)*$productsPerPage;$i<$pageNum*$productsPerPage;$i++){
$row=mysql_fetch_array($result, MYSQL_ASSOC);
print("<div class=\"col-lg-6\">
<table class=\"article\">
<tr><td colspan=\"2\"><img src=\"images/".$row["id"].".jpg\" class=\"imgArticle\"/></td></tr>
<tr><td colspan=\"2\"><b>".$row['ime']."</b></td></tr>
<tr><td>Kategorija: </td><td>".$row['kategorija']."</td></tr>
<tr><td>Opis: </td><td>".$row['opis']."</td></tr>
<tr><td>Cijena: </td><td>".$row['cijena']." kn</td></tr>
</table>
</div>");
}
print("<div class=\"col-lg-12\" id=\"paginationControl\">
<span class=\"col-lg-4\">
Prikazano: ".(($pageNum-1)*$productsPerPage+1)."-".$pageNum*$productsPerPage."/".$numProducts."
</span>
<span class=\"col-lg-4\" id=\"pageNumbers\">");
if($productsPerPage!=0){
for($i=1;$i<=ceil($numProducts/$productsPerPage);$i++){
if($i==$pageNum) print($i."   ");
else print("<a class=\"pageNumControl\" href=\"#\">".$i."</a>");
}
}
print("</span>
<span class=\"col-lg-4\">Proizvoda po stranici:
<select id=\"paginationSelect\">
<option value=\"10\" "); if($productsPerPage==10){ print("selected");} print(">10</option>
<option value=\"20\" "); if($productsPerPage==20){ print("selected");} print(">20</option>
<option value=\"30\" "); if($productsPerPage==30){ print("selected");} print(">30</option>
<option value=\"50\" "); if($productsPerPage==50){ print("selected");} print(">50</option>
</select>
</span>
</div>");
mysql_free_result($result);
?>
You could use jQuery .Data(). But please note, if you refresh the entire page, the .data() information is lost.
So, without have more code this is the best example I could come up with. I am storing the search information in the #searchBar's data, then retrieving it on pagination change.
$("#searchButton").click(function() {
var $sb = $("#searchBar"),
keyword = $sb.val();
$sb.data({
prevKeyword: keyword
}).blur();
$.ajax({
type: "GET",
url: "print.php",
data: {
keyword: keyword
}
}).done(function(rtnData) {
$('#content').html(rtnData);
return false;
});
});
$(document).on("change", "#paginationSelect", function() {
var productsPerPage = $("#paginationSelect").val(),
previousKeyword = $("#searchBar").data('prevKeyword');
// Do something with the keyword
console.log(previousKeyword);
$.ajax({
type: "GET",
url: "print.php",
data: {
keyword: previousKeyword,
productsPerPage: productsPerPage
}
}).done(function(rtnData) {
$('#content').html(rtnData);
return false;
});
});
Related
I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.
I'm working on a little PHP MYSQL chat app. I need to refresh the data in the chat window every few seconds without reloading the entire page. I know I have to use Javascript or Jquery to accomplish this but I don't really know them good enough.
Below is the code that creates the chat window and populates it from the database.
Thanks so much, appreciate the help.
<textarea id="screen" name="screen" style="width:100%;height:300;resize:none">
<?php
$sql="SELECT * FROM `$tbl_5` WHERE advertid='$advertid' ORDER by id ASC";
$result = mysqli_query($dbconn, $sql);
while ($row2=mysqli_fetch_row($result))
{
echo $row2[5]."\n";
}
?>
</textarea>
EDIT: My attempt using AJAX
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
sendRequest();
function sendRequest(){
$.ajax({
type: 'POST',
url: '/chatrefresh.php',
data: parameters,
success: function(response){
$('#chatwindow').html(response);
},
error: function(response){
alert(response);
},
complete: function() {
setInterval(sendRequest, 5000);
}
});
};
});
</script>
<table id="chatwindow" name="chatwindow"><tr><td></td></tr></table>
Chatrefresh.php
<textarea id="screen" name="screen" style="width:100%;height:300;resize:none">
<?php
include_once('session.php');
include('config.php');
$advertid=$_SESSION['advertid'];
$sql="SELECT * FROM `$tbl_5` WHERE advertid='$advertid' ORDER by id ASC";
$result = mysqli_query($dbconn, $sql);
while ($row=mysqli_fetch_row($result))
{
echo $row[5]."\n";
}
?>
</textarea>
Having trouble deleting a record from mysql databse using ajax/jquery. Issue I am having is that it does not delete from the database but does delete from the list. What am I doing wrong here?
Here is my code:
jQuery(document).ready(function(){
$(".deleteitem").click(function(){
var parent = $(this).closest('li');
var id = parent.attr('id');
$.ajax({
type: "POST",
data: "id=" +id,
URL: "delete.php",
success: function(msg){
$('#'+id).remove();
}
});
});
});
My php file delete.php:
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$id = $_POST['id'];
if (isset($id)) {
$query = "DELETE FROM img_slider WHERE id = '$id'";
mysqli_query($query) or die('Error, insert query failed');
}
The HTML markup:
<li id='".$row['id']."'>
<a href='#' class='deleteitem'><img src='../img/delete.png'></a>
</li>
Firstly test to make sure calling the delete file with a valid id works. The javascript below should work fine.
<script type="text/javascript">
<!--
$(function() {
$('.deleteitem').click(function(e) {
e.preventDefault();
var id = $(this).parent('li').attr('id');
$.get('delete.php',{ id: id}).done(function(data) {
if(data=='Error, insert query failed') {
// dont delete from list
alert('Failed to delete '+id);
} else {
//delete from list
$('#'+id).remove();
alert('Deleted '+id);
}
});
});
});
//-->
</script>
EDIT: updated the script to assist parent-id handling.
Are you able to say where the error is coming from? Most modern browsers should offer you some insight into what line, or what section the error is occurring on.
The script above should replace all your javascript.
I've got some JQuery which monitors a form. Basically, for every keyup it will call a php file to search the database.
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2) {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
});
This works fine, however it filters the results in #searchresultdata depending on the query. The only thing is, if nothing is in the form, I want it to load everything - the user should not have to click the form to do this, therefore a .blur would not work.
The PHP file is simply:
if(isset($_GET['keyword'])){}
you should handle a [*] search on your server
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
if (faq_search_input =='') faq_search_input ='*';
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2 || faq_search_input=='*') {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
$("#faq_search_input").trigger('keyup');
});
If you're loading all results initially, then could you not just store this in a JavaScript array and filter the results with JavaScript? This would save you a HTTP request on every key press, which can only be good for speed and resource usage of your site.
EDIT: Sample.
<?php
$sql = "SELECT `title` FROM `your_table`";
$res = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($res)) {
$rows[] = $row['title'];
}
echo '<script>var data = ' . json_encode($rows) . ';</script>';
?>
<form method="post" action="">
<fieldset>
<input type="text" name="search" id="faq_search_input" />
</fieldset>
</form>
<script>
// I presume you're using jQuery
var searchInput = $('#faq_search_input');
var searchResults = $('#searchresultdata');
var tmpArray = data;
// add all results to results div
$.each(data, function(key, val) {
searchResults.append('<li>' + val + '</li>');
});
searchInput.attr('placeholder', 'Begin typing to search');
searchInput.keyup(function() {
// hide any <li> in your #searchresultdata that don't match input
});
</script>
I don't know what is in your serverresponse variable, so I can only guess what gets put into the searchresultdata <div>. You'll also need to modify the SQL query to match your table and column names.
Contents of searchdata.php
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%'";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$result=mysql_query($query, $database_connection) or die(mysql_error());
if($result){
if(mysql_affected_rows($database_connection)!=0){
while($row = mysql_fetch_object($result)){
?>
<div class="hold-cont">
<div class="holder">
<div class="image-hold" >
<img class="image-icon" src="<? echo $deviceimg.($row->Image); ?>"/>
</div>
</div>
<div class="device-name devicename-txt"><? echo($row->Manufacturer. ' ' .$row->Model); ?></div>
</div>
<?
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';
}
}
}else {
echo 'Parameter Missing';
}
I am having some trouble with my jquery. I am not sure if it is connecting to doc.php but I am not getting anything inserted into my database.
I have an insert command in doc.php which I know is working.
I'm trying to create a way to update prices in a database, from doc.php, that searches out items one at a time.
The doc.php is searching by var, then updating in the same page.
The foreach loop function then, takes the var one by one, sends them to the doc.php page that then searches by var and updates into the database.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die (mysql_error());
$sql = "SELECT var FROM table";
$query = mysql_query($sql) or die (mysql_error());
while ($result = mysql_fetch_array($query)) {
$variable = array($result['var']);
foreach ($variable as $variable1) {
?>
<script src="jquery-1.7.2.min.js" type="text/javascript">
$(function() {
var valueToSend = '<?php echo $variable1; ?>';
$.ajax({
url: "doc.php",
dataType: "json",
type: "POST",
data: { Variable: valueToSend },
success: function (m) {
alert(m);
},
error: function (e) {
alert("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
}
}
?>
First of all, what do you want to do with this code? If you want to read & write to db using php, ajax call is unnecessary. If you want to practice ajax & php you need to read some howto because your code is somewhere strange ;). This is nice collection of tutorials for jQuery and some for PHP read some and practice.