Ajax and PHP debug - javascript

Building a script that once a date is selected in a datepicker calendar, it uses ajax to post the selected date in a php script;
in the success of that ajax call, it uses another ajax call to post the same selected date to another php script and displays that in the page.
Did some research around and this seemed to be the best solution for what I try to do.
The script is the following:
<script> //for the events
jQuery(function($) {
$(".date").datepicker({
onSelect: function(dateText) {
display("Selected date: " + dateText + "; input's current value: " + this.value);
$(this).change();
}
}).on("change", function() {
display("Got change event from field");
// call next ajax function
var mydate = this.value;
$.ajax({
type: "POST",
url: 'boxes_script.php',
data: ({dates: mydate}),
dataType : 'html',
success: function(data) {
$('.caixas').html(data);
alert(data);
$.ajax({
type: "POST",
url: 'events_script.php',
data: ({dates1: mydate}),
dataType : 'html',
success: function(data) {
$('.results-ajax').html(data);
alert(data);
}
});
}
});
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
</script>
This is the code being used atm. Got some updates because of the feedback given here, but the solution still hasn't worked 100%
There's a problem on it and I think it's because the second Ajax call is inside of a success Ajax.
The problem is the following:
The data is being posted in the php scripts, which run like how they should.
The array gets populated with the right information.
The
$('.caixas').html(data);
works fine and displays data from 'boxes_script.php' there.
The
$('.results-ajax').html(data);
receives 100% of the data being sent from 'events_script.php' but for any weird reason, doesn't append it to the page..
I can see the data in alert messages and it's the right data being sent to the browser.
Why isn't that data being appended to the page?
This is the php code for 'events_script.php':
<?php
include 'config/config.php';
include 'libraries/database.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
print_r($_POST);
echo $_POST[dates1];
$dias= $_POST[dates1];
$mysql_date = date('Y-m-d', strtotime($dias));
echo $mysql_date;
//Make database query
$sql = "***";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$image = $row['Company_Logo'];
$myArray = json_decode($image, true);
$event=$row['eventID'];
echo '<div class="tab-pane" role="tabpanel">
<div id="'.$dias.'" class="container day-events">
<div class="row event-list">
<div class="event-list-time col-md-3 col-sm-3 center" style="background-image:url('.$myImage = $myArray[0]['name'].');">
<p class="event-list-start-time">'.$row['Start_Date'].'</p>
<hr class="event-list-time-divider">
<p class="event-list-end-time">'.$row['End_Date'].'</p>
</div>
<div class="event-list-info col-md-9 col-sm-9">
<h2 class="event-list-name">'.$row['Event_Name'].'</h2>
<p>Organized by <span class="event-list-organizer">'.$row['Company_Name'].'</span></p>
<p class="event-list-description">'.$row['Event_Description'].'</p>
<button type="button" class="btn more-info-list">More Information</button>
</div>
</div>
</div>
</div>';
}} else { echo 'No results found.'; }
}
?>
Note: no errors were found in the error log. The network gives status 200.
The data can be seen sent to the browser here:
The first part of the data is being appended to the browser, as you can see in the images.
Why is not working everything?

This was what fixed the problem and made the following final result:
Old:
<div class="row events-tabs">
<div class="container" data-example-id="togglable-tabs">
<ul class="nav nav-pills center caixas" id="myTabs" role="tablist">
</ul>
<div class="results-ajax tab-content" id="myTabContent">
</div>
</div>
</div>
New:
<div class="row events-tabs">
<div class="container" data-example-id="togglable-tabs">
<ul class="nav nav-pills center caixas" id="myTabs" role="tablist">
</ul>
<div class="tab-content" id="myTabContent">
<div class="results-ajax"></div>
</div>
</div>
</div>
So, basically using results-ajax as class of an own div fixed the problem.

Change
data1: ({dates1: this.value})
to
data: ({dates1: this.value})

var mydate = this.value; // add before the 1st ajax call
change -
data1: ({dates1: mydate})

Related

Make Load more Button disappear after fetching all data

My code works fine, it displays more users when the load more button is clicked.
my constraint right now is how to remove the Load more button if there is no more value on the response.
This is how my model looks like
public function getFreeAds($page){
$offset = 10*$page;
$limit = 10;
$this->db->select('*');
$this->db->from('escort');
$this->db->where('status', 'Approved');
$this->db->limit($offset ,$limit);
$this->db->order_by("time_stamp, UPPER(time_stamp)", "DESC");
$query = $this->db->get();
return $query->result();
}
My Controller looks like this
public function getCountry(){
$page = $_GET['page'];
$countries = $this->Home_model->getCountry($page);
foreach($countries as $country){
echo
'<div class="col-md-4 col-sm-6">
<div class="portfolio-item">
<div class="thumb">
<a ><div class="hover-effect" data-e_id="'.$country->e_id.'" id="profile2">
<div class="hover-content">
<h1> '.$country->ProfileName.'</em></h1>
<p> '.$country->Height.' CM tall '.$country->BreastCup.' Breast Size <b>Nationality: '.$country->Nationality.' </b></p>
<button type="button" class="btn-info">View More</button>
<button type="button" class="'.$country->confirmstatus.'">'.$country->confirmstatus.'</button>
<div class="top">
</div>
</div>
</div></a>
<div class="image" width="70%" height="1000px">
<img src="uploads/'.$country->ProfilePicture.'">
</div>
</div>
</div>
</div>';
}
exit;
}
Here is my query code that displays the response.
$(document).ready(function(){
getcountry(0);
$("#load_more").click(function(e){
e.preventDefault();
var page = $(this).data('val');
getcountry(page);
});
});
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>Home/getCountry",
type:'GET',
data: {page:page}
}).done(function(response){
$("#show_data").append(response);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
scroll();
});
};
var scroll = function(){
$('html, body').animate({
scrollTop: $('#load_more').offset().top
}, 1000);
};
What you can do is get the next values in the same function and if there are values available you can make an input field(hidden) and then show or hide the button according to its value.
I'm writing a possible solution for your case, comments are mentioned wherever necessary. Remember there are better ways of doing this like using count but this is according to your code. See if it helps you.
Controller
public function getCountry(){
$page = $_GET['page'];
$countries = $this->Home_model->getCountry($page);
$nextValue = $this->Home_model->getCountry($page+1); // get the values for the next page
$showButton = !empty($nextValue) ? 'yes' : 'no'; // show the button if next value exists
foreach($countries as $country){
echo
'<div class="col-md-4 col-sm-6">
<div class="portfolio-item">
<div class="thumb">
<a ><div class="hover-effect" data-e_id="'.$country->e_id.'" id="profile2">
<div class="hover-content">
<h1> '.$country->ProfileName.'</em></h1>
<p> '.$country->Height.' CM tall '.$country->BreastCup.' Breast Size <b>Nationality: '.$country->Nationality.' </b></p>
<input type="hidden" class="showButton" value="'.$showButton.'" />
<!-- make a hidden input field and assign a value (yes/no) -->
<button type="button" class="btn-info">View More</button>
<button type="button" class="'.$country->confirmstatus.'">'.$country->confirmstatus.'</button>
<div class="top">
</div>
</div>
</div></a>
<div class="image" width="70%" height="1000px">
<img src="uploads/'.$country->ProfilePicture.'">
</div>
</div>
</div>
</div>';
}
exit;
}
View
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>Home/getCountry",
type:'GET',
data: {page:page}
}).done(function(response){
$("#show_data").append(response);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
// check the value of input field
if($('.showButton:last').val() == "no"){
$('#load_more').hide(); // hide the button
}
scroll();
});
};
Add to your response metadata with total pages count. During every request make count query to your DB with same clauses. In your JS code after every request compare current page with total pages from response and hide button if last page reached.

Can't return html from controller using Ajax calls in a Chat app

So i'm building an integrated chat app in CRM. Whenever the logged in user click on a contact it displays the chat history between both users using Ajax calls, and this is where troubles begin.
So here's my Ajax Call code:
function GetChatHistory(receiver_id){
$.ajax({
dataType : "json",
url: '/chat/get_chat_history_by_user',
data:{receiver_id:receiver_id},
success:function(data)
{
$('#chathistory').html(data);
ScrollDown();
},
error: function (jqXHR, status, err) {
// alert('Local error callback');
alert("error fetching")
}
});
}
this is my controller
public function get_chat_history_by_user(){
//get the receiver id
$receiver_id = $this->input->get('receiver_id');
//get the sender id
$Logged_sender_id = $this->session->userdata['user_id'];
$history = $this->chat_model->GetReciverChatHistory($receiver_id);
foreach($history as $chat):
$message_id = $chat['id'];
$sender_id = $chat['sender_id'];
$userName = $this->UserModel->GetName($chat['sender_id']);
$userPic = $this->UserModel->PictureUrlById($chat['sender_id']);
$messagebody = $chat['message'];
$messagedatetime = date('d M H:i A',strtotime($chat['message_date_time']));
?>
<?php if($Logged_sender_id!=$sender_id){?>
<!-- Message. Default to the left -->
<div class="direct-chat-msg">
<div class="direct-chat-info clearfix">
<span ><?=$userName;?></span>
<span ><?=$messagedatetime;?></span>
</div>
<!-- /.direct-chat-info -->
<div class="direct-chat-text">
<?=$messageBody;?>
</div>
<!-- /.direct-chat-text -->
</div>
<!-- /.direct-chat-msg -->
<?php }else{?>
<!-- Message to the right -->
<div class="direct-chat-msg right">
<div class="direct-chat-info clearfix">
<span ><?=$userName;?></span>
<span ><?=$messagedatetime;?></span>
</div>
<!-- /.direct-chat-info -->
<div class="direct-chat-text">
<?=$messageBody;?>
</div>
<!-- /.direct-chat-text -->
</div>
<!-- /.direct-chat-msg -->
<?php }?>
<?php
endforeach;
}
the simple version of the view and the div i want to insert data in it :
<div id="chathistory"></div>
Please note that the models are written correctly(i did test them), and the call is written correctly because whenever i remove the foreach loop and add this to my controller :
echo json_encode($history);
and then console log the data in my ajax call i get the full chat history without a problem. so my guess is that there's something wrong with foreach loop and the html rendering !
ALSO : i did review some simple web app chat on github and they did write the controller with the same manner and it work perfectly fine for them. So what do you think is the problem please?
dataType : "json"
tells jQuery to expect JSON in the response, but you are returning HTML from the controller. So it will likely throw an error when it tries to parse your HTML as JSON. Either remove that line, or specify
dataType: "html"
instead

Ajax Tabs for Wordpress that loads and runs different shortcodes when user changes the tab

How does one execute a shortcode, which is placed in a tab, only when the user clicks on the Tab's Title. How do we do this for five tabs? MY objective is to reduce load time of me website. So, only that content which the user wants must load when he clicks on the tab.
I'm fairly certain the best way to do this is by utilizing Wordpress's admin-ajax.php. I've searched a great deal. And I've found most of the code (I think) to create the AJAX tabs. But, when I fire the code it doesn't show up. Rather the HTML shows us, the AJAX doesn't.
$(document).ready(function() {
$('.my_tabs a').click(function(e) {
e.preventDefault();
var tab_id = $('this').attr('id');
$.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({
action: 'my_tab_menu',
id: tab_id
}),
success: function(data) {
$('#my_tab' + tab_id).html(data);
},
error: function(data) {
alert("Error!");
return false;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my_tabs">
Tab 1
Tab 2
Tab 3
Tab 4
Tab 5
</div>
<div class="my_section" id="my_tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my_section" id="my_tab2">
<?php echo do_shortcode ('[shortcode-2]'); ?>
</div>
<div class="my_section" id="my_tab3">
<?php echo do_shortcode ('[shortcode-3]'); ?>
</div>
<div class="my_section" id="my_tab4">
<?php echo do_shortcode ('[shortcode-4]'); ?>
</div>
<div class="my_section" id="my_tab5">
<?php echo do_shortcode ('[shortcode-5]'); ?>
</div>
I add all the code directly into the page using a page-builder. So, I'm not using functions.php to add_action for this particular tab that I'm trying to implement.
I found all the code from a similar post on stackover:
Ajax tabs (wordpress)
They call template_parts into the tabs. Where as I want to execute a shortcode.
I'm what you'd call a coding bimbo. All help shall be much appreciated.
Thank you. And if you've managed to read till here, you deserve to have a pleasant day. :D
Okay, so you can't achieve it the way you have laid your template. As soon as you echo the shortcode and the browser renders the page, the shortcode contents must have printed. You need to create a custom-page-template.php, create a page and on that page you need to send the shortcode handler as soon as you click on the tab through GET or POST method using ajax.
In your Custom Template you receive the [shortcode-1]. An example code would be like you see below:
<?php
/*
Template Name: Shortcode Processor
*/
$current_shortcode = $_POST['shortcode_name'];
?>
<div id="shortcode-contents">
<?php echo do_shortcode($current_shortcode); ?>
</div>
Now you have the response in your Ajax Call. You can now inject the success html inside your desired tab.
Try
<button class="tabs" id="my-tabid1" data-target=".my-section1.box">Tab 1</button>
<button class="tabs" id="my-tabid2" data-target=".my-section2.box">Tab 2</button>
<button class="tabs" id="my-tabid3" data-target=".my-section3.box">Tab 3</button>
<div class="my_section1 box active" id="my-tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section2 box" id="my-tab2">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section3 box" id="my_tab3">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<style>
.box {
display: none;
}
.box.active {
display: block;
}
</style>
<script>
$('.tabs').on('click', function(){
var $target = $($(this).data('target'));
$target.siblings().removeClass('active');
$target.addClass('active');
});
</script>

How to change displayed html content in view using jquery - codeigniter

I'm not so sure about how to type this question title, but anyway
I have code like this in my view called content.php
<div class="fix single_content floatleft">
<h2><img src="<?php echo base_url('assets/images/New.png')?>" alt="" width="24" height="24"></img><a href="<?php echo base_url('index.php/Main_Controller/loadKeluhan')?>" >New</a> </h2>
<?php include 'tableLoad.php' ?>
<p class="viewall">view more <i class="fa fa-hand-o-right"></i></p>
</div>
And in its looks like this in tableLoad.php
<div class="fix"><ul id="newTable"><?php
$i=0;
while($i<count($array)){
echo '<li>
<div class="entry_name floatleft"><img src="assets/images/mozilla.png" alt="">'.$array[$i].'</div>
<div class="download-count floatright"><i class="fa fa-download"></i> 4578</div>
</li>';
$i++;
}
?></ul></div>
$array[i] is a forwarded variable from my controller which have list of item I need from my database.
I want to have it refreshed every 2 second so it will change the display if something changed from the database. I use my code in jQuery like this to do it:
$(document).ready(function(){setInterval(function(){
$('#newTable').html("<?php include 'tableLoad.php'; ?>")
}, 2000);});
The problem is that every time jQuery code run, it show nothing and there is no error report in browser's console. The codes in php run well, but the one from jQuery did not.
Can anybody please give me some enlightment?
Thanks in advance and sorry for my bad English
SOLVED
Solution :
I change my js code to Ajax and call function from controller with it like poonam said. The js file become like this :
$(document).ready(function(){
setInterval('autoRefresh_div()', 2000);
});
function autoRefresh_div()
{
$.ajax({
dataType:'text',
type: "POST",
url: BASE_URL+'index.php/Main_Controller/loadKeluhan',
success: function (response){
$("#newTable").html(response);
}
});}
with loadKeluhan is a function in my Main_Controller to load tableLoad view and pass new array value to it.
You should use load()
Try this:
function autoRefresh_div()
{
$("#newTable").load("tableLoad.php");// a function which will load data from other file after x seconds
}
setInterval('autoRefresh_div()', 2000); // refresh div after 2 secs
And use this:
<div class="fix single_content floatleft">
<h2><img src="<?php echo base_url('assets/images/New.png')?>" alt="" width="24" height="24"></img><a href="<?php echo base_url('index.php/Main_Controller/loadKeluhan')?>" >New</a> </h2>
<div class="fix"><ul id="newTable">
<?php include 'tableLoad.php' ?>
</ul>
</div>
<p class="viewall">view more <i class="fa fa-hand-o-right"></i></p>
</div>
Get only <li> from tableLoad.php.
Similarly you can use $.ajax() or $.post() etc instead of load() function and put the response in div or ul.
With $.ajax()
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function autoRefresh_div()
{
$.ajax({
dataType:'text',
type: "POST",
url: 'url_to_your_file or function',
success: function (response){
$("#newTable").html(response);
}
});
}
setInterval('autoRefresh_div()', 2000); // refresh div after 2 secs
</script>

PHP/AJAX: Ajax request to php not working, not putting rows into div

I am making a php chat but am having some trouble using ajax to check a mysql database and to put the data into a div. Here are my codes:
HTML
<div id="chatbox">
<div class="chatheader"><div class="chatheadertext">chatheader</div></div>
<div id="chatcontainer">
<div class="chatpadding">
<div id="chatmessages">
<div class="chat-replies">
<div class="chat-reply-container">
<div class="chat-reply-avatar">
<img src="img/default_avatar.png">
</div>
<div class="chat-reply-chat">
<span class="chat-reply-author">testuser</span><br>
<span class="chat-reply-content">test message goes here</span>
</div>
</div>
</div>
</div>
</div>
<form id="form" action="">
<textarea class="chatchat" id="message" placeholder="Type message here!"></textarea>
</form>
</div>
</div>
JAVASCRIPT
<script>
$(".chatheader").on("click", function () {
$("#chatcontainer").slideToggle();
});
$("textarea").keyup(function(e){
if((e.keyCode ? e.keyCode : e.which) == 13) {
//The enter button has been pressed
}
});
$(function ()
{
$.ajax({
url: 'ajax.php',
data: "",
dataType: 'json',
success: function(data)
{
$('#chatmessages').html("<div class='chat-replies'>
<div class='chat-reply-container'>
<div class='chat-reply-avatar'>
<img src='img/default_avatar.png'>
</div>
<div class='chat-reply-chat'>
<span class='chat-reply-author'>testuser</span><br>
<span class='chat-reply-content'>test message goes here</span>
</div>
</div>
</div>");
}
});
});
</script>
PHP
<?php
$con = mysqli_connect('localhost','root','','chat');
$query = mysqli_query($con,"SELECT * FROM `messages`");
$msgnum = mysqli_num_rows($query);
$array = mysqli_fetch_row($query);
echo json_encode($array);
?>
So basically what I am trying to do is use ajax to contact the php file which will then check the mysql database for tables and encode them to json, on the index page, the chatbox is supposed to come up by the first javascript function but it's not sliding up. know that it is the ajax that is doing this, specifically the $('#chatmessages').html(); line. When I remove the code from that line, the chatbox comes up but is empty inside. What am I doing wrong, how would I do it so that when it contacts, for each row that is found in the database, it echoes
<div class='chat-replies'>
<div class='chat-reply-container'>
<div class='chat-reply-avatar'>
<img src='img/default_avatar.png'>
</div>
<div class='chat-reply-chat'>
<span class='chat-reply-author'>testuser</span><br>
<span class='chat-reply-content'>test message goes here</span>
</div>
</div>
</div>
So if there are like 50 rows in the database, it would echo that script for each of the rows, and there would be an overflow-y:scroll on the <div id="chatmessages"> so it doesn't overflow. Thanks in advance to anyone that can help!
If you've json data in success callback of your AJAX call, you can iterate through all records and append each record to your chat div
success: function(data)
{
$.each(data,function(index,dataRecord){
document.getElementById('chatmessages').innerHTML +="html content goes here";
});
//scroll down your div,make sure you should have propery, overflow-y:scroll
document.getElementById('chatmessages').scrollTop=100000;
}
Hope this will help,
Thanks

Categories

Resources