Change text area content using AJAX - php

Newbie in AJAX here, I want to requery or select *from again on my database on button click and change the textarea content? How do I do that using AJAX.
Here is my code.
<textarea id="CKUPDATEALL">
<?php
$result = mysqli_query($con,"SELECT *FROM home WHERE ANNOUNCE_TYPE='WELCOMENOTE' ORDER BY ANNOUNCE_NUMBER DESC limit 0,1");
while($row = mysqli_fetch_array($result))
{
echo $row['ANNOUNCEMENTS'];
}
?>
</textarea>

No you can set your php file to check against different variables being passed in the Ajax call. The in the Ajax response success look for the different variables that were defined in the php file. So you might call Ajax.php for 10 different Ajax calls and responses. Just have to set it up properly.
$(document).ready(function(){
$("#my_button").on('cick',function(){
Var name = $('#thisinputid').val();
$.ajax({
url: "getval.php",
type: "POST",
data : { fullname : name },
success: function(data) {
$("#CKUPDATEALL").val(data);
}
});
});
Then in the php file check for $_post['fullname'].

Say this is your button
<input type="button" id="my_button" value="Cick"/>
Ajax
$(document).ready(function(){
$("#my_button").on('cick',function(){
$.ajax({
url: "getval.php",
type: "POST",
data : {'type':'textarea'},
success: function(data) {
$("#CKUPDATEALL").val(data);
}
});
});
And in getval.php
<?php
if(isset($_POST['type']) && trim($_POST['type']) == 'textarea'){
$result = mysqli_query($con,"SELECT * FROM home WHERE ANNOUNCE_TYPE='WELCOMENOTE' ORDER BY ANNOUNCE_NUMBER DESC limit 0,1");
while($row = mysqli_fetch_array($result)){
echo $row['ANNOUNCEMENTS'];
}
die();
}
?>

Try $.ajax() like,
$(function(){
$.ajax({
url:'get_announcement.php',
type:'POST',
data:{type:'announcement'},
success:funtion(d){
$('#CKUPDATEALL').val(d);
}
});
});
get_announcement.php
<?php
// type is announcement
if(isset($_POST['type']) and $_POST['type']=='announcement'){
$result=mysqli_query($con,"SELECT * FROM home WHERE
ANNOUNCE_TYPE='WELCOMENOTE' ORDER BY ANNOUNCE_NUMBER DESC limit 1");
while($row = mysqli_fetch_array($result)){
echo $row['ANNOUNCEMENTS'];
}
echo 'not found';
}
?>

Related

Dependent Drop Down Jquery option list JSON error

Guys I am very new in Jquery and Json trying, I am trying to create a Dependent Option list with Jquery but it's not working. I am expecting your kind help.
here is my HTML code..
<div class="form-group">
<label for="categoriesId">
Categories</label>
<select class="form-control" id="categoriesId" name="categoriesId">
<option selcted="">Select
Categories</option>
<?php
getCat();
?>
</select>
</div>
and my fetchProductDta.php page code is here
<?php
require_once 'db_connect.php';
if(isset($_POST['cid'])){
$sql = "SELECT product_id, product_name
FROM product WHERE categories_id = '". $cid
."'";
$result = $connect->query($sql);
while($product = $productData->fetch_array()) {
echo "<option value='".$product['product_id']."'>
".$product['product_name']."</option>";
}
}
?>
My Jquery Code is here
$(document).ready(function () {
$("#categoriesId").change(function () {
var cid = $("#categoriesId").val();
$.ajax({
url: 'fetchProductData.php',
method: 'POST',
data: 'cid' + cid
.done(function (product) {
console.log(product);
product = json.parse(product);
product.forEach(function (products) {
$('#product').appned();
});
});
});
In your jquery you have mistakes , first of all you are getting html response from server as Nigel Ren said.So,to get that you don't need to use json.parse .Also i didn't find any id with name product in your html code.and there is no appned function in jquery .So,make below changes in your code to make it worked.
$(document).ready(function () {
$("#categoriesId").change(function () {
var cid = $("#categoriesId").val();
$.ajax({
url: 'fetchProductData.php',
method: 'POST',
data: {cid : cid },
success:function(data){
$("#product").html(data);//here response from server will be display in #product
}
});
});

Refresh textarea every few seconds that populates from MYSQL

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>

php jquery mysql - load more button in another loadmore in loop

I have two files for a load more button for posts but I can't use another load more for posts replay
this is one load more code:
file index.php:
<script>
$(document).ready(function() {
var comco = 2;
var offset = 0;
$("#btn1").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco: comco, offset: offset }
})
.done(function(msg) {
$("#comnts").append(msg);
});
offset = offset + comco;
});
$("#btn1").trigger("click");
});
</script>
<div id="comnts"></div>
<button id="btn1">load more</button>
and this is the ld_comco.php file:
$comnco=$_POST['comnco'];
$offset=$_POST['offset'];
$qq="SELECT * FROM tbl_users_posts limit $offset, $comnco";
$qr=mysqli_query($conn,$qq);while($fff=mysqli_fetch_assoc($qr)){
echo $fff['post'];}
I do change the ld_comco.php file for add repost button inside the posts:
$comnco=$_POST['comnco'];
$offset=$_POST['offset'];
$qq="SELECT * FROM tbl_users_posts limit $offset, $comnco";
$qr=mysqli_query($conn,$qq);while($fff=mysqli_fetch_assoc($qr)){
$sbid=$fff['id'];
echo $fff['post'];
?>
<script>
$(document).ready(function() {
var recomco = 2;
var sbid = <?php echo $sbid?>;
var reoffset = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_recomco.php",
data: { recomnco: recomco, reoffset: reoffset }
})
.done(function(msg) {
$("#recomnts").append(msg);
});
reoffset = reoffset + recomco;
});
$("#btn2").trigger("click");
});
</script>
<?php }?>
<div id="recomnts"></div>
<button id="btn2">load more re-pst</button>
and add a ld_recomco.php file:
$recomnco=$_POST['recomnco'];
$reoffset=$_POST['reoffset'];
$sbid=$_POST['sbid'];
$qq2="SELECT * FROM re_pst WHERE subid=$sbid limit $reoffset, $recomnco";
$qr2=mysqli_query($conn,$qq2);while($fff2=mysqli_fetch_assoc($qr2)){
echo $fff2['id'];
echo $fff2['remsg'];
}
This dosen't work properly, how can I do this?
Edit:
i have the user posts in a while-loop like this:
$qq="SELECT * FROM tbl_users_posts";
$qr=mysqli_query($conn,$qq);while($fff=mysqli_fetch_assoc($qr)){
$sbid=$fff['id'];
echo $fff['post'];}
i can add -load more- button to post but i cant add -load more- button to posts replay
in some code like this:
$qq="SELECT * FROM tbl_users_posts limit 10";
$qr=mysqli_query($conn,$qq);while($fff=mysqli_fetch_assoc($qr)){
$sbid=$fff['id'];
echo $fff['post'];?>
<?php $qq2="SELECT * FROM re_pst WHERE subid=$sbid";
$qr2=mysqli_query($conn,$qq2);while($fff2=mysqli_fetch_assoc($qr2)){
echo $fff2['remsg'];
}}

Multiple Ajax requests Colliding

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." &nbsp ");
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;
});
});

Jquery: If form is blank load this query

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';
}

Categories