i have probleme when i load a page with.laod() or $.ajax()
it load only the content like static page
at page1.php i have function getStats() as php and i have a <div id="loadpage">
and at page2.php i when use the getStats() and page2.php is load in the <div id="loadpage">
so i have include all the file i need at page2.php but it start become too slow
so i tried load page with a include and when any checkbox checked it will load the content again like
$("#loadpage").text("<?php include "page2.php"?>");
but you can imagine what i get when my page2.php have a table with 300 line data
so i give up this solution
and my plan is every time i check a checkbox it will reset my table
$func=getStats($_POST['statut']);
<div id="loadpage">
echo "$func";
</div>
actuel code : // it load but really slow
[page1.php]
<div id="loadpage">
</div>
<script type="text/javascript">
$(function(){
$("#loadpage").load("views/suivicommande2View.php",{"statut" : "","page":"page2.php"});
$("input[type='checkbox']").change(function(){
var statut = [];
$.each($(".ckb:checked"), function(){
statut.push($(this).val());
});
console.log(statut);
var urgent = $("input[name='Urgent']").val();
console.log(urgent);
$("#loadpage").load("views/page2.php",{"statut" : statut,"page":"suivicommande2View.php"});
});
});
</script>
[page2.php]
<?php include "function.php" ?>
<table id="myTable" class="table table-bordered display" style="width:100%">
<thead>
<tr>
<th> some th here</th>
</tr>
</thead>
<tbody >
<?php
$data=getStats($_REQUEST['statut']); //getStats function is in function.php
//getStats([statut]){ return data }
// var_dump($historiques);
foreach ($data as $oneData) {
//showing all my data as table
}
</tbody>
</table>
[function.php]
function getStats($condition = null,$date=null,$type=null,$hide_col=false){
//setting default val
if($condition == null)$condition = null;
if($data == null)$date="DESC";
if($type == null) $type=null;
if($hide_col==0)$hide_col=" AND hide_col IS NULL";else {
$hide_col="";
}
$where=where($condition);
$where2=where2($type);
if(!$date === null){
$ordre =" ORDER BY `wor7576_historique_commandes`.id_commande".$date;
}else {
$date ="";
}
$req="SELECT distinct * FROM `wor7576_historique_commandes` where ".$where2." AND ".$where." ".$hide_col." ".$ordre;
// echo $req ; // show query req
$db=DBConnect();
$mysqli_request = mysqli_query($db, $req);
$res=array();
$result_request = mysqli_fetch_all($mysqli_request, MYSQLI_ASSOC);
return $result_request;
}
function where($condition){
if(!count($condition)==0){
$where =" ( ";
for ($i=0; $i < count($condition); $i++) {
$where= $where." statut = ".$condition[$i];
if( $i ==(count($condition)-1) ){
}else{
$where= $where ." OR ";
}
}
$where =$where .")";
}else {
$where =" (statut = statut) ";
}
return $where;
}
function where2($type){
if(!count($type)==0){
$where2 =" ( ";
for ($i=0; $i < count($type); $i++) {
$where2 = $where2." type = '".$type[$i];
if( $i ==(count($type)-1) ){
}else{
$where2 = $where2 ."' OR '";
}
}
$where2 = $where2 ."')";
}else {
$where2 ="(type = type)";
}
return $where2;
}
i'm just learning the jq and ajax at internet like 1 week
i'm not sure im using the .load or ajax right way..
Related
I have a problem inserting the multiple row from my table to my database. Ill show picture of my UI.
https://i.stack.imgur.com/1okJB.png
There are 5 column that I will insert into my database Barcode,Description and QTY is in the table that I want to insert and the two data is outside the table,or not on the table e.g username and customer_id. Its printed on the other part of my UI.
I tried this ajax code but nothing happen.
$(document).on('click','.Enter',function(e){
var user = [];
var product = [];
var customer = [];
var quantity = [];
$('input .user').each(function(){
user.push($(this).text());
});
$('tableData tr td .barcode').each(function(){
product.push($(this).text());
});
$('select .customer_id').each(function(){
customer.push($(this).text());
});
$('tableData tr td .qty').each(function(){
quantity.push($(this).text());
});
$.ajax({
url:"insert_sales.php",
method:"POST",
data:{user:user, product:product, customer:customer, quantity:quantity},
success: function(data){
alert(user[0]);
},
})
});
This is part of my HTML file.
<input type="hidden" name="user" value="<?php echo $row['username']; ?>" class="user" />
<select class="customer_id" name="customer" style='cursor:pointer'>
<?php
if(mysqli_num_rows($show)>0){
while ($row = mysqli_fetch_array($show)) {
?>
<option value="<?php echo $row['customer_id']; ?>"><?php echo $row['firstname'];?>
</option>
<table id="table2">
<thead>
<tr class='text-center'>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
This is my insert_product.php file.
if(isset($_POST['user'])){
$user = $_POST['user'];
$product = $_POST['products'];
$customer = $_POST['customer'];
$quantity = $_POST['quantity'];
$query = '';
for($count = 0; $count<count($user); $count++){
$user_clean = mysqli_real_escape_string($db, $user[$count]);
$product_clean = mysqli_real_escape_string($db, $user[$count]);
$customer_clean = mysqli_real_escape_string($db, $user[$count]);
$quantity_clean = mysqli_real_escape_string($db, $user[$count]);
if($user_clean != '' && $product_clean != '' && $customer_clean != '' && $quantity!= ''){
$query = "INSERT INTO sales(username,product_id,customer_id,quantity) VALUES('$user_clean',$product_clean,$customer_clean,$quantity_clean)";
}
}
if ($query != ''){
if(mysqli_multi_query($db,$query)){
echo "Item Inserted"
}else{
echo "Error";
}
}else{
echo "No Product";
}
}
Hope someone can help me about this one. I'd put an alert in ajax to know if the it passes to the code. There's no insert happening even though it passes to the alert.
I have following loop in php:
foreach ($sid as $key => $value) {
$sql = " a sql query ";
$vehicle->rowQuery($sql);
$numRows = $vehicle->rows;
while ( $data = $vehicle->result->fetch_assoc()) {
$vid = $data['vid'];
$vehicleName = $data['vehicleName'];
$noOfSeat = $data['noOfSeat'];
$seatBooked = $data['seatBooked'];
$supplierName = $data['supplierName'];
echo "<table class='table table-bordered table-condensed table-striped'>";
echo "<tr>";
echo "<th colspan='4' class='success'>
<label class='checkbox-inline'>
<input type='checkbox' class='vehicleClass' name='vid[]' value='{$vid}'>$vehicleName<strong> ( $noOfSeat Seats available) - $supplierName
</label>
<div class='pull-right'><a href='#' class='hideMe'>Show/Hide</a></div></strong>
<input type='hidden' name='noOfSeat[$vid]' value='$noOfSeat'>
</th>";
echo "</tr>";
echo "<tr>";
echo "<th colspan='4'>All Seats</th>";
echo "</tr>";
$count = 0;
for ($seat=1; $seat <= $noOfSeat; $seat++) {
if($count % 4 == 0) {
echo "</tr><tr class='toggleMe'>";
}
echo "<td><label class='checkbox-inline'><input type='checkbox' name='seatNo[$vid][]' value='$seat'>Seat $seat </label></td>";
$count++;
}
echo "</table>";
}
if( $numRows == 0 ) {
echo "<table class='table table-bordered table-condensed table-striped'>";
echo '<tr><td class="alert alert-warning">Your selected vehicle is not available.</td></tr>';
echo "</table>";
}
}
It's output is like that:
Now, I am trying to show and hide the corresponding All Seats Checkbox list whne I click on show/hide link using following jQuery:
$(document).ready(function(){
$('.hideMe').click(function() {
$(this).next('.toggleMe').toggle();
});
});
But show/hide it's not working. Can you guys tell me how can I solve it?
Thanks.
===================
Update:
When the loop result is this :
then using this code it's working fine:
$(document).ready(function(){
$('.hideMe').click(function() {
$('.toggleMe').toggle();
});
});
Do you use ajax to get the html?
if yes, you had better use $('body').on('click,'.hideMe',function() {})
and tr is not next element of .hideMe
You can try this code.
$(document).ready(function(){
$('body').on('click','.hideMe',function() {
$(this).parents('table').find('.toggleMe').toggle();
});
});
I think you should use on('Click',function(){ }) instead of click try this
$(document).ready(function(){
$('body').on('click', '.hideMe', function() {
$(this).next('.toggleMe').toggle();
});
});
I think your structuring with "<tr>" is not correct in
if($count % 4 == 0) {
echo "</tr><tr class='toggleMe'>";
}
this will add a </tr> at the beginning of each toggleMe class.
here is my html:
<?php echo ($row['status'] == 1)? ?>
<span id='slide_".$row['id']."' name="slid_id" class='label label-danger'>Inactive</span>
<?php : ?>
<span id='slide_".$row['id']."' name="slid_id" class='label label-success'>Active</span>
<?php ; ?>
here is my jquery code:
$(document).ready(function()
{
$("span").click(function()
{
var id = $(":input[name=slide_id]").val();
alert(id);
});
});
i didn't get anything , i want to get the
ID & its dynamic generated value
of the span element and then perform some action like on click i want to change the status from active to inactive or vise versa.
thanks in advance.
var id = $(":input[name=slide_id]").attr('id'); should do the job. .val() only returns the current value of input elements.
Your HTML is missing from the question, but eliminating the colon in your jQuery selector might do the trick in selecting an input field - i.e. $("input[name=slide_id]").val().
If you want to get the ID attribute of a span element, this would work:
$('span_selector').attr('id');
okay finally i got the way to solve this things. m just sharing this if anyone have same issue one day then this might helpful.
html codes:
<tr class="tr">
<td class="td">
<div id="status">
<?php
echo ($row['status'] == 1)?
"<span id='".$row['id']."' class='label label-danger'>Inactive</span>":
"<span id='".$row['id']."' class='label label-success'>Active</span>";
?>
</div>
</td>
</tr>
my jquery code:
$(document).ready(function()
{
$("#status > span") .click(function()
{
var id = $(this).attr('id');
var tempelement = $(this);
var texts = $(this).closest(".tr").find("#texts").val();
var author = $(this).closest(".tr").find("#author").val();
var status = $(this).text();
$.ajax({
type: 'POST',
url: 'manage_feedback.php',
data: {id:id, texts:texts, author:author, status:status},
success: function(data)
{
if (data == "Active")
{
$(tempelement).removeClass("label label-danger");
$(tempelement).addClass("label label-success");
$(tempelement).html(data);
alert('status changed');
}
else if (data == "Inactive")
{
$(tempelement).removeClass("label label-success");
$(tempelement).addClass("label label-danger");
$(tempelement).html(data);
alert('status changed');
}
else
{
alert(data);
}
}
});
});
php script
//ajax status changer code
if (isset($_POST['id']) && isset($_POST['texts']) && isset($_POST['status']) && isset($_POST['author']))
{
$id = $_POST['id'];
$texts = trim($_POST['texts']);
$author = trim($_POST['author']);
$status = $_POST['status'];
$qry = "SELECT count(id) as count FROM tbl_testimonials WHERE texts = '".$texts."'
AND author = '".$author."' AND id != ".$id." ";
$sql = mysql_query($qry);
$data = mysql_fetch_assoc($sql);
if ($data['count'] == 0)
{
if($status == 'Inactive')
{
$qry = "UPDATE tbl_testimonials SET status = 0 WHERE id = ".$id." " ;
$sql = mysql_query($qry);
if($sql == 1)
{
echo 'Active';
exit;
}
}
elseif ($status == 'Active')
{
$qry = "UPDATE tbl_testimonials SET status = 1 WHERE id = ".$id." " ;
$sql = mysql_query($qry);
if($sql == 1)
{
echo 'Inactive';
exit;
}
}
}
else
{
echo "name already taken";
exit;
}
}
hope it will help someone.
I've made a popup message with auto-refresh function, so every few minutes the popup will appear to display the records. And it worked.
The following is the JavaScript code that auto refreshes:
$(document).ready(function() {
setInterval(function() {
$('#rtnotice').load('plugins/notice/n_notice_invoice.php').fadeIn("slow");
}, 5000)
});
code of n_notice_invoice.php
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#noticearea").hide();
});
});
</script>
<?php
try{
require_once "../../config/c_config.php";
$db = dbConn::getConnection();
$timestamp = $_REQUEST['term'];
$sqlck = $db->prepare("SELECT COUNT(id_notice_alert) as ttlinv FROM str_notice_alert WHERE date_alert > '$timestamp'");
$sqlck->execute();
$resck = $sqlck->fetch(PDO::FETCH_ASSOC);
if($resck['ttlinv'] == '0')
{}else{
?>
<div id="noticearea">
<div id="modal">
<div class="modal-content">
<div class="header">
<div id="circle" align="center"><h1><?php echo $resck['ttlinv'];?></h1></div><div class="titlenotice"><h1>NOTICE ALERT<?php echo $timestamp; ?></h1></div>
<div class="break"></div>
</div>
<div class="copy">
<p>
<table width="100%" class="gridtable">
<tr><th>No</th><th>Name</th><th>Status</th><th>Location</th><th>Date</th></tr>
<?php
$sqll = $db->prepare("SELECT * FROM str_notice_alert");
$sqll->execute();
while($resl = $sqll->fetch(PDO::FETCH_ASSOC)){
?>
<tr><td align="center"><?php echo $resl['id_notice_alert']; ?></td><td><?php echo $resl['alert_name']; ?></td><td align="center"><?php echo $resl['alert_status']; ?></td><td align="center"><?php echo $resl['alert_location']; ?></td><td><?php echo $resl['date_alert']; ?></td></tr>
<?php } ?>
</table>
</p>
</div>
<div class="cf footer">
<button id="hide" class="btn">Close</button>
</div>
</div>
<div class="overlay"></div>
</div></div>
<?php
$sqltrunc = $db->prepare("TRUNCATE TABLE str_notice_alert");
$sqltrunc->execute();
}$db = null;}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
?>
After a popup message is displayed, it will display the file n_notice_invoice.php existing records and also delete the records via queries available. In any appearances. But the question is, why the records are not updated / changed. uUnless I refresh the file directly n_notice_invoice.php, and then auto-refresh displays the most recent data.
$timestamp = $_REQUEST['term'];
should be updated each time you call the page. You should load the page with Ajax passing $timestamp as a parameter instead of just loading it.
To get what you need can I suggest you to use long polling? PHP long polling or even better with node.js. For php for example the "server" page:
$timeStart = time();
// Create connection
$con = mysqli_connect('localhost','root','','polldb');
// Check connection
if (mysqli_connect_errno($con))
die ('Failed to connect to MySQL: ' . mysqli_connect_error() );
// select where item is new
if(isset($_POST['timestamp'])){
$timestamp = $_POST['timestamp'];
}else{
// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
}
$sql = "SELECT * FROM `notification` WHERE timestamp > '$timestamp'";
$newData = false;
$notifications = array();
// loop while there is no new data and is running for less than 20 seconds
while(!$newData && (time()-$timeStart)<20){
// check for new data
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)){
$notifications[] = $row;
$newData = true;
}
// let the server rest for a while
usleep ( 500000 );
}
// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
mysqli_close($con);
// output
$data = array('notifications'=>$notifications,'timestamp'=>$timestamp);
echo json_encode($data);
exit;
and the client:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
pullNotification();
});
function pullNotification(timestamp){
var data = {};
if(typeof timestamp!='undefined')
data.timestamp = timestamp;
$.post('longpoll.php',data,function(msg){
var newData = '';
for(i in msg.notifications){
newData+=msg.notifications[i].message+'\n';
}
if(newData!='')
alert(newData);
pullNotification(msg.timestamp);
},'json');
}
</script>
This will check for database updates and will pop them up. Every 20 seconds it will renew the request. Obviously you have to adapt it to your needs.
I believie your issue comes from cached request (in Browser on in ajax itself)
please try to disable ajax caching :
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: "plugins/notice/n_notice_invoice.php",
cache: false
})
.done(function( data ) {
$('#rtnotice').html(data).fadeIn("slow");
});
}, 5000)
});
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);
}
}