Load data after search function using ajax in one php page - javascript

I'm new with ajax and php. I had created a page where it loads the data using ajax. The data is shown using pagination. The thing is, I can't figure out on how to make the results search loading back to birds.php.
birds.php
<script type="text/javascript">
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='../~ww319/images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
var search = $('#search').val();
$.ajax
({
type: "POST",
url: "../~ww319/load_data.php",
data: "page="+page+"&search="+search,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
});
</script>
<div class="entry">
<form action="../~ww319/load_data.php" method="POST">
<fieldset>
<legend>Searching</legend><br />
<input type="text" id="search" name="search" />
<input type="submit" value="Search" onClick="loadData(1);" /><br /><br />
<input type="hidden" name="page" value="1" />
</fieldset>
</form>
<br />
<div id="loading"></div>
<div id="container">
<div class="data"></div>
<div class="pagination">
</div>
</div>
</div>
load_data.php //this is the page to load the data to birds.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 2;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
include 'connect.php';
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(isset($_POST['search'])){
$search = $_POST['search'];
$searchPar = '';
if(!empty($search)){
$searchPar = "WHERE (`species` LIKE '%".$search."%') OR (`location` LIKE '%".$search."%')";
}
$query = "SELECT * from birds $searchPar LIMIT $start, $per_page";
$result1 = mysql_query($query) or die('MySql Error' . mysql_error());
$msg = "";
if(mysql_num_rows($result1) > 0){
while($result = mysql_fetch_array($result1)){
$msg .= "<li><img src=".$result['imgThumb']."></li>";
}
$msg = "<div class='data'><ul>" . $msg . "</ul></div>"; // Content for Data
$query_pag_num = "SELECT COUNT(*) AS count FROM birds WHERE (`species` LIKE '%".$search."%') Or (`location` LIKE '%".$search."%')";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
if ($cur_page >= 5) {
$start_loop = $cur_page - 2;
if ($no_of_paginations > $cur_page + 2)
$end_loop = $cur_page + 2;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 4) {
$start_loop = $no_of_paginations - 4;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 5)
$end_loop = 5;
else
$end_loop = $no_of_paginations;
}
$msg .= "<div class='pagination'><ul>";
// FOR ENABLING THE FIRST BUTTON
if ($first_btn && $cur_page > 1) {
$msg .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$msg .= "<li p='1' class='inactive'>First</li>";
}
// FOR ENABLING THE PREVIOUS BUTTON
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$msg .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$msg .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$msg .= "<li p='$i' style='color:#fff;background-color:#983D3A;' class='active'>{$i}</li>";
else
$msg .= "<li p='$i' class='active'>{$i}</li>";
}
// TO ENABLE THE NEXT BUTTON
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$msg .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$msg .= "<li class='inactive'>Next</li>";
}
// TO ENABLE THE END BUTTON
if ($last_btn && $cur_page < $no_of_paginations) {
$msg .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$msg .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
echo $msg;
}
else{ // if there is no matching rows do following
$msg .= "no results found.";
echo $msg;
}}
else{
$query_pag_data = "SELECT * from birds LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result_pag_data)) {
$msg .= "<li><img src=".$row['imgThumb']."></li>";
}
$msg = "<div class='data'><ul>" . $msg . "</ul></div>"; // Content for Data
/* --------------------------------------------- */
$query_pag_num = "SELECT COUNT(*) AS count FROM birds";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
if ($cur_page >= 5) {
$start_loop = $cur_page - 2;
if ($no_of_paginations > $cur_page + 2)
$end_loop = $cur_page + 2;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 4) {
$start_loop = $no_of_paginations - 4;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 5)
$end_loop = 5;
else
$end_loop = $no_of_paginations;
}
$msg .= "<div class='pagination'><ul>";
// FOR ENABLING THE FIRST BUTTON
if ($first_btn && $cur_page > 1) {
$msg .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$msg .= "<li p='1' class='inactive'>First</li>";
}
// FOR ENABLING THE PREVIOUS BUTTON
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$msg .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$msg .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$msg .= "<li p='$i' style='color:#fff;background-color:#983D3A;' class='active'>{$i}</li>";
else
$msg .= "<li p='$i' class='active'>{$i}</li>";
}
// TO ENABLE THE NEXT BUTTON
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$msg .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$msg .= "<li class='inactive'>Next</li>";
}
// TO ENABLE THE END BUTTON
if ($last_btn && $cur_page < $no_of_paginations) {
$msg .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$msg .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
echo $msg;
}
}
The search results would be shown on load_data.php instead of loading back to birds.php.

Try this:
birds.php
<script type="text/javascript">
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='../~ww319/images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
var search = $('#search').val();
$.ajax
({
type: "POST",
url: "../~ww319/load_data.php",
data: "page="+page+"&search="+search,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
});
</script>
<div class="entry">
<form action="../~ww319/load_search.php" method="POST">
<fieldset>
<legend>Searching</legend><br />
<input type="text" name="search" id="search"/>
<input type="button" value="Search" onClick="loadData(<?php $_POST['page'] ?>);" /><br /><br />
</fieldset>
</form>
<br />
<div id="loading"></div>
<div id="container">
<div class="data"></div>
<div class="pagination">
</div>
</div>
</div>
And your search query should be generated as follows:
$searchPar = '';
if(!empty($search)){
$searchPar = "WHERE (`species` LIKE '%".$search."%') OR (`location` LIKE '%".$search."%')";
}
$query = "SELECT * from birds $searchPar LIMIT $start, $per_page";

why don't try this http://www.datatables.net/examples/styling/jqueryUI.html ?
it was useful for me and it implement many functionalities like instant search that you will surely like

Related

how to get multiple variable values using ajax

I am using ajax to get data from my Mysql database. The data is about in 10k rows so I need pagination in my page. I get a pagination code online and it is working fine without ajax but I am unable to make it functional with my ajax code.
here is my pagination file "function.php" and I have no issue with that
<?php
function displayPaginationBelow($per_page,$page){
$page_url="?";
$query = "SELECT COUNT(*) as totalCount from pdbp inner join bp on(pdbp.bp_id=bp.id) where bp.status= 1";
$rec = mysql_fetch_array(mysql_query($query));
$total = $rec['totalCount'];
$adjacents = "2";
$page = ($page == 0 ? 1 : $page);
$start = ($page - 1) * $per_page;
$prev = $page - 1;
$next = $page + 1;
$setLastpage = ceil($total/$per_page);
$lpm1 = $setLastpage - 1;
$setPaginate = "";
if($setLastpage > 1)
{
$setPaginate .= "<ul class='setPaginate'>";
$setPaginate .= "<li class='setPage'>Page $page of $setLastpage</li>";
if ($setLastpage < 7 + ($adjacents * 2))
{
for ($counter = 1; $counter <= $setLastpage; $counter++)
{
if ($counter == $page)
$setPaginate.= "<li><a class='current_page'>$counter</a></li>";
else
$setPaginate.= "<li><a href='{$page_url}page=$counter'>$counter</a></li>";
}
}
elseif($setLastpage > 5 + ($adjacents * 2))
{
if($page < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $page)
$setPaginate.= "<li><a class='current_page'>$counter</a></li>";
else
$setPaginate.= "<li><a href='{$page_url}page=$counter'>$counter</a></li>";
}
$setPaginate.= "<li class='dot'>...</li>";
$setPaginate.= "<li><a href='{$page_url}page=$lpm1'>$lpm1</a></li>";
$setPaginate.= "<li><a href='{$page_url}page=$setLastpage'>$setLastpage</a></li>";
}
elseif($setLastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
{
$setPaginate.= "<li><a href='{$page_url}page=1'>1</a></li>";
$setPaginate.= "<li><a href='{$page_url}page=2'>2</a></li>";
$setPaginate.= "<li class='dot'>...</li>";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
{
if ($counter == $page)
$setPaginate.= "<li><a class='current_page'>$counter</a></li>";
else
$setPaginate.= "<li><a href='{$page_url}page=$counter'>$counter</a></li>";
}
$setPaginate.= "<li class='dot'>..</li>";
$setPaginate.= "<li><a href='{$page_url}page=$lpm1'>$lpm1</a></li>";
$setPaginate.= "<li><a href='{$page_url}page=$setLastpage'>$setLastpage</a></li>";
}
else
{
$setPaginate.= "<li><a href='{$page_url}page=1'>1</a></li>";
$setPaginate.= "<li><a href='{$page_url}page=2'>2</a></li>";
$setPaginate.= "<li class='dot'>..</li>";
for ($counter = $setLastpage - (2 + ($adjacents * 2)); $counter <= $setLastpage; $counter++)
{
if ($counter == $page)
$setPaginate.= "<li><a class='current_page'>$counter</a></li>";
else
$setPaginate.= "<li><a href='{$page_url}page=$counter'>$counter</a></li>";
}
}
}
if ($page < $counter - 1){
$setPaginate.= "<li><a href='{$page_url}page=$next'>Next</a></li>";
$setPaginate.= "<li><a href='{$page_url}page=$setLastpage'>Last</a></li>";
}else{
$setPaginate.= "<li><a class='current_page'>Next</a></li>";
$setPaginate.= "<li><a class='current_page'>Last</a></li>";
}
$setPaginate.= "</ul>\n";
}
return $setPaginate;
}
?>
here is my ajax file in which i am getting data through database and sending it to my view file.
<?php
include_once('config/connection.php');
// here is the Pagination code starts
include_once "function.php";
if(isset($_GET["page"]))
$page = (int)$_GET["page"];
else
$page = 1;
$setLimit = 10;
$pageLimit = ($page * $setLimit) - $setLimit;
// Pagination code ends
if(isset($_GET['name'])){
$name = $_GET['name'];
$retval = "";
$pagination = "";
$counter = 0;
$query = mysql_query("select id,card_name,phone1,address,region,country,cert_num,category_cod,material_cod,trade_type,web from pdbp inner join bp on(pdbp.bp_id=bp.id) where bp.status= 1 and card_name like '%$name%' limit $pageLimit , $setLimit");
while($data = mysql_fetch_assoc($query)){
$id = $data['id'];
$name = $data['card_name'];
$phone1 = $data['phone1'];
$region = $data['region'];
$trade_type = $data['trade_type'];
$address = $data['address'];
$web = $data['web'];
$queryr= mysql_query("select Region from regions where RegionId = '$region'");
$region_1 = mysql_fetch_array($queryr);
$region_name = $region_1['Region'];
$country = $data['country'];
$queryc= mysql_query("select Country from countries where CountryId = '$country'");
$country_1 = mysql_fetch_array($queryc);
$country_name = $country_1['Country'];
$cert_num = $data['cert_num'];
$cn=explode(",",$cert_num);
$cns = "";
foreach($cn as $cc){
$cert_fetch = mysql_query("select description from cert where id='$cc'");
$cert_fetch1 = mysql_fetch_array($cert_fetch);
$cnum = $cert_fetch1['description'];
$cns=$cns."<div style='margin:5px;display:block;clear:both'> ".$cnum." </div>";
}
$cat = $data['category_cod'];
$category = explode(",",$cat);
$cc = "";
foreach($category as $categories){
$categories_fetch = mysql_query("select subc_name, category_name, line from sub_categories as s inner join product_categories p ON (p.category_cod = s.pc_Cod) inner join product_line l ON (p.line_cod = l.line_cod) where subc_cod='$categories'");
$aaa = mysql_fetch_array($categories_fetch);
$s = $aaa['subc_name'];
$cname = $aaa['category_name'];
$l = $aaa['line'];
$cc=$cc."<div style='margin:5px;display:block;clear:both'> ".$s.'-'.$cname.'-'.$l." </div>";
}
$mat = $data['material_cod'];
$material = explode(",",$mat);
$mm = "";
foreach($material as $materials){
$material_fetch = mysql_query("select material from product_material where material_cod='$materials'");
$mat_fetch1 = mysql_fetch_array($material_fetch);
$mcod = $mat_fetch1['material'];
$mm=$mm."<div style='margin:5px;display:block;clear:both'> ".$mcod." </div>";
}
$retval=$retval."<tr><td>".++$counter."</td><td> ".$name." </td><td> ".$phone1." </td><td> ".$address." </td><td> ".$region_name." </td><td> ".$country_name." </td><td> ".$cns." </td><td> ".$cc." </td><td> ".$mm."</td><td> ".$trade_type."</td><td> ".$web."</td><td></tr>";
}
echo $retval;
}
?>
I am getting data successfully but Now I need to echo displayPaginationBelow($setLimit,$page); to show pagination below the data,which is coming through function.php and I have no idea how to do this.
and here is my jquery code:
$("#cmp_name").keyup(function(){
$.ajax({
'url':"filter.php",
'data':{name:$("#cmp_name").val()},
'method':'GET',
'success':function(name){
$("#data").html(name);
}
})
});
Anyone know how to achieve this. Kindly help me out or if someone give some more efficient way to achieve my goal I will be very gratefull. Secondly I know I am using mysql_* which is deprecated and I will fix it soon
use type instead method while using ajax
$("#cmp_name").keyup(function(){
name = $("#cmp_name").val();
$.ajax({
'url':"filter.php",
'data':{"name":name},
'type':'POST',
'success':function(data){
$("#data").html(data);
}
})
});
use array for multiple return value.
in filter.php
$retval['data'] = YOUR_PREVIOUS_RETVAL;
$retval['pagination'] = displayPaginationBelow($setLimit,$page);
echo json_encode($retval);
in javascript
$("#cmp_name").keyup(function(){
$.ajax({
'url':"filter.php",
'data':{name:$("#cmp_name").val()},
'type':'GET',
'dataType':'json',
'success':function(result){
$("#data").html(result.data);
$("#PAGINATION").html(result.pagination);
}
})
});
you must specify dataType to 'json'.

how to export html table to excel, with pagination

I have a form which displays mysql data in the form of an HTML table, using pagination of 5 records per page. I'm trying to export my table to excel, but it's only exporting data of the rows that are currently show, meaning if there are 20 rows, it only shows the first 5 as those get displayed. How can I make it export the one's that are not being displayed but still part of the search? I saw a few other people with a similar question but none have answers( How to export all HTML table rows to Excel file from a paginated table?). Hopefully I can get one!
<?php
if(isset($_GET['submit']) || isset($_GET['page'])){
// Setting up the Pagination below
echo '<center>';
$page_query = "SELECT * FROM tbl_call_log_detail ";
$page_query .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ";
$page_result = mysqli_query($conn, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
$start_loop = $page;
$difference = $total_pages - $page;
if($difference <= $total_pages){
$start_loop = $total_pages - $difference;
}
$end_loop = $start_loop + 2;
if($end_loop > $total_pages){
$end_loop = $total_pages;
}
if($difference > $total_pages){
$end_loop = $total_pages;
}
echo '<div class = "center">';
echo '<div class = "pagination">';
if($page > 1){
echo "<a href= 'dealer_call_log.php?page=1".$urlparameter."'>First</a>";
echo "<a href= 'dealer_call_log.php?page=".($page - 1).$urlparameter."'> << </a>";
}
for ($i = $start_loop; $i <= $end_loop; $i++){
echo "<a href= 'dealer_call_log.php?page=".$i.$urlparameter."'>".$i."</a>";
}
if($page < $end_loop){
echo "<a href= 'dealer_call_log.php?page=".($page + 1).$urlparameter."'> >> </a>";
echo "<a href= 'dealer_call_log.php?page=".$total_pages.$urlparameter."'>Last</a>";
}
if($page < 1){
$page = 1;
}
echo '</div>';
echo '</div>';
echo '<br>';
$sql = "SELECT Name, SFID, Comment, Time FROM tbl_call_log_detail
WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='')
ORDER BY Time DESC LIMIT $start_from, $record_per_page ";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
$all_property = array();
echo "<table class = 'data-table' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table'>
<tr class = 'data-heading'>";
while($property = mysqli_fetch_field($result)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property, $property ->name);
}
echo '</tr>';
while ($row = mysqli_fetch_array($result)){
echo '<tr>';
foreach($all_property as $item){
echo '<td> '. $row[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
echo '<br>';
?>
// This is what is getting the current rows, but not all
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table').outerHTML));" value = "Export into excel" />
<?php
}
?>
UPDATE: Found the answer I was looking for I simply ran a new sql query without the LIMIT clause and stored it in a hidden table. I then use the hidden table to export data
// SQL and hidden table for exporting to excel
$page_query2 = "SELECT * FROM tbl_call_log_detail ";
$page_query2 .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ORDER BY TIME DESC ";
$page_result2 = mysqli_query($conn, $page_query2);
$row2 = mysqli_num_rows($page_result2);
$all_property2 = array();
echo "<table class = 'data-table2' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table2' hidden>
<tr class = 'data-heading2'>";
while($property = mysqli_fetch_field($page_result2)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property2, $property ->name);
}
echo '</tr>';
while ($row2 = mysqli_fetch_array($page_result2)){
echo '<tr>';
foreach($all_property2 as $item){
echo '<td> '. $row2[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
?>
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table2').outerHTML));" value = "Export into excel" />
<?php
}
?>
You can use JQuery table2excel plugin following is the link
http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html
Try following code pen to only JavaScript
https://codepen.io/kostas-krevatas/pen/mJyBwp

How to put validation on a dynamic dropdown when inserting in PHP?

I'm constructing a survey and I have a textbox that generates dynamic dropdowns based on user input which displays the same data.
This is the script
<script>
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
</script>
This is the insert code when I'm creating the survey
<?php
$con = mysqli_connect("localhost","root","","imetrics");
if(isset($_POST['submit'])){
$title = $_POST['surveytitle'];
$catdd = $_POST['catdd'];
$subcatdd = $_POST['subcatdd'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$occupation = $_POST['occupation'];
$occupationtwo = $_POST['occupdd'];
$relstatus = $_POST['relationshipstatus'];
$q_num = $_POST['q_num'];
$insert = mysqli_query($con, "INSERT INTO `surveyform` (`surveytitle`,`surveycategory`,`surveysubcategory`,`gender`,`age`,`occupation`,`occupation_status`,`status`) VALUES ('$title','$catdd','$subcatdd','$gender','$age','$occupation','$occupationtwo','$relstatus')");
if(!$insert){
echo mysqli_errno();
}
else{
$getMaxID = mysqli_query($con, "SELECT MAX(survey_id) as maxid FROM surveyform");
$row_2 = mysqli_fetch_array($getMaxID);
$survey_id = $row_2[0];
for( $a = 1; $a <= $q_num; $a++)
{
mysqli_query($con, "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")");
//echo "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")";
}
echo '<script language="javascript">';
echo 'alert("Survey Created!")';
echo '</script>';
}
}
?>
And this is my dropdown code
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "<b>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}
here's my submit button
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
What's the validation code that will prevent me from inserting if the data chosen from the dropdown is the same? For example I generated 2 dropdowns and I chose the same datas from the dropdown, what's the validation code for it?
Please call checkValues method your submit button click
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
checkValues method below :
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
Also , you can see an example Example

Replace div contents with jQuery on form submit within PHP loop

I have this jQuery form being outputted in a PHP while loop if the button has not previously been clicked and just an image with the value if it has, the function is like facebooks like button where when the user clicks the button the icon changes so its not clickable any longer and the value increments by 1. The form submission works but I cannot seem to update the icon image and value count in the feed without effecting all the other buttons and values in the feed… I tried jQuery replaceWith() but it replaces all the #bumpCont divs in the feed…
index.php
<div class="images">
<?php
while($row = $result2->fetch_assoc()){
$path = $row['path'];
$user = $row['user'];
$id = $row['id'];
$desc = $row['desc'];
$update = $row['update_date'];
$bump = $row['bump'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
?>
<?php if(empty($desc)){}else{?><div id="desc"><?php echo $desc;?></div><?php }?>
<img id="pic" src="uploads/<?php echo $path;?>"/>
<div id="userCont">
<div id="user"><a rel="external" href="user_profile.php?user='.$user.'"><?php echo $user;?></a></div>
<div id="timer"><?php echo $timer;?></div>
<?php
if(in_array($path, $mypath)) {
echo '<div id="bumpCont"><img id="bump" style="height:55px;right:8px;top: 2px;position: relative;" src="../img/bumpg.png"/><span id="bumpCount">'.$bump.'</span></div>';
}else{
echo '<form method="post" id="bumpF" data-ajax="false">';
echo '<input name="id" data-ajax="false" id="field_'.$id.'" type="hidden" value="'.$id.'" />';
echo '<div id="bumpCont"><input type="image" style="height:55px;right:8px;top: 2px;position: relative; " id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm('.$id.');" value="Send" /><span id="bumpCount">'.$bump.'</span></div>';
echo ' </form>';
}
?>
</div>
<?php
}
?>
//Submit Form
function SubmitForm(id) {
event.preventDefault();
var name = $('#field_'+id).val();
console.log(name);
$.post("bump.php", {name: name},
function(data) {
$( "#bumpCont" ).replaceWith( '<div id="bumpCont"><img id="bump" style="height:55px;right:8px;top: 2px;position: relative;" src="../img/bumpg.png"/><span id="bumpCount">' + data + '</span></div>' );
}
Bump.php -
$id = $_POST['name'];
$sessionUser = $_SESSION['userSession'];
// GET USERNAME
$sql = "SELECT * FROM userbase WHERE user_id='$sessionUser'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$myname = $row['username'];
}
}
$bump = 1;
$sql = "SELECT * FROM images WHERE id=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$bump = $row['bump'];
$path = $row['path'];
$desc = $row['desc'];
$post_user = $row['user'];
$bump++;
}
}
$bumpC = 0;
$sql = "SELECT * FROM bumped WHERE path='$path' AND myname ='$myname'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$bumpC++;
}
}
echo $bump;
if($bumpC >= 1){
}else{
$sql = "INSERT INTO `bumped` ( `myname`,`path`, `description`, `post_user`) VALUES ( '$myname','$path', '$desc', '$post_user')";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "UPDATE images SET update_date='$date' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
$sql = "UPDATE images SET bump=$bump WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
}
First look shows me a problem of Elements with same ID in loop.
You could have same class to multiple elements.
<div class="bumpCont"><span class="bumpCount">1</span></div>
<div class="bumpCont"><span class="bumpCount">2</span></div>
Use $(this)
Based on the click on particular element, you can change contents.
$('.bumpCount').click(function(){
$(this).html(parseInt($(this).html) + 1);
});
Hope this helps you.
$('.bumpCount').click(function(){
$(this).html(parseInt($(this).html()) + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bumpCont"><span class="bumpCount">1</span></div>
<div class="bumpCont"><span class="bumpCount">2</span></div>

PHP Pagination set 25 result per page

i am facing problem, my php show all pages in row and its increasing day by day as i upload data on my sql. I just want 25 page result on page and other for click to next.
<?php
if(isset($page))
{
$result = mysql_query("select Count(*) As Total from store_urls");
$rows = mysql_num_rows($result);
if($rows)
{
$rs = mysql_fetch_assoc($result);
$total = $rs["Total"];
}
$totalPages = ceil($total / $perpage);
if($page <=1 ){
echo "<span id='page_links' style='font-weight: bold;float:left;'>Prev</span>";
}
else
{
$j = $page - 1;
echo "<span style='float:left;'><a style='padding: 8px;' id='page_a_link' href='url_lists.php?page=$j'>< Prev</a></span>";
}
for($i=1; $i <= $totalPages; $i++)
{
if($i<>$page)
{
echo "<span><a style='float:left;padding: 8px;' id='page_a_link' href='url_lists.php?page=$i'>$i</a></span>";
}
else
{
echo "<span id='page_links' style='font-weight: bold;float:left;'>$i</span>";
}
}
if($page == $totalPages )
{
echo "<span id='page_links' style='font-weight: bold;'>Next ></span>";
}
else
{
$j = $page + 1;
echo "<span><a id='page_a_link' style='float:left;padding: 8px;' href='url_lists.php?page=$j'>Next</a></span>";
}
}
?>

Categories

Resources