I want to show my data using the Next, Previous, First and Last buttons.
When I click on Next and Previous button 30 or more times, my browser will hang and ajax will not respond.
Please see the below code:
Main page script
<button id="lastbutton" onclick=" getlastinformation();">Last</button>
<button id="previousbutton">Previous</button>
<button id="nextbutton" onclick="getnextinformation();">Next</button>
<button id="firstbutton" onclick="getfirstinformation();">First</button>
<input type="hidden" id="change_id" name="change_id">
<input type="text" class="form-control" id="typedescription" readonly>
<input type="text" class="form-control" id="cityname" readonly>
function getfirstinformation()
{
document.getElementById('change_id').value = first_element;
put_data(first_element);
}
function getnextinformation()
{
var next_element = parseInt(document.getElementById('change_id').value);
if(next_element!=last_element)
next_element++;
document.getElementById('change_id').value = next_element;
put_data(next_element);
}
function getpreinformation()
{
var pre_element = parseInt(document.getElementById('change_id').value);
if(pre_element!=first_element)
pre_element--;
document.getElementById('change_id').value = pre_element;
put_data(pre_element);
}
function getlastinformation()
{
var last = localStorage.getItem("val");
if(last==null)
last = last_element;
else
{
last = localStorage.getItem("val");
localStorage.clear();
}
document.getElementById('change_id').value = last;
put_data(last);
}
function put_data(val)
{
// Add this line for next previous from Search Button
var id = array_of_records[val]['id'];
getalldata(id);
}
function getalldata(val)
{
$.ajax({
type: "POST",
url: "get_account.php",
data:'id1='+val,
success: function(data)
{
var supplier_array = new Array();
supplier_array = data.split("|");
$(".get-code").val(supplier_array[0]);
$("#typedescription").val(supplier_array[23]);
$("#cityname").val(supplier_array[24]);
}
});
}
Ajax requested URL file code
get_account.php
$customer_details = "";
if(!empty($_POST["id1"]))
{
$query ="SELECT * FROM `ledger WHERE id = '" . $_POST["id1"] . "' ORDER BY id DESC";
$results = mysqli_query($connection, $query);
while($state=mysqli_fetch_assoc($results))
{
$customer_details = $state["id"]."|".$state["type"];
$query2 ="SELECT description FROM type WHERE type = '" . $state["type"]. "' ";
$results2 = mysqli_query($connection, $query2);
while($state2=mysqli_fetch_assoc($results2))
{
$customer_details = $customer_details."|".$state2["description"];
}
$query3 ="SELECT cityname FROM citymast WHERE citycode = '".$state["citycode"]."' ";
$results3 = mysqli_query($connection, $query3);
while($state3=mysqli_fetch_assoc($results3))
{
$customer_details = $customer_details."|".$state3["cityname"];
}
}
}
echo $customer_details;
Abort code in my ajax request function
var currentRequest = null;
function getalldata(val) {
currentRequest = $.ajax({
type: "POST",
data:'id1='+val,
url: "master/get_account.php",
beforeSend : function(){ if(currentRequest != null)
{ currentRequest.abort(); } },
success: function(data) {
var supplier_array = new Array();
supplier_array = data.split("|");
$("#typedescription").val(supplier_array[23]);
$("#cityname").val(supplier_array[24]); } }); }
How can I fix the above code such that it fixes the hanging of the browser when sending button clicks 30 or more times?
Related
I want to do it so when a user clicks a checkbox it sets the tinyint value that's set in the database from 0 to 1 and vice-versa. My ajax.js:
function emailNextWithAddress(chk, address) {
var nextEmail, inside_where;
if (chk.checked === true) {
$.ajax({
url: "marca_enviado.php",
data: address,
type: "get",
success: function () {
nextEmail = document.createElement('input');
nextEmail.id = address;
nextEmail.value = address;
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
},
error: function () {
console.log("Erro!");
}
});
} else {
$.ajax({
url: "desmarca_enviado.php",
data: address,
type: "get",
success: function () {
inside_where = document.getElementById(address);
inside_where.parentNode.removeChild(inside_where);
},
error: function () {
console.log("Erro!");
}
});
}
return false;
}
And the part that I'm trying to update is(dbh.php is the connection to the database):
<?php
include_once 'dbh.php';
$id = $_GET['address'];
$updateEnviado = "UPDATE escolas SET Enviado = '$id'";
$result = mysqli_query($conn , $updateEnviado);
?>
In my index.php the part of the code that's being outputted is:
$execItems = $conn->query("SELECT Nome,EmailGeral,Enviado FROM escolas");
while($infoItems = $execItems->fetch_array()){
echo "
<tr style=\"border: 1px solid black;\">
<td>".$infoItems['Nome']."</td>
<td>".$infoItems['EmailGeral']."</td>
<td><input type=\"checkbox\" ".($infoItems['Enviado']?' checked':' ')." onclick=\"emailNextWithAddress(this, '".$infoItems['EmailGeral']."');\"/></td>
</tr>
";
}
?>
Note that I'm only interested in updating the checkbox.
I have a function called function getContactsToForm();
This function runs on a div row called results that holds the values from my sql. On click each row is supposed to load this function grab the data from li[0] and pass it on to the rest of the function.
I seem to be getting it to work all right, however the Li's show up empty on my console log even though the table is populated. I assume that means that the sequencing is wrong.
Previously I had a working sample that had everything it table rows. The original function commented out would use the Tr tags and grab the value. The function was called within the getContacts() function and it all worked well, with the LI I am having trouble. Any thoughts?
functions.js
// JavaScript Document
//formoverlay
function formSubmit() {
$.ajax({
type: 'POST',
url: 'contactsinsert.php',
data: $('#frmBox').serialize(),
success: function(response) {
$('#success').html(response);
}
});
var form = document.getElementById('frmBox').reset();
window.location.reload();
return false;
}
$(document).ready(function() {
$('#srchbtn').click(function start() {
getContacts();
});
});
function getContacts() {
var txtsearch = $('#txtsearch').val();
$.ajax({
url: 'contactstable.php',
type: "POST",
//dataType: "json",
data: ({
txtsearch: txtsearch
}),
success: function(response) {
$('#displayContacts').html(response);
//addRowHandlers();
//getContactsToForm();
}
});
}
window.onload = getContacts();
/*function addRowHandlers() {
console.log("hi");
var table = document.getElementById("resultstable");
var rows = table.getElementsByTagName("li");
console.log(rows[0]);
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
console.log(currentRow);
var createClickHandler = function(row) {
return function() {
*/
function getContactsToForm() {
var table = document.getElementById("resultstable");
var rows = table.getElementsByTagName("ul")['results'];
console.log(rows);
var lis = table.getElementsByTagName('li')[0];
console.log(lis);
var id = lis.innerHTML;
console.log(id);
//alert("id:" +id);
document.getElementById("id").value = id;
$.ajax({
url: "inputtest.php",
success: function(result) {
var frm = document.getElementById("frmBox2");
var ID = document.getElementById("id").value;
if (/\S/.test(ID)) {
ajax_request(this.action, {
"action": "fetch",
"ID": ID
}, process_response);
} else {
alert("No ID supplied");
}
function ajax_request(url, data, callback) {
var i, parts, xhr;
// if data is an object, unroll as HTTP post data (a=1&b=2&c=3 etc.)
if (typeof data == "object") {
parts = [];
for (i in data) {
parts.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
data = parts.join("&");
}
// create an XML HTTP Request object
xhr = new XMLHttpRequest();
if (xhr) {
// set a handler for changes in ready state
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// check for HTTP status of OK
if (xhr.status == 200) {
try {
callback(JSON.parse(xhr.responseText));
} catch (e) {
console.log(xhr.responseText); // for debug
alert("AJAX request incomplete:\n" + e.toString());
}
} else {
alert("AJAX request failed: " + xhr.status);
}
}
};
// open connection and send payload
xhr.open("GET", "inputtest.php" + "?" + data, true);
xhr.send(null);
}
}
/**
* process the response, populating the form fields from the JSON data
* #param {Object} response the JSON data parsed into an object
*/
function process_response(response) {
var frm = document.getElementById("frmBox2");
var i;
console.dir(response); // for debug
for (i in response) {
if (i in frm.elements) {
frm.elements[i].value = response[i];
}
}
}
}
});
};
// currentRow.onclick = createClickHandler(currentRow);
// }
// }
//window.onload = addRowHandlers();
function openNav() {
document.getElementById("myNav").style.width = "100%";
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
window.location.reload();
}
function openCon() {
document.getElementById("conNav").style.width = "100%";
}
function closeCon() {
document.getElementById("conNav").style.width = "0%";
var form = document.getElementById('frmBox').reset();
}
function enablebuttons() {
document.getElementById("insert").disabled = false;
}
contactstable.php (calls the mysql and receives contacts)
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php
include_once "iud.php";
$arrayval = array();
$search=$_POST['txtsearch'];
$search1 = explode(" ", $search);
array_push($arrayval, $search1);
foreach ($arrayval as $val){
$orIndex = checkOr($val);
if(empty($orIndex)){
$resultstable = getResults($val);
$resultstable1 = buildTable($resultstable);
print($resultstable1);
}else{
print"there is an or here";
$resultstable = getResults($orIndex);
$resultstable1 = buildTable($resultstable);
print($resultstable1);
}
}
buildTable($resultstable);
/*if (empty($orIndex)){
print "no or";
$resultstable = getResults($val);
$resultstable1 = buildTable($resultstable);
print $resultstable1;
function getResults($array){
include_once "iud.php";
$db = connectDatabase();
$totalResults = array();
$length = count($array);
for ($i = 0; $i < $length; $i++){
$outputDisplay = "";
$myrowcount = 0;
$sql_statement = "SELECT id, firstname, lastname, pcat, position, state ";
//, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes ";
$sql_statement .= "FROM contacts ";
$sql_statement .= "WHERE (firstname LIKE '%$array[$i]%' or lastname LIKE '%$array[$i]%')";
$sql_statement .= "ORDER BY lastname, firstname";
$sqlResults = selectResults($db, $sql_statement);
$error_or_rows = $sqlResults[0];
if (substr($error_or_rows, 0 , 5) == 'ERROR')
{
$outputDisplay .= "<br />Error on DB";
$outputDisplay .= $error_or_rows;
} else {
$totalResults = array_merge($totalResults, $sqlResults);
//$totalResults = array_map("unserialize", array_unique(array_map("serialize", $totalResults)));
$arraySize = $error_or_rows;
}
}
//return $totalResults;
//print $arraySize;
//print_r($error_or_rows);
return $totalResults;
}
function buildTable($totalResults){
include_once "iud.php";
$outputDisplay = "";
//$outputDisplay .= '<table id="resultstable" style="overflow-x:auto;">';
//$outputDisplay .= '<tr><th align="left">ID</th><th align="left" width="30%">First Name</th><th align="left" width="30%">Last Name</th><th align="left" width="30%">Pages Category</th><th align="left" width="30%">Position</th><th align="left" width="30%">state</th></tr>';
$outputDisplay .= '<div id="resultstable">';
$outputDisplay .= '<div id="headers">';
$outputDisplay .= '<ul id="headers">';
$myrowcount = 0;
for ($i=0; $i < count($totalResults); $i++)
{
$myrowcount++;
$contactid = $totalResults[$i]['id'];
$firstname = $totalResults[$i]['firstname'];
$lastname = $totalResults[$i]['lastname'];
$pcat = $totalResults[$i]['pcat'];
$position = $totalResults[$i]['position'];
$state = $totalResults[$i]['state'];
$outputDisplay .= '<ul id="results">';
$outputDisplay .='<li>'.$contactid.'</li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon();getContactsToForm();">'.$firstname.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$lastname.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$pcat.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$position.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$state.'</span></li>';
$outputDisplay .= '</ul>';
//echo $myrowcount;
}
$outputDisplay .= "</div>";
return $outputDisplay;
}
function checkOr($searchArray){
if (in_array("OR",$searchArray)){
$orPos = array_search("OR", $searchArray);
//$surrVal =array();
//$surrVal = array(--$orPos, ++$orPos);
if (!empty($orPos)){
$surrVal = "";
$surrVal = --$orPos;
$orValArray = array();
array_push($orValArray,$searchArray[$surrVal]);
$surrVal = $orPos+2;
array_push($orValArray,$searchArray[$surrVal]);
return $orValArray;
}
}
}
The results I get are:
209AnisBakerDC
but from the console side:
I have a page with ajax pagination on it, I am currently able to check if the session exists and process accordingly. However, I cannot seem to remove the menu or reload the page properly if the session has expired. Only the menu remains and the login page shows in the small area where the table was.
Controller code
public function index()
{
$conditions = array();
$data = array();
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search(array('limit'=>$this->get_per_page()));
$data['user'] = $this->AccountModel->get_person($this->get_person_id());
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('layout/admins/common/header');
$this->load->view('layout/admins/common/navigation');
$this->load->view('layout/admins/common/title');
$this->load->view('layout/admins/common/errors');
$this->load->view('layout/admins/common/search');
$this->load->view('admins/documents/index',$data);
$this->load->view('layout/admins/common/footer');
}
public function search(){
if($this->input->is_ajax_request()){
if(!$this->logged_in()){
$this->index();
}else{
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('admins/documents/ajax_pagination', $data, false);
}
}
}
My JS Code that is placed in the view
<script>
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (html) {
$('#list').html(html);
$('.loading').fadeOut("slow");
}
});
}
function changeStatus(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/ChangeStatus/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
console.log(result);
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
function deleteDocument(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/Delete/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
</script>
i am assuming $('#list').html(html); code loads the html in the dom. instead of directly sending the html from php you can send a json containing the html as well the login status. like this.
$data = [
'login_status' => 1 // or 0,
'html' => $html // full html your are sending now
];
echo json_encode($data);
then in ajax success.
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (response) {
var data = $.parseJSON(response);
if(data.login_status == 0)
{
window.location.href = 'redirect to login page';
}
if(data.login_status == 1)
{
$('#list').html(data.html);
}
$('.loading').fadeOut("slow");
}
});
}
controller method :
public function search(){
if($this->input->is_ajax_request()){
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$html = $this->load->view('admins/documents/ajax_pagination', $data, true);
$res['html'] = $html;
$res['login_status'] = ($this->logged_in()) ? '1' : '0';
echo json_encode($res);
}
This code submits a form and an ID # to addBand.php. The php inserts the form data into a DB, and then echos an array that houses 2 arrays: 1 is an array of ids, the other is a string to update an HTML select element. I've only included the PHP that generates and echos the arrays.
i keep getting "Uncaught TypeError: Cannot read property 'selectRestults' of undefined" with the following code. what am I doing wrong?
javascript/jquery:
$(function() {
$("#addBandForm").submit(function(event) {
event.preventDefault();
var globalShowID = '&id=' + window.globalShowID;
$.ajax({
url: "womhScripts/addBand.php",
type: "POST",
data: $('#addBandForm').serialize() + globalShowID,
success: function(msg) {
var actArray = msg['actIDArray'];
var bandArray = msg['bandSelectArray'];
var result = bandArray['selectResults'];
window.globalShowID='';
$("#band1").html(result)
},
error:function(errMsg) {
console.log(errMsg);
}
});
});
});
addBand.php
$bandSelectArray = array();
$actIDArray = array();
$bandResults = "";
if (isset($_POST['id']))
{
$ShowID = $_POST['id'];
$actSQL = mysqli_query($link, "SELECT actID FROM Act WHERE showID=".$ShowID."");
while($actRow = mysqli_fetch_array($actSQL))
{
$actIDArray[] = array(
'actID' => $actRow['actID'],
);
}
}
$selectBandSQL = mysqli_query ($link, "SELECT bandID, bandName FROM Band");
while ($row = mysqli_fetch_array($selectBandSQL))
{
$bandID = $row['bandID'];
$bandName2 = $row['bandName'];
$bandResults .= '<option value="'.$bandID.'">'.$bandName2.'</option>';
}
$bandSelectArray['selectResults'] = $bandResults;
$resultArray = array();
$resultArray['actIDArray'] = $actIDArray;
$resultArray['bandSelectArray'] = $bandSelectArray;
echo json_encode($resultArray);
I can comment with only first item in while loop, When I tried to comment with another item it's always display alert box You know you need to write a comment right?. I think it can't get comment text on another item in my loop, What's wrong with my code?
I've got this comment code from this link.
My code:
Ajax in index.php
<script type="text/javascript">
$(function () {
// Alert(event.timeStamp);
$('.new-com-bt').live('click', function (evt) {
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* When you click on the cancel button */
$('.bt-cancel-com').click(function () {
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function () {
$('.new-com-bt').fadeIn('fast');
});
});
// On post comment click
$('.bt-add-com').live('click', function (evt) {
var comment_on_id = $("input[name=comment_on_id]");
var theCom = $("textarea[name=comment-text]");
var theName = $('#name-com');
var theMail = $('#mail-com');
if (!theCom.val()) {
alert('You know you need to write a comment right?');
} else {
$.ajax({
type: "POST",
url: "ajax/add-comment.php",
data: 'act=add-com&id_post=' + comment_on_id.val() + '&name=' + theName.val() + '&email=' + theMail.val() + '&comment=' + theCom.val(),
success: function (html) {
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function () {
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
scroll.js in index.php
var ajax_arry=[];
var ajax_index =0;
var sctp = 100;
$(function(){
$('#loading').show();
$.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page=1",
cache: false,
success: function(response){
$('#loading').hide();
$('#demoajax').html(response);
}
});
$(window).scroll(function(){
var height = $('#demoajax').height();
var scroll_top = $(this).scrollTop();
if(ajax_arry.length>0){
$('#loading').hide();
for(var i=0;i<ajax_arry.length;i++){
ajax_arry[i].abort();
}
}
var page = $('#demoajax').find('.nextpage').val();
var isload = $('#demoajax').find('.isload').val();
if ((($(window).scrollTop()+document.body.clientHeight)==$(window).height()) && isload=='true'){
$('#loading').show();
var ajaxreq = $.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page="+page,
cache: false,
success: function(response){
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$('#loading').hide();
$('#demoajax').append(response);
}
});
ajax_arry[ajax_index++]= ajaxreq;
}
return false;
if($(window).scrollTop() == $(window).height()) {
alert("bottom!");
}
});
});
scroll.php
<?php
include('db.php');
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit);
}
function showData($data,$con,$limit){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "select * from infinitescroll order by id asc limit $start,$limit";
$str='';
$data = $con->query($sql);
if($data!=null && $data->num_rows>0){
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
$post_to_itemid = $row['id'];
$str.="<div class='data-container'><p>".$row['id']."</p><p>".$row['firstname']."</p><p>".$row['lastname']."</p>";
$str .= "<div class='new-com-bt'>
<span>Type something ..</span>
</div>
<div class='new-com-cnt'>
<br>
<input type='hidden' value='".$post_to_itemid."' name='comment_on_id'>
<textarea class='the-new-com' name='comment-text'></textarea>
<div class='bt-add-com'>Comment</div>
<div class='bt-cancel-com'>Cancel</div>
</div></div>";
}
$str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
}else{
$str .= "<input type='hidden' class='isload' value='false'><p>Finished</p>";
}
echo $str;
}
?>