I'm new to jquery & Ajax.
I have a php file with jquery inside it, which loads content from another php file on selection of a date
$("#datepicker3").change(function(){
$.ajax({
type: "POST",
url: "ptreport1.php",
data: 'ptdate=' + $(this).val(),
success: function(resultt){
$('#searchr').html(resultt);
$("#searchr").show();
}
});
});
The issue I'm facing is contents in ptreport1.php has links (pagination) contained to browsing scope of that php file. When the user clicks on those links he is directed out of the original page ajax content is loaded from.
Is there anyway to prevent that and load content in original page.
Update # 2.
After ediding the codes with preventDefault, following is my jquery
<script>
$(document).ready(function() {
$("#searchr").hide();
$(function() {
$('#datepicker3' ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd M yy'
});
});
$("#datepicker3").change(function(){
var myValue = $(this).val();
$.ajax({
type: "POST",
url: "ptreport1.php",
data: 'ptdate=' + $(this).val(),
success: function(resultt){
$('#searchr').html(resultt);
console.log('html.resultt');
$("#searchr").show();
$('.pagination-link').click(function(e) {
e.preventDefault();
//Another AJAX call to load the content here.
var page = $("#pagediv").html();
var timestamp =$("#timediv").html();
var dataString = 'page='+ page + '×tamp='+ timestamp;
$.ajax({
type: "GET",
url: "ptreport1.php",
data: dataString,
success: function(resultt){
$('#searchr').html(resultt);
console.log('html.resultt');
$("#searchr").show();
}
});
});
}
});
});
});
</script>
and ptreport1.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
include "core.php";
connectdb();
$page = $_GET['page'];
$timestamp = $_GET['timestamp'];
$ptdate = $_POST['ptdate'];
if(isset($timestamp)){
$ptdate = date('d M Y', $_GET['timestamp']);
}else{
$timestamp = strtotime($ptdate);
}
if(!isset($page)){
$page=1;
}
if($page=="" || $page<=0)$page=1;
$numresults = mysqli_query($connect, "SELECT patient.firstname, patient.lastname, appointment.charge FROM patient INNER JOIN appointment ON patient.id = appointment.patientid WHERE DATE_FORMAT(appointment.date, '%d %b %Y')='".$ptdate."'")or die("error querying");
$numrows = mysqli_num_rows($numresults);
$num_items = $numrows; //changable
$items_per_page= 5;
$num_pages = ceil($num_items/$items_per_page);
if($page>$num_pages)$page= $num_pages;
$limit_start = ($page-1)*$items_per_page;
$npage = $page+1;
$numresults = mysqli_query($connect, "SELECT patient.firstname, patient.lastname, appointment.charge FROM patient INNER JOIN appointment ON patient.id = appointment.patientid WHERE DATE_FORMAT(appointment.date, '%d %b %Y')='".$ptdate."' LIMIT $limit_start, $items_per_page")or die("error querying");
$numrows = mysqli_num_rows($numresults);
if($numrows==0){
echo "Sorry, No results for $ptdate.";
exit();
}
echo "<p><table>";
while($msdrow = mysqli_fetch_assoc($numresults)){
$charge= $msdrow['charge'];
$fname= $msdrow['firstname'];
$lname= $msdrow['lastname'];
// $fullname = $fname." ".$lname;
echo "<tr><td>$fname</td><td>$lname</td><td>$charge</td></tr>";
$totalcharge = $totalcharge+$charge;
}
echo "<b><tr><td colspan=\"2\">Total Charge</td><td>$totalcharge</td></tr></b></table></p>";
echo "<div id='pagediv' >";
echo "$page</div>";
echo "<div id='timediv' >";
echo "$timestamp</div>";
echo "<p align=\"center\">";
if($page>1)
{
$ppage = $page-1;
echo "«PREV ";
}
if($page<$num_pages)
{
$npage = $page+1;
echo "Next»";
}
echo "<br/>$page/$num_pages<br/>";
echo "</p>";
What am i doing wrong here, since it after second click it jumps out of ajax directs to original php page.
Thanx
You would need to set onclick event handlers on the pagination links after loading the content in ptreport1.php. You'll need to change .pagination-link to match the links in the content you are loading.
success: function(resultt){
$('#searchr').html(resultt);
$("#searchr").show();
$('.pagination-link').click(function(e) {
e.preventDefault();
//Another AJAX call to load the content here.
});
}
Related
I have a code for showing list from database and a loadmore button. After all records list is displayed and click on loadmore button show empty places.
How to hide loadmore button once all records displayed?
index.php file:
<?php $chinp=$_GET['schinp'];?>
<div id="schts"></div>
<button id="btnsch">load more</button>
<script>
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 1;
var offsrch = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp}
})
.done(function(msg) {
$("#schts").append(msg);
});
offsrch = offsrch + srchco;
});
$("button").trigger("click");
});
</script>
search.php :
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
Thanks.
Here is code to hide load more button as per your code.
Replace this code in your first file.
<script type="text/javascript">
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 2;
var offsrch = 0;
var page_num = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp, page_num : page_num}
})
.done(function(msg) {
if(msg == 'noMoreData'){
$("#btnsch").hide();
} else {
$("#schts").append(msg);
}
});
page_num = page_num + 1;
offsrch = offsrch + srchco;
});
$("#btnsch").trigger("click");
});
</script>
Now add this code in your search file.
<?php
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$page_num=$_POST['page_num'];
$total_records = 0;
$totalschql="SELECT id FROM t_users WHERE name LIKE 'krishna' ORDER BY name ASC";
if ($result=mysqli_query($conn,$totalschql))
{
$total_records=mysqli_num_rows($result);
}
$last_records_count = ($page_num) * $srchcoun;
if($last_records_count >= $total_records) {
echo 'noMoreData';exit();
} else {
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";;
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];
?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
<?php
}
?>
Try this and let me know if you have any issue.
Simply use $('#myButtonId').hide(); in ajax part after you load the entire data from database.
function get_rain_data_list(is_load_more=0){
if(is_load_more!=0){//if is_load_more is not 0 then get offset data from btnlod attr
offset = $('#btn_load_more_rain').attr("data-offset");
}else{ //set offset =0 when is_load_more is 0
offset = 0;
}
var id = $('#id').val();
var countShow = 0;
if(fromDate!=''){
countShow = 1;
}
$.ajax({
url: base_url+"rain_data_list_ajax",
type: "POST",
data:{offset:offset,propertyId:propertyId,fromDate:fromDate,toData:toData},
dataType: "JSON",
beforeSend: function() {
show_loader();
},
success: function(data){
hide_loader();
// console.log(data);
$('.proprty_load_more_btn').remove();//remove load more button
if(offset==0){ //clear div when offset 0
$("#append_rain_list").html('');
}
if(data.no_record==0){//show data in div when no previous record
$("#append_rain_list").html(data.html_rain);
$("#add_count").html('');
if(countShow){
//$("#add_count").html(data.count+data.record);
}
}else{
//append data when already record show in view
$("#append_rain_list").append(data.html_rain);
$("#append_load_btn").append(data.btn_html);
$("#add_count").html('');
if(countShow){
$("#add_count").html(data.count+data.record);
}
}
},
});
}
<div id="append_rain_list"></div>
<div id="add_count"></div>
<?php
function rain_data_list_ajax(){
$limit = 6;
$is_next = 0;
//get and set offset
$offset = $this->input->post('offset');
$data['property_id'] = decoding($this->input->post('propertyId'));
$fDate = sanitize_input_text($this->input->post('fromDate'));
$tDate = sanitize_input_text($this->input->post('toData'));
$new_offset = $limit+$offset; //pr($data);
//set where
$where = array('property_id'=>$data['property_id']);
//set select field to get
$data['limit'] = $limit;
$data['offset'] = $offset;
//get count of records
$dataView['total_count'] = $this->Property_model->get_rain_count($data);
//get records
$dataView['rain_list'] = $this->Property_model->get_rain_list($data);
///lq();
//check for load more btn
//pr($dataView);
if($dataView['total_count']>$new_offset){
$is_next =1;
}
$btn_html = '';
if($is_next){
//if is next =1 set load more button in btn_html
$id = "btn_load_more_rain";
$btn_html = '<div class="col-sm-12 text-center pt-20 proprty_load_more_btn"><button class="login-btn load load_more_btn" id = "'.$id.'" data-offset ="'.$new_offset.'" data-isNext ="'.$is_next.'" >'.lang('load_more').'</button></div>';
}
//load view with data
$html_rain = $this->load->view('test1',$dataView,true);
$response = array('status'=>1,'html_rain'=>$html_rain,'btn_html'=>$btn_html,'count'=>$dataView['total_count'],'record'=>lang('recod_found'));
//flag for no record
$no_record=1;
if(empty($dataView['rain_list'])){
$no_record = 0;
}
$response['no_record'] = $no_record;
echo json_encode($response);die;
}
?>
I'm trying to load applicants info that i get from database (fisrt name, lasta name, ID number) in a slidetoggle that appears after clicking "Display applicants" button.
My code keeps showing ERROR DETECTED message, after I click the button "display applicants" an slidetoggle should appear and the json data be shown on the slide. can someone give me some directions about what i'm doing wrong here.
Query:
if(isset($_GET['id'])){
$id_oferta = $_GET['id'];
$sql ="SELECT postulacion.* FROM postulacion WHERE id_oferta = '". $id_oferta ."'";
$listapostulantes = mysql_query($sql) or die(mysql_error());
$return_arr= array();
$num = mysql_num_rows($listapostulantes);
if($num > 0){
while($row = mysql_fetch_array($listapostulantes, MYSQL_ASSOC)){
$return_arr[] = $row;
}
echo json_encode($return_arr);
}
}
Script:
$(document).ready(function(){
$('.myslide').hide();
$(".postulantes").on('click', function(e){
e.preventDefault();
if($(this).parent().next().css('display') == 'none'){
$('.myslide').hide('fast');
$(this).parent().next().slideToggle('slow');
var link = $(this).attr('href').split('&');
var idd= link[1].match(/id=([0-9]+)/)[1];
$.ajax({
url: link[0],
type: 'GET',
dataType:'json',
data:{'id': idd},
success:function(data){
// console.log();
var htmlStr = '';
$.each(data, function(key, value){
htmlStr += '<p>' + value.rut_usuario + '</p>';
});
$(".myslide").html(htmlStr);
},
error: function(){
$("#listaofertas").html("ERROR DETECTED");
//console.log();
}
});
}
});
});
json
Your response, as shown under the Respuesta tab, includes not only JSON, but some HTML as well. Get rid of the html, and make sure only JSON is returned, and then jquery should execute your success callback
Use this to split the response and "cut out" the html part.
$splitted = explode("<!DOCTYPE HTML>",json_encode($return_arr));
echo $splitted[0];
I currently have two php files (index.php and update.php) In index.php, there is some javascript code and a button that sends a variable, called $sid, to update.php, where it is processed based on $sid. Here is the code for both index.php and update.php. I am not pasting it directly into StackOverflow, simply because of how you have to add code to your text on StackOverflow, and how JavaScript works with it's spacing hierarchy.
http://pastebin.com/fq87vvgz
Currently, when you press the button, an alert box does not pop up. If you put the PHP code in a PHP code checker, no errors appear.
Here is my code:
This is what is in index.php
<?php
$sid = 11;
?>
<script type="text/javascript">
$(document).ready(function(){
$('#vote').click(function(){
$.ajax({
url : 'update.php', // Notice how this sends to update.php
type : 'POST',
data : {
action : 'vote_server',
sid : $('#sid').data('sid')
},
dataType : 'JSON',
success : function(result) {
if (result.xhr == 'success') {
alert('You bumped your server!');
} else if (result.xhr == 'voted_already')
alert('You can only bump every 24 hours!')
}
});
});
})
</script>
<input type="button" class="btn btn-primary" id="vote" value="Vote up your server">
This is what is contained in update.php
<?php
define('action',$_POST['action']);
$result = array(
'xhr' => 'error'
);
if (action == 'vote_server')
{
$sid = (int)$_POST['sid'];
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$dbTime = #mysql_result(mysql_query("SELECT `id`, `last_updated` FROM `servers` WHERE `id` = '$sid'"), 0);
$timeDiff = $time - $dbTime;
if($timeDiff >= 86400){
mysql_query("UPDATE `servers` SET `last_updated` = '$time' WHERE `id` = '$sid'");
$result['xhr'] = 'success';
} else { $result['xhr'] = 'voted_already'; }
}
echo json_encode($result);
?>
Use query and ajax
in your index page...
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$( ".button" ).click(function() {
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
$.ajax({
type: "POST",
url: 'update.php',
data: {postedVar:var1, postedVar2:var2},
success: function(data)
{
alert(data);
}
});
});
});
</script>
<html>
<button class="button" data-var1="<?php echo "this is var1"; ?>" data-var2="<?php echo "this is var2"; ?>">Button</button>
</html>
On you update page...
access your vars like this
<?php
var1 = $_POST['postedVar1'];
var2 = $_POST['postedVar2'];
echo var1;
?>
...NOT TESTED
How would I go about updating a div with a id every x seconds? I want it to update the users statuses which are contained inside this, that includes the time the amount of comments made on that individual post.
I've tried setInterval but it takes 10 seconds for the status to be added and then duplicates the status every x amounts of seconds after that. All I need is for the response data to be updated not the insertion of the comment to be re-added every 10 seconds.
HTML:
<div id='divider-"+response['streamitem_id']+'></div>
JavaScript:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var content = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
cache: false,
dataType: "json",
data: { toid: content, newmsg: newmsg },
success: function(response){
$("#homestatusid").html("<div id='divider-"+response['streamitem_id']+"'><div class='userinfo'>X</div><a href='/profile.php?username="+response['username']+"'>"+response['first']+" "+ response['middle']+" "+response['last']+"<span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+response['streamitem_timestamp']+"</a><hr>"+newmsg+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+response['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+response['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a id='likecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+response['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'>Like</div></a><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'></div></div><div id='streamdislike'><a id='dislikecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+response['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'>Dislike</div></a><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'></div></div></div><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+response['streamitem_id']+"'><div id='comment_list_"+response['streamitem_id']+"'><table width=100%><tr><td valign=top width=30px><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><td valign=top align=left><div class='stream_comment_inputarea'><input id='addcomment' type='text' name='content' style='width:100%;' class='input_comment' placeholder='Write a comment...' onkeyup='growcommentinput(this);' autocomplete='off' onkeypress=\"if(event.keyCode==13){addcomment("+response['streamitem_id']+",this.value,'comment_list_"+response['streamitem_id']+"',"+response['id']+",'"+response['first']+" "+ response['middle']+" "+response['last']+"');this.value='';}\"><br/></div></div>");
}
});
return false
});
});
INSERT.PHP
$json = array();
$check = "SELECT streamitem_id FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_id DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_id'] = $resultArr['streamitem_id'];
mysql_free_result($check1);
$check = "SELECT streamitem_timestamp FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_timestamp DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
mysql_free_result($check1);
$check = "SELECT username, id, first, middle, last FROM users";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
mysql_free_result($check1);
echo json_encode($json);
First wrap up the Ajax call in a single-execution function, with the callback function referring to the same:
$(function() {
(function ajaxcall() {
$.ajax({
url: 'foo.php',
data: {boo:'moo',goo:'loo'},
timeout: function() { ajaxcall(); },
success: function(data) {
//do somethng with the data
//done, now call the function again:
ajaxcall();
}
});
}());
});
Then in the PHP write something like:
$timeout = 30;
$pollinterval = .5;
$counter = 30;
while ($counter >= 0) {
//function which fetches fresh data and sets $test to true if data is returned
list($test,$dataarray) = fetchdata();
if ($test) { //JSON_encode the data array and send it
echo JSON_ENCODE($dataarray);
}
else { //no fresh data, query the db again after wating for some time)
usleep($pollinterval*1000);
$counter -= $pollinterval;
}
//timeout, return whetever you have!
echo JSON_ENCODE($dataarray);
You can use setInterval (see Documentation) or setTimeout (see Documentation).
Sounds like polling. You can include an AJAX call, that will send a request to a backend PHP script that will search the database for further update. if found, it will immediately return the new result. The client side JS on receiving the new data, will wait for say 30 seconds before making another request. If the PHP doesn't find any new data, then it will query the DB again, say after 5 seconds, and continue to do so until a script-defined timeout, say 25 seconds, occur. Then it will return an empty result, on receiving which the client side JS will immediately make another request.
I think this is what you're wanting, using Jquery:
HTML:
<div id="divider-whatever"></div>
Jquery:
$(document).ready(function() {
setInterval(function() {
div = $("#divider-whatever");
$.get(data.php, function(responseData) {
div.html(responseData);
}, 1000);
// change 1000 to whatever time you need
// change data.php to the file where your data is coming from
});
});
*not tested
Hope this helps!
I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});