Can I automatically run an AJAX function when another AJAX function succeeds? - php

I am about to make a note system in procedural PHP and AJAX, which should allow me to both display new notes without refreshing and to load more notes without refreshing.
In my current case both works, but not together. If no notes to show from the database, then my site will display a text saying "There is no notes to display". If I then make a note, it still won't display the note, until I load it in via a click on the loading notes button.
I've tried to add in following to my success function:
if(res.indexOf("success")!=-1) {
location.reload(true);
}
Without any luck, even I could read on the internet, that it somehow worked out for other people.
Here is my ajax functions:
$(document).ready(function() {
var noteCount = 2;
$("#loadMore").click(function() {
noteCount = noteCount + 2;
$("#notes").load("load-notes.php", {
noteNewCount: noteCount
});
});
$("#noteform").on("submit", function(event) {
event.preventDefault();
noteCount = noteCount + 1;
var form_data = $(this).serialize();
$.ajax({
url: "add-notes.php",
method: "POST",
noteNewCount: noteCount,
data: form_data,
dataType: "JSON",
success: function(data) {
if(res.indexOf("success")!=-1) {
location.reload(true);
}
}
});
});
});
My add-notes.php
<?php
session_start();
require_once "../inc/core/config.php";
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit;
$subject = mysqli_real_escape_string($dbconn, $_POST['subject']);
$note = mysqli_real_escape_string($dbconn, $_POST['note']);
$my_date = date("Y-m-d H:i:s");
$author = $_SESSION['u_firstname'];
$noteNewCount = $_POST['noteNewCount'];
$sql = "INSERT INTO notes(author, subject, note, created_at) VALUES ('$author', '$subject', '$note', '$my_date')";
mysqli_query($dbconn, $sql);
$sql = "SELECT * FROM notes LIMIT $noteNewCount";
$result = mysqli_query($dbconn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="note">
<div class="noteHead">
<div class="row">
<div class="col-md-8">
<h3>' . $row["subject"] . '</h3>
</div>
<div class="col-md-4">
<p class="text-muted">Note created by ' . $row["author"] . '</p>
</div>
</div>
</div>
<div class="noteContent">
<div class="row">
<div class="col-12">
<p>' . $row["note"] . '</p>
</div>
</div>
</div>
<div class="noteFooter">
<div class="row">
<div class="col-12">
<p class="text-muted">Created ' . $row["created_at"] . '</p>
</div>
</div>
</div>
</div>';
}
} else {
echo "No comments yet...";
}
The note div where my notes are displayed and the form where they are created:
<form id="noteform" action="add-notes.php" method="POST" >
<div class="form-group">
<label for="usr">Titel:</label>
<input type="text" class="form-control" name="subject">
</div>
<div class="form-group">
<label for="pwd">Note:</label>
<textarea class="form-control" rows="5" name="note"></textarea>
</div>
<button class="btn btn-outline-success my-2 my-sm-0" name="submit" type="submit">Opret note</button>
</form>
<div id="notes">
<?php
$sql = "SELECT * FROM notes LIMIT 2";
$result = mysqli_query($dbconn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="note">
<div class="noteHead">
<div class="row">
<div class="col-md-8">
<h3>' . $row["subject"] . '</h3>
</div>
<div class="col-md-4">
<p class="text-muted">Note created by ' . $row["author"] . '</p>
</div>
</div>
</div>
<div class="noteContent">
<div class="row">
<div class="col-12">
<p>' . $row["note"] . '</p>
</div>
</div>
</div>
<div class="noteFooter">
<div class="row">
<div class="col-12">
<p class="text-muted">Created ' . $row["created_at"] . '</p>
</div>
</div>
</div>
</div>';
}
} else {
echo "No comments yet...";
}
?>
</div>
So to sum up, I am looking for a way to display a new note made, without having to load it in via my load button. What can I do?

Instead of location.reload, you can just replace the HTML in #notes. Also, in add-notes.php you are echoing HTML but in your ajax, you are expecting dataType: json. Also, not sure what is noteNewCount being passed to AJAX.
$.ajax({
url: "add-notes.php",
method: "POST",
data: form_data,
success: function(data) {
$("#notes").html(data);
}
});

Related

How to remove an error "Uncaught SyntaxError: Unexpected token S in JSON at position 0"?

I referenced sols of SO, but nothing solve the error.
I have a file dashboard.html with search condition and on click it calls loadtable.js and this loadtable.js file using search.php retrives rows from table,
But there is some error Uncaught SyntaxError: Unexpected token S in JSON at position 0 and also i don't want to display the server returned JSON on client side. Instead this i want to display table and put values in that. I am attaching both loadtable.js and search.php code.
File loadtable.js
$(document).ready(function(){
var delay = 1000;
// Campaign Submit Info
$('[name="search_submit"]').click(function(e){
e.preventDefault();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var campaign_status = $('#filterformpost').find('#campaign_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();
console.log(lead_status)
console.log(campaign_status)
console.log(company_name)
console.log(tech_area)
console.log(firm_size)
console.log(firm_type)
console.log(country_name)
console.log(state_name)
console.log(start_date)
console.log(end_date)
$.ajax({
type: "POST",
url: "http://localhost/CRM/server/search.php",
data: {
"lead_status":lead_status,
"campaign_status":campaign_status,
"company_name":company_name,
"tech_area":tech_area,
"firm_size":firm_size,
"firm_type":firm_type,
"country_name":country_name,
"state_name":state_name,
"start_date":start_date,
"end_date":end_date
},
beforeSend: function() {
$('.message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, delay);
}
});
$.ajax({
method: "POST",
url: "./server/search.php"
}).done(function( data ) {
var result= $.parseJSON(data);
var string='<table><thead><th>#</th><th>Lead ID</th><th>Name</th><th>Company</th><th>Location</th><th>Communication</th><th>Last Contact Date</th><th>Next Contact Date</th><th>Lead Status</th><th>Details</th></thead><tbody>';
/* from result create a string of data and append to the div */
var i = 1;
$.each( result, function( key, value ) {
string += "<tr><td>"+i+"</td><td>"+value['Lead_Id']+"</td><td>"+value['FirstName']+' '+value['LastName']+"</td><td>"+value['Company']+"</td><td>"+value['State']+'\n'+value['Country']+"</td><td>"+value['Phone']+'\n'+value['Email']+"</td><td>"+value['LastContactDate']+"</td><td>"+value['NextContactDate']+"</td><td>"+value['LeadStatus']+"</td><td><a href='#'>Click Here</a></td></tr>";
i = i+1;
});
string += '</tbody></table>';
$("#filterRecords").html(string);
});
});
});
File search.php
<?php
include('connection.php');
$sqlFlag = 0;
function queryDelimiter(){
global $sqlFlag;
if ($sqlFlag == 0){
$sqlFlag = 1;
return ' WHERE ';
}else{
return ' AND ';
}
}
$selectSQL = "SELECT * FROM tbl_main_lead_info";
if(isset($_POST['lead_status']) and strlen(trim($_POST['lead_status'])) > 0){
$selectSQL .= queryDelimiter()."LeadStatus = '".$_POST['lead_status']."'";
}
if(isset($_POST['company_name']) and strlen(trim($_POST['company_name'])) > 0){
$selectSQL .= queryDelimiter()."Company = '".$_POST['company_name']."'";
}
if(isset($_POST['tech_area']) and strlen(trim($_POST['tech_area'])) > 0){
$selectSQL .= queryDelimiter()."TechArea = '".$_POST['tech_area']."'";
}
if(isset($_POST['firm_size']) and strlen(trim($_POST['firm_size'])) > 0){
$selectSQL .= queryDelimiter()."FirmSize = '".$_POST['firm_size']."'";
}
if(isset($_POST['firm_type']) and strlen(trim($_POST['firm_type'])) > 0){
$selectSQL .= queryDelimiter()."FirmType = '".$_POST['firm_type']."'";
}
if(isset($_POST['country_name']) and strlen(trim($_POST['country_name'])) > 0){
$selectSQL .= queryDelimiter()."Country = '".$_POST['country_name']."'";
}
if(isset($_POST['state_name']) and strlen(trim($_POST['state_name'])) > 0){
$selectSQL .= queryDelimiter()."State = '".$_POST['state_name']."'";
}
if(isset($_POST['start_date']) and strlen(trim($_POST['start_date'])) > 0){
$selectSQL .= queryDelimiter()."LastContactDate >='".$_POST['start_date']."'";
}
if(isset($_POST['end_date']) and strlen(trim($_POST['end_date'])) > 0){
$selectSQL .= queryDelimiter()."NextContactDate <= '".$_POST['end_date']."'";
}
$selectSQL .= " ORDER BY Lead_Id";
$result_array = array();
$result = $conn -> query ($selectSQL);
// If there are results from database push to result array
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
array_push($result_array, $row);
}
}
// send a JSON encoded array to client
echo json_encode($result_array);
$conn->close();
?>
In dashboard.html i have code as follows
<!-- View Main Lead Table with Filters -->
<section class="operation" id="view_lead_info" style="display: none;">
<!-- Filters -->
<div class="row">
<div class="col">
<label><p><b>Select Filter</b></p></label>
</div>
</div>
<form action='' method='POST' class='filterformpost' id='filterformpost'>
<div class="row">
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
Lead Status:
</div>
<div class="col span-2-of-4">
<select id='lead_status_select'><option value=''>Select</option>
<?php
echo "<option value='All'>All</option>";
echo "<option value='Active'>Active Leads</option>";
echo "<option value='Paused'>Paused Leads</option>";
echo "<option value='Expired'>Expired Leads</option>";
echo "<option value='Unsubscribed'>Unsubscribed</option>";
?>
</select>
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-1-of-4">
Campaign Status:
</div>
<div class="col span-2-of-4">
<select id='campaign_status_select'><option value=''>Select</option>
<?php
echo "<option value='All'>All</option>";
echo "<option value='Active'>Active</option>";
echo "<option value='Paused'>Paused</option>";
echo "<option value='Expired'>Expired</option>";
echo "<option value='Unsubscribed'>Unsubscribed</option>";
?>
</select>
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-1-of-3">
Company Name:
</div>
<div class="col span-2-of-3">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_main_lead_info ORDER By Company ASC";
$result = $conn -> query ($sqlSelect);
echo "<select id='company_name_select'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[Company]'> $row[Company] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
State:
</div>
<div class="col span-2-of-4">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_state_info ORDER By StateName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='state_name_select' name='StateName'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[StateName]'> $row[StateName] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-1-of-4">
Country:
</div>
<div class="col span-2-of-4">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_country_info ORDER By CountryName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='country_name_select' name='CountryName'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[CountryName]'> $row[CountryName] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-1-of-3">
Firm Type:
</div>
<div class="col span-2-of-3">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_firm_type_info ORDER By FirmType_Value ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='firm_type_select' name='FirmType'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[FirmType_Value]'> $row[FirmType_Value] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
Firm Size:
</div>
<div class="col span-2-of-4">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_firm_size_info ORDER By FirmSize_Id ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='firm_size_select' name='FirmSize'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[FirmSize_Value]'> $row[FirmSize_Value] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-3">
Tech Area:
</div>
<div class="col span-2-of-3">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_tech_area_info ORDER By TechAreaName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='tech_area_select' name='TechAreaName'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[TechAreaName]'> $row[TechAreaName] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
Start Date:
</div>
<div class="col span-3-of-4">
<?php
echo "<input type='date' id='start_date_search' name='startdate'>";
?>
</div>
</div>
</div>
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
End Date:
</div>
<div class="col span-3-of-4">
<?php
echo "<input type='date' id='end_date_search' name='enddate'>";
?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col span-1-of-3">
<div class="row">
<div class="col span-3-of-4">
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-3-of-4">
<div class="row">
<div class="col span-1-of-3">
<label></label>
</div>
<div class="col span-2-of-3">
<input type="submit" name='search_submit' value="Search">
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div class="row">
<div class="col span-1-of-3">
<label></label>
</div>
<div class="col span-2-of-3">
<div class="message_box" style="margin-left: 60px;">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div style="overflow-x:auto;">
<div id="filterRecords"></div>
</div>
</div>
</div>
</section>
You are returning more than just the desired json in your search.php
try removing these lines:
echo $selectSQL;
echo "<p></p>";
echo "<p></p>";
for the json output in the frontend: you have 2 ajax calls in your js file, the first one puts the json into the div with the class message_box
for the results not changing: the results come from the 2nd ajax call, which does not send your form data.
try to change your js to this:
$(document).ready(function() {
var delay = 1000;
// Campaign Submit Info
$('[name="search_submit"]').click(function(e) {
e.preventDefault();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var campaign_status = $('#filterformpost').find('#campaign_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();
console.log(lead_status)
console.log(campaign_status)
console.log(company_name)
console.log(tech_area)
console.log(firm_size)
console.log(firm_type)
console.log(country_name)
console.log(state_name)
console.log(start_date)
console.log(end_date)
$.ajax({
type: "POST",
// url: "https://tribalyze.com/CRM/server/login.php",
url: "search.php",
data: {
"lead_status": lead_status,
"campaign_status": campaign_status,
"company_name": company_name,
"tech_area": tech_area,
"firm_size": firm_size,
"firm_type": firm_type,
"country_name": country_name,
"state_name": state_name,
"start_date": start_date,
"end_date": end_date
},
beforeSend: function() {
$('.message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success: function(data) {
var result = $.parseJSON(data);
var string = '<table><thead><th>#</th><th>Lead ID</th><th>Name</th><th>Company</th><th>Location</th><th>Communication</th><th>Last Contact Date</th><th>Next Contact Date</th><th>Lead Status</th><th>Details</th></thead><tbody>';
/* from result create a string of data and append to the div */
var i = 1;
$.each(result, function(key, value) {
string += "<tr><td>" + i + "</td><td>" + value['Lead_Id'] + "</td><td>" + value['FirstName'] + ' ' + value['LastName'] + "</td><td>" + value['Company'] + "</td><td>" + value['State'] + '\n' + value['Country'] + "</td><td>" + value['Phone'] + '\n' + value['Email'] + "</td><td>" + value['LastContactDate'] + "</td><td>" + value['NextContactDate'] + "</td><td>" + value['LeadStatus'] + "</td><td><a href='#'>Click Here</a></td></tr>";
i = i + 1;
});
string += '</tbody></table>';
$("#filterRecords").html(string);
$('.message_box').html('');
}
});
});
});

How to make PHP Pagination is working in Mobile?

I have implement pagination in PHP.
It's works fine on Desktop and Laptop but but its not working on mobile devices.
member_list.php
<?php
include "../connection.php";
extract($_REQUEST);
$perPage = 50; // total records per page
// page
$conditionArr = array(); // array for condition
$condition = ""; // conditions
$pages = ""; // how many pages created
$type = "";
$company = "";
$message = "";
$rersArr = array();
$data = array();
$templeArr = array();
if ($sabhasadnumber != "") {
array_push($conditionArr, "sabhasad_number = '" . $sabhasadnumber . "'");
}
if ($Sakhe != "") {
array_push($conditionArr, "sakhe_id = '" . $Sakhe . "'");
}
if ($g != "") {
array_push($conditionArr, "gender LIKE '%" . $g . "%'");
}
$sql = "SELECT * FROM members WHERE village_id = '$id' and is_active = '1' and status = '1' ";
if (sizeOf($conditionArr) > 0) {
$condition = implode(" AND ", $conditionArr);
// echo $condition;
$sql .= " AND $condition";
}
$start = ($page - 1) * $perPage;
$sql1 = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$count = mysqli_num_rows($sql1);
$pages = ceil($count / $perPage);
$sql .= " ORDER BY members_id ASC";
$sql .= " limit $start,$perPage ";
$num_of_rows = mysqli_num_rows($sql1);
?>
<input type="hidden" name="total_page" id="total_page" value="<?php echo $pages; ?>">
<input type="hidden" name="current_page" class="current_page" id="current_page"
value="<?php echo $page; ?>">
<div class="member--items">
<div class="row gutter--15 AdjustRow">
<div class="row">
<?php
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-md-3 col-xs-6 col-xxs-12" style="height:300px">
<div class="member--item ">
<?php
$imgurl = "";
if ($row["image"] != "") {
$imgurl = "../admin/uploads/" . $row["image"];
} else {
$imgurl = "../admin/uploads/default_profile.jpg";
}
?>
<div class="img img-circle">
<a href="sabhasad_family.php?id=<?php echo $row['sabhasad_number']; ?>" class="btn-link">
<img src="<?php echo $imgurl; ?>" alt=""
style="height: 150px; width: 150px;">
<!-- <img src="../admin/uploads/default_profile.jpg" alt=""-->
<!-- style="height: 150px; width: 150px;">-->
</a>
</div>
<div class="name">
<h3 class="h fs--12">
<p>
<a href="sabhasad_family.php?id=<?php echo $row['sabhasad_number']; ?>"> <?php echo $row['surname'] ." " ;
echo $row['name'] ." ";
echo $row['middle_name'] ." "; ?></a></p>
</h3>
</div>
<div class="activity">
<p>સભાસદ નંબર : <?php echo $row['sabhasad_number']; ?> </p>
</div>
</div>
</div>
<?php
}
}
else { ?>
<?php
}
?>
member_list.js
var page = 1;
var total_page = "";
function getresult(searches) {
$.ajax({
url: "process/member_list.php",
type: "post",
data: {
sabhasadnumber: $("#sabhasadnumber").val(),
id: $("#village_id").val(),
Sakhe: $("#Sakhe").val(),
g: $("#g").val(),
page: page
},
success: function (data) {
// alert(data);
if (data != "") {
if (searches === true) {
$("#mlist").html(data);
} else {
$("#mlist").append(data);
}
}
}
});
}
$(document).ready(function () {
getresult(false);
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height()) {
if (parseInt($(".current_page:last").val()) < parseInt($("#total_page").val())) {
page = parseInt($(".current_page:last").val()) + 1;
// alert("scrool"+$(".current_page:last").val());
getresult(false);
}
}
});
$("#reset").click(function () {
$("#Sakhe").val("");
$("#sabhasadnumber").val("");
$("#g").val("");
page = 1;
getresult(true);
});
$("#shopsubmit").click(function () {
page = 1;
getresult(true);
});
$("#freset").click(function () {
$("#subcategory").val("");
page = 1;
getresult(true);
});
});
My front page code look like this
village.php
<?php
include 'connection.php';
include 'header.php';
$id = $_GET['id'];
$totalvillagemember = mysqli_num_rows(mysqli_query($conn, "select members_id from members WHERE village_id = $id AND is_active = '1' and status = '1' "));
$villagename = mysqli_query($conn, "SELECT name from village WHERE village_id = $id");
$row1 = mysqli_fetch_array($villagename);
?>
<body>
<!-- Preloader Start -->
<div id="preloader">
<div class="preloader--inner"></div>
</div>
<!-- Preloader End -->
<!-- Wrapper Start -->
<div class="wrapper">
<!-- Header Section Start -->
<!-- Header Section End -->
<!-- Page Header Start -->
<div class="page--header pt--60 pb--60 text-center" data-bg-img="img/page-header-img/bg.jpg" data-overlay="0.85">
<div class="container">
<div class="title">
<h2 class="h1 text-white">સભ્યો</h2>
</div>
<ul class="breadcrumb text-gray ff--primary">
<li>હોમ</li>
<li class="active"><span class="text-primary">સભ્યો</span></li>
</ul>
</div>
</div>
<!-- Page Header End -->
<!-- Page Wrapper Start -->
<section class="page--wrapper pt--80 pb--20">
<div class="container">
<div class="row">
<!-- Main Content Start -->
<div class="main--content col-md-8 pb--60" data-trigger="stickyScroll">
<div class="main--content-inner">
<!-- Filter Nav Start -->
<div class="filter--nav clearfix">
<div class="filter--link">
<h2 class="">ગામ : <?php echo $row1['name']; ?></h2>
<h2 class="">કુલ સભ્ય :<?php echo number_format($totalvillagemember) ?></h2>
</div>
</div>
<div id="mlist" name="mlist">
</div>
<!-- Page Count End -->
</div>
</div>
<!-- Main Content End -->
<!-- Main Sidebar Start -->
<div class="main--sidebar col-md-4 pb--60" data-trigger="stickyScroll">
<!-- Widget Start -->
<div class="widget">
<h2 class="h4 fw--700 widget--title">સભ્ય શોધો</h2>
<!-- Buddy Finder Widget Start -->
<div class="buddy-finder--widget">
<form name="village" id="village">
<div class="row">
<div class="col-xs-6 col-xxs-12">
<div class="form-group">
<label>
<span class="text-darker ff--primary fw--500">શોધી રહ્યો છુ</span>
<select class="form-control form-sm" name="g" id="g">
<option value=""> પસંદ કરો
</option>
<option value = "M">પુરુષ</option>
<option value = "F">સ્ત્રી</option>
</select>
</label>
</div>
</div>
<div class="col-xs-6 col-xxs-12">
<div class="form-group">
<label>
<span class="text-darker ff--primary fw--500">સભાસદ નંબર</span>
<input type="text" name="sabhasadnumber" id="sabhasadnumber"
class="form-control form-sm"
placeholder="સભાસદ નંબર">
</label>
</div>
</div>
<div class="col-xs-6 col-xxs-12">
<div class="form-group">
<label>
<input type="hidden" id="village_id" name="village_id"
value="<?php echo $id; ?>">
<span class="text-darker ff--primary fw--500">સાખે</span>
<select class="form-control form-sm" name="Sakhe" id="Sakhe">
<option value=""> સાખે પસંદ કરો
</option>
<?php
$query = mysqli_query($conn, "select * from sakhe where status = 1 order by sakhe_id asc");
while ($row = mysqli_fetch_array($query)) {
echo "<option value = " . $row['sakhe_id'] . ">" . $row['name'] . "</option>";
}
?>
</select>
</label>
</div>
</div>
<div class="col-xs-12">
<button type="button" onclick="getresult()" class="btn btn-primary" id="shopsubmit" name="shopsubmit">
સબમિટ કરો
</button>
<button type="button" onclick="getresult()" class="btn btn-primary"
id="reset" name="reset">
ફરીથી સેટ કરો
</button>
</div>
</div>
</form>
</div>
</div>
<!-- Widget End -->
</div>
<!-- Main Sidebar End -->
</div>
</div>
</section>
<!-- Page Wrapper End -->
<!-- Footer Section Start -->
<!-- Footer Widgets End -->
<!-- Footer Extra Start -->
<?php include 'footer.php'; ?>
<!-- Footer Section End -->
</div>
<!-- Wrapper End -->
<!-- Back To Top Button Start -->
<div id="backToTop">
<i class="fa fa-caret-up"></i>
</div>
<!-- Back To Top Button End -->
<!-- ==== Plugins Bundle ==== -->
<script src="js/plugins.min.js"></script>
<!-- ==== Color Switcher Plugin ==== -->
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<!-- ==== Main Script ==== -->
<script src="js/main.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<!--<script src="http://malsup.github.com/jquery.form.js"></script>-->
<script src="myjs/member_list.js"></script>
</body>
<!-- Mirrored from themelooks.us/demo/socifly/html/members.html by HTTrack Website Copier/3.x [XR&CO'2014], Mon, 30 Sep 2019 09:33:46 GMT -->
</html>
This pagination is not working only on Mobile devices.
Please help.

update mysqli query on ajax form submit

I have a dynamicaly php page that displays all results from database and i want to create a search bar that updates at every character the user inputs.
My problem is that i can't make the query update! he always displays no results. First I had the query in the same page as the form but that wouldnt work because the ajax would run all the code from the page when i used that url in the parameters so i splitted everything but it still doesnt work. Any sugestions?
PHP page - part with search bar --> categorias.php:
<div class="container">
<h2 class="title">Empresas De Confianza</h2>
<div class="col-lg-12">
<div class="col-lg-6 col-centered">
<form method="POST" action="buscador.php" id="search">
<input class="search-bar" type="text" name="filterName" id="filterName">
<button type="submit" hidden></button>
<?php
$msqliquery = "SELECT * FROM empresa WHERE categorias_id = $id AND menulogo IS NOT NULL";
$array = $connection->query($msqliquery);
?>
</form>
</div>
</div>
<?php
echo '<div class="row index-margin" id="results">';
if (mysqli_num_rows($array) == 0) {
echo "<h2 class='text-center'>No hemos encontrado ningún resultado con esa busqueda!</h2><ul class='text-center'><li class='list-categorias'><a class='fa-categorias fa fa-refresh' href='categorias.php?id=$id'></a></li></ul>";
};
while ($field = mysqli_fetch_array($array)) {
?>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3 parent size">
<a style="background-color:<?php echo $field['color'] ?>"
href="profile.php?id=<?php echo $field['id'] ?>">
<img src="/test<?php echo $field['menulogo'] ?>" class="logo img-grayscale">
<div class="hover-item"><h5 class="label-profile"><?php echo $field['nombre'] ?></h5></div>
</a>
</div>
<?php }
echo '</div>' ?>
´
Form/search bar handling --> buscador.php:
<?php
require 'config.php';
$connection = new mysqli($servername, $username, $password, $db);
session_start();
$id = $_SESSION['id'];
$filterName = $_POST['filterName'];
$msqliquery = "SELECT * FROM empresa WHERE categorias_id = $id AND menulogo
IS NOT NULL AND nombre COLLATE UTF8_GENERAL_CI LIKE '%$filterName%'";
$array = $connection->query($msqliquery);
Function for update at every character and ajax form submit:
$(document).ready(function () {
var timeoutID = null;
$('#filterName').keyup(function (e) {
clearTimeout(timeoutID);
timeoutID = setTimeout(searchEmpresa.bind(undefined, e.target.value), 500);
});
function searchEmpresa(str) {
console.log('search: ' + str);
$("#search").submit(function (event) {
$.ajax({
method: "POST",
url: 'buscador.php',
data: $("#filterName").val(),
success: function (data) {
console.log(data);
$("#results").load("categorias.php #results > *");
}
});
event.preventDefault();
});
}
})
You have to send data as object with key value pairs
data: {filterName:$("#filterName").val()},
Also you have to correct method: 'post', So you should have method of posting not type of posting
Hope it will help you.
put this code in your buscador.php
<?php
if (mysqli_num_rows($array) == 0) {
echo "<h2 class='text-center'>No hemos encontrado ningún resultado con esa
busqueda!</h2><ul class='text-center'><li class='list-categorias'><a
class='fa-categorias fa fa-refresh' href='categorias.php?id=$id'></a></li>
</ul>";
};
while ($field = mysqli_fetch_array($array)) {
?>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3 parent size">
<a style="background-color:<?php echo $field['color'] ?>"
href="profile.php?id=<?php echo $field['id'] ?>">
<img src="/test<?php echo $field['menulogo'] ?>" class="logo img-
grayscale">
<div class="hover-item"><h5 class="label-profile"><?php echo
$field['nombre'] ?></h5></div>
</a>
</div>
<?php }
echo '</div>' ?>
and append it to your div with id result
$('#result').append(data);

AJAX pagination not working properly after new entry

I am having a main page "landing.php", here in a div i am calling another page using ajax function "fetch_pages.php". In fetch_pages.php, i am loading data from db as 5 records at a time, when the user reaches the end of page then next 5 records are displayed. Thats working perfectly.
But in landing.php, when i enter a new record and reload the div, then the div content becomes blank, it doesn't show the latest content, after refreshing the full page manually then its again shows all the records. Can't understand whats wrong, kindly help.
landing.php page
<div class="mainsection">
<div>
<div class="pull-left postimage"><?php echo "<img src=profile_pic/".$ProfilePic ." />"; ?></div>
<div class="pull-left posttext">
<div class="postname"><?php echo $Name; ?></div>
<p><?php echo $UT." - ".$Designation." - ".$Company; ?></p></div>
<textarea id="posting" name="posting" rows="2" cols="50" placeholder="Share something here..."></textarea>
<div class="clear"></div>
<hr>
</div>
<div class="fileUpload btn btn-default">
<span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i>Upload Image</span>
<input type="file" class="upload" />
</div>
<div>
<input class="postall btn btn-primary pull-right" type="submit" onClick="UserPost()" value="Post">
</div>
<div class="clear"></div>
</div>
<!-- Loading User Posts -->
<div id="mainsectionID">
<div id="results"><!-- results appear here as list --></div>
</div>
<script>
(function($){
$.fn.loaddata = function(options) {// Settings
var settings = $.extend({
loading_gif_url : "images/ajax-loader.gif", //url to loading gif
end_record_text : 'No more records found!', //no more records to load
data_url : 'fetch_pages.php', //url to PHP page
start_page : 1 //initial page
}, options);
var el = this;
loading = false;
end_record = false;
contents(el, settings); //initial data load
$(window).scroll(function() { //detact scroll
if($(window).scrollTop() + $(window).height() >= $(document).height()){ //scrolled to bottom of the page
contents(el, settings); //load content chunk
}
});
};
//Ajax load function
function contents(el, settings){
var load_img = $('<img/>').attr('src',settings.loading_gif_url).addClass('loading-image'); //create load image
var record_end_txt = $('<div/>').text(settings.end_record_text).addClass('end-record-info'); //end record text
if(loading == false && end_record == false){
loading = true; //set loading flag on
el.append(load_img); //append loading image
$.post( settings.data_url, {'page': settings.start_page}, function(data){ //jQuery Ajax post
if(data.trim().length == 0){ //no more records
el.append(record_end_txt); //show end record text
load_img.remove(); //remove loading img
end_record = true; //set end record flag on
return; //exit
}
loading = false; //set loading flag off
load_img.remove(); //remove loading img
el.append(data); //append content
settings.start_page ++; //page increment
})
}
}
})(jQuery);
$("#results").loaddata(); //load the results into element
</script>
fetch_pages.php code-
<?php
session_start();
include 'db.php'; //include config file
$UserID=$_SESSION['uid'];
$UserType=$_SESSION['utype'];
$GLOBALS['lks']=0;
$GLOBALS['cmnts']=0;
$GLOBALS['disabled']="";
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
?>
<!---post start -->
<?php
//fetch records using page position and item per page.
$results = $linkID1->query("select slno,posts,img_link,video_link,likes,comments,shares,post_date,post_time,UserID from user_posts where UserID='$UserID' or UserID in(select MyFriendsUserID from user_connections where MyUserID='$UserID') or UserID in(select MyUserID from user_connections where MyFriendsUserID='$UserID') order by slno desc LIMIT $position, $item_per_page")
or
die(mysqli_error());
//output results from database
?>
<?php
while($row = mysqli_fetch_array($results))
{ //fetch values
$CUID=$row['UserID'];
$stmt = $linkID1->prepare("select Name,Company,Designation,UserType from user_details where UserID=?");
$stmt->bind_param("s", $CUID);
$stmt->execute();
$stmt->bind_result($Name2,$Company2,$Designation2,$UType);
$stmt->fetch();
$stmt->close();
$UT2='';
if($UType=='A')
{
$UT2='Advertiser';
}
else if($UType=='P')
{
$UT2='Publisher';
}
$stmt = $linkID1->prepare("select ProfilePic from user_picture where UserID=?");
$stmt->bind_param("s", $CUID);
$stmt->execute();
$stmt->bind_result($PPic);
$stmt->fetch();
$stmt->close();
?>
<div class="mainsection">
<div>
<div class="pull-left postimage"><?php echo "<img src=profile_pic/".$PPic ." />"; ?></div>
<div class="pull-left posttext">
<div class="postname"><?php echo $Name2; ?></div>
<p><?php echo $UT2." - ".$Designation2." - ".$Company2; ?></p></div>
<div class="clear"></div>
<div class="postdowntxt"><p><?php echo $row['posts']; ?></p></div>
<hr>
</div>
<div class="btnclasess" id="likescommentID<?php echo $row[slno]; ?>">
<div class="likescomment"><?php dataLC($linkID1, $row['slno'],$CUID); ?><a style="padding-right: 7px" href="#"><?php if($GLOBALS['lks']==0){echo '';}else{ echo $GLOBALS['lks']." Likes"; } ?></a><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></div>
<div class="pull-left likebtn"><button <?php echo $disabled; ?> class="btn" id="likeButton<?php echo $row[slno]; ?>" onClick="connect(<?php echo $row[slno]; ?>)"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</button></div>
<button class="pull-left btnhideshow show_hide" data-toggle="collapse" data-target="#demo<?php echo $row['slno']; ?>"><li class="fa fa-comments show_hide" style="margin-right: 6px;"></li>Comment</button>
<button class="pull-left btnhideshow show_hide"><li class="fa fa-share-alt show_hide" style="margin-right: 6px;"></li>Share</button>
<div class="clear"></div>
<div class="clear"></div>
</div>
<!-- Display All Comments -->
<div id="myModal<?php echo $row['slno']; ?>" class="modal">
<div id="DialogDiv<?php echo $row['slno']; ?>">
<!-- Modal content -->
<div class="modal-content" id="modalDialog<?php echo $row['slno']; ?>">
<p class="popupheading"><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></p>
<?php
$result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where PostID='$row[slno]' order by upc.slno")
or
die(mysqli_error());
while($row2 = mysqli_fetch_array($result2))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row2['Comment']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<div id="nReply2<?php echo $row2['slno']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox2<?php echo $row2['slno']; ?>" onkeyup="enter_reply2(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>,<?php echo $row['slno']; ?>);">
</div>
</div>
<div class="clear"></div>
<!-- Nested Comments Starts -->
<div id="NestedCmntsDialog" class="nestedcmnts">
<?php
$result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
or
die(mysqli_error());
while($row3 = mysqli_fetch_array($result3))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row3['Comments']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply2(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<?php
}
?>
</div>
<!-- Nested Comments Ends -->
<?php
}
?>
<div class="invidone">Close</div>
</div>
</div>
</div>
<!-- Display All Comments -->
<div class="slidingDiv collapse" id="demo<?php echo $row['slno']; ?>">
<div class="viewallcomments">View All Comments</div>
<div class="allcomment" id="commentsLoad<?php echo $row['slno']; ?>">
<?php
$result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where upc.PostID='$row[slno]' order by upc.slno desc limit 3")
or
die(mysqli_error());
while($row2 = mysqli_fetch_array($result2))
{
?>
<!-- Showing Top 3 Comments -->
<div id="nestedReplyDiv<?php echo $row['slno']; ?>">
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row2['Comment']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply<?php echo $row2['slno']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox<?php echo $row2['slno']; ?>" onkeyup="enter_reply(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<!-- Nested Comments Starts -->
<div id="NestedCmnts" class="nestedcmnts">
<?php
$result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
or
die(mysqli_error());
while($row3 = mysqli_fetch_array($result3))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row3['Comments']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<?php
}
?>
</div>
<!-- Nested Comments Ends -->
</div>
<?php
}
?>
</div>
<textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>
<!--<div class="fileUpload second_fileupload btn btn-default pull-left">
<span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i></span>
<input type="file" class="upload" />
</div>-->
<div class="clear"></div>
</div>
</div>
<?php
}
?>
<!--post end-->
<?php
function dataLC($linkID1, $val, $CUID)
{
$UserID=$CUID;
$LgUserID=$_SESSION['uid'];
$stmt = $linkID1->prepare("select likes,comments from user_posts where slno=?");
$stmt->bind_param("s", $val);
$stmt->execute();
$stmt->bind_result($lksD,$cmntsD);
$stmt->fetch();
$stmt->close();
$GLOBALS['lks']=$lksD;
$GLOBALS['cmnts']=$cmntsD;
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $UserID,$UserID,$val);
$stmt->execute();
$stmt->bind_result($cnt);
$stmt->fetch();
$stmt->close();
if($cnt>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $UserID,$LgUserID,$val);
$stmt->execute();
$stmt->bind_result($cnt2);
$stmt->fetch();
$stmt->close();
if($cnt2>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $LgUserID,$UserID,$val);
$stmt->execute();
$stmt->bind_result($cnt3);
$stmt->fetch();
$stmt->close();
if($cnt3>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
}
?>
<script>
$('.btn').on('click', function(e)
{
$(this).prop('disabled',true); });
</script>
<script>
function UserPost() {
var x = document.getElementById('posting').value;
var timezone_offset_minutes = new Date().getTimezoneOffset();
timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
$.ajax({
type: "POST",
url: "user-post.php?p="+x+"&tz="+timezone_offset_minutes,
success: function(data) {
$("#mainsectionID").load(" #mainsectionID");
document.getElementById('posting').value='';
}
});
}
</script>
<script type="text/javascript">
function connect(num) {
$.ajax({
type: "POST",
url: "user-likes.php?id="+num,
success: function(data) {
if(data=='1')
{
$("#likescommentID"+num).load(" #likescommentID"+num);
}
}
});
}
function enter_comment(postid,userpostedid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('commentarea'+postid).value;
$.ajax({
type: "POST",
url: "user-comments.php?id="+postid+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#commentsLoad"+postid).load(" #commentsLoad"+postid);
$("#likescommentID"+postid).load(" #likescommentID"+postid);
}
}
});
document.getElementById('commentarea'+postid).value='';
}
else{
//nothing
}
}
</script>
<script type="text/javascript">
function enter_reply(slno,userpostedid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('nReplyBox'+slno).value;
$.ajax({
type: "POST",
url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#commentsLoad"+slno).load(" #commentsLoad"+slno);
}
}
});
document.getElementById('nReplyBox'+slno).value='';
}
else{
//nothing
}
}
function enter_reply2(slno,userpostedid,dno) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('nReplyBox2'+slno).value;
$.ajax({
type: "POST",
url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#DialogDiv"+dno).load(" #DialogDiv"+dno);
//$("#modalDialog"+dno).load(" #modalDialog"+dno);
}
}
});
document.getElementById('nReplyBox2'+slno).value='';
}
else{
//nothing
}
}
</script>
<script type="text/javascript">
function enter_nested_reply(slno,userpostedid,divNo,pid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var tot=(slno*slno)+pid;
var cmnt = document.getElementById('nReplyBox'+tot).value;
$.ajax({
type: "POST",
url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
success: function(data2) {
if(data2=='1')
{
$("#nestedReplyDiv"+divNo).load(" #nestedReplyDiv"+divNo);
}
}
});
document.getElementById('nReplyBox'+tot).value='';
}
else{
//nothing
}
}
function enter_nested_reply2(slno,userpostedid,divNo,pid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var tot=(slno*slno)+pid;
var cmnt = document.getElementById('nReplyBox2'+tot).value;
$.ajax({
type: "POST",
url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
success: function(data2) {
if(data2=='1')
{
$("#DialogDiv"+divNo).load(" #DialogDiv"+divNo);
//$("#modalDialog"+divNo).load(" #modalDialog"+divNo);
}
}
});
document.getElementById('nReplyBox2'+tot).value='';
}
else{
//nothing
}
}
</script>
<script>
function LoadComment(num) {
var modal2 = document.getElementById('myModal'+num);
var span2 = document.getElementById("close3");
span2.onclick = function() {
modal2.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal2) {
modal2.style.display = "none";
}
}
var x = document.getElementById('myBtn2');
modal2.style.display = "block";
}
</script>
Problem resolved. Called the pagination again in the success method of ajax.

Form loaded into div w/ AJAX no longer submits

Let me start by apologizing for the information overload. I have no idea what is not working, so I included a little of everything here.
I have a page named jobs.php that shows a table of open 'jobs' on the left side. When the add job button is clicked, the form to add a new job is loaded into the div on the right side of the page using this:
//Get Next Job
$query = "SELECT * FROM jobs WHERE job_id = (SELECT MAX(job_id) FROM jobs)";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
$topjob = $result->fetch_assoc();
$nxtjob = $topjob['job_id'] + 1;
<button class="btn btn-primary pull-right ajaxCall" id="addJobBtn" onclick="nxtJob('<?php echo $nxtjob; ?>')">Add Job</button>
function nxtJob(job) {
var nxtjob = job;
$("#jobDetails").html("Loading...");
$.ajax({
type: "GET",
data: {'id':nxtjob},
url: "addjob.php",
async: true,
success: function(data) {
$("#jobDetails").html(data);
}
});
}
The reasoning behind the get variable is that I need the next job # to be used as a value in the form.
The form itself is on addjob.php, and the very simplified version is this:
<?php
require 'database.php';
if (isset($_POST['addNewJob'])) {
$error = '';
//Check Job # for duplicate if manually changed
$job = $_POST['addjob'];
$query = "SELECT job_id from jobs WHERE job_id = '$job'";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
if (mysqli_num_rows($result) > 0) {
$error .= '<br/>Job # already exists.'
}
if ($error == '') {
//Set variables for insert
$job = $mysqli->real_escape_string($_POST['addjob']);
$status = $mysqli->real_escape_string($_POST['addstatus']);
$sql = "INSERT INTO jobs (job_id, status)
VALUES ('$job', '$status')";
if (mysqli_query($mysqli, $sql)) {
$validation = '< div class="alert alert-success" > Job ' . $job . ' Successfully Added </div >';
} else {
$validation = '<div class="alert alert-danger" > "ERROR: Could not able to execute' . $sql . mysqli_error($mysqli);
}
} else {
$validation = ' <div class="alert alert - danger">Job Not Added:' . $error . '</div>';
}
?>
<form class="form - horizontal" method="post" id="addJobForm">
<div class="form - group">
<label for="addjob" class="col - sm - 2 control - label">Job #</label>
<div class="col - sm - 4">
<input type="text" class="form - control" name="addjob"
value=" <?php echo $nxtjob; ?>">
</div>
<label for="addstatus" class="col-sm-2 control-label">Status</label>
<div class="col-sm-4">
<?php
$options = array("New", "In Progress", "Waiting for Parts", "Ready for Customer", "Completed");
?>
<select class="form-control" name="addstatus">
<?php foreach ($options as $option): ?>
<option>
<?php echo $option; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<button type="submit" name="addNewJob" id="addNewJob" class="btn btn-primary pull-right">Submit New
Job
</button>
</form>
<?php echo $validation; ?>
When the add job button is clicked on jobs.php (below), the form loads beautifully, but it doesn't work.
<div class="row">
<div class="col-md-4">
<table class="table table-hover" id="jobTable" data-link="row">
<thead>
<tr>
<th class="col-md-2">Job #</th>
<th class="col-md-4">Customer Name</th>
<th class="col-md-6">Description</th>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($jobs)) {
// Print out the contents of the entry
date_default_timezone_set('America/Los_Angeles');
$startdate = date("m/d/Y", strtotime($row['started']));
echo '<tr>';
echo '<td><a class="ajaxCall" href="#" rel="' . $row['job_id'] . '"></a>' . $row['job_id'] . '</td>';
echo '<td>' . $row['cust_name'] . '</td>';
echo '<td class="col-lg-2">' . $row['description'] . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<div class="col-md-8">
<div id='jobDetails'></div>
</div>
</div>
When I click Submit New Job, the right side of the page simply goes blank. The form disappears, and no new entry is created in the sql table. However, the form works just fine if I use it directly from addjob.php.
I've read about binding after an AJAX call, and I'm guessing it has something to do with that, but I can't seem to get it working. This is my first attempt at AJAX, so any help is appreciated.

Categories