updating div without page refresh - php

i have a php script that counts button clicks to a txt file. this is working just fine.
On my html page i am displaying the clicks as such :
<?php
include ('counter.php');
?>
<div class="count_right" id="one"></div>
<div class="count_left" id="two"></div>
<form action="" method="post" id="form" >
<button class="vote_right" name="clicks1" ></button>
</form>
<form action="" method="post" id="form2" >
<button class="vote_left" name="clicks2"></button>
</form>
the php
<?php
if( isset($_POST['clicks1']) ) {
incrementClickCount1();
}
function getClickCount1()
{
return (int)file_get_contents("count_files/clickcount1.txt");
}
function incrementClickCount1()
{
$count = getClickCount1() + 1;
file_put_contents("count_files/clickcount1.txt", $count);
}
if( isset($_POST['clicks2']) ) {
incrementClickCount2();
}
function getClickCount2()
{
return (int)file_get_contents("count_files/clickcount2.txt");
}
function incrementClickCount2()
{
$count2 = getClickCount2() + 1;
file_put_contents("count_files/clickcount2.txt", $count2);
}
?>
and the js (EDITED)
<script type="text/javascript">
var valueOne = "<?php echo getClickCount1(); ?>";
var valueTwo = "<?php echo getClickCount2(); ?>";
$('#one').html(valueOne);
$('#two').html(valueTwo);
$('.vote_right').click(function(){
$.ajax({
type: "POST",
url: "counter.php",
data: valueOne,
cache: false,
success: function(data)
{
$("#one").html(data);
} });
</script>
tried also adding
e.preventDefault();
but then the button wont work.
My problam is that i dont want the page to refresh when the button is clicked. insted i would like the div to refresh with the new data.
I have tried usin ajax but with no success. its either the page refreshes or the data wont update.
Any suggestions?

Use type=button to not submit the form when clicking buttons (and thus prevent page reloading).
<button type="button" class="vote_right" name="clicks1" ></button>

The below shows how to write two of the 4 api calls you need to add to your website.
Main Page:
<?php
include ('counter.php');
?>
<div class="count_right" id="one"></div>
<div class="count_left" id="two"></div>
<button class="vote_right" name="clicks1" onclick="addCount1()"></button>
<button class="vote_left" name="clicks2" onclick="addCount2()"></button>
JS:
<script type="text/javascript">
var valueOne = //use ajax (GET) to call the page for count1;
var valueTwo = //use ajax (GET) to call the page for count2;
$(document).ready(function(){
$('#one').html(valueOne);
$('#two').html(valueTwo);
});
function addCount1(){
//use ajax (POST/PUT) to call a page that adds 1 to your text file thing for count1
}
function addCount2(){
//use ajax (POST/PUT) to call a page that adds 1 to your text file thing for count2
}
</script>
New API Page (for count1):
<?php
class IntegerValue implements JsonSerializable {
public function __construct($number) {
$this->number = (integer) $number;
}
public function jsonSerialize() {
return $this->number;
}
}
echo json_encode(new IntegerValue(getClickCount1()), JSON_PRETTY_PRINT);
?>
New API page (for count2):
<?php
class IntegerValue implements JsonSerializable {
public function __construct($number) {
$this->number = (integer) $number;
}
public function jsonSerialize() {
return $this->number;
}
}
echo json_encode(new IntegerValue(getClickCount2()), JSON_PRETTY_PRINT);
?>
How PHP and JavaScript work
On initial page load:
The process flow looks like this:
Server Side code (php) -> sends data to client -> browser begins rendering and executing JS
On form Submit:
Client Executes code (javascript) -> Sends data to server -> Server gets data and processes (PHP)
Because of this if you don't want the page to "refresh" you'd have to use JavaScript and the best way of handling this is AJAX if you use a form you are going to get a refresh also known as a POST-BACK. Otherwise with AJAX you can easily just send a POST or a GET and it won't refresh.

No need to put with in form tag for ajax async request.
Use only
<?php
include ('counter.php');
?>
<div class="count_right" id="one"></div>
<div class="count_left" id="two"></div>
<button class="vote_right" name="clicks1" ></button>
<button class="vote_left" name="clicks2"></button>

Related

How to fetch data from database based on user input and display as JSON array using asynchronous POST in php

I have 1 php page which establishes connection to the database and fetches data from the database using JSON array (this code is working fine).
index2.php
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$uid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I created one more HTML page where i am taking one input (userid) from the user. Based on userid, i am fetching more data about that user from the database. Once the user enters userid and clicks on "Get_Logs" button, more data will be fetched from the the database.
<!DOCTYPE html>
<html>
<head>
<title>User_Logs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$uid =$_POST["USERID"];
}
?>
<form method="POST" id="form-add" action="index2.php">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
</body>
</html>
My script:
$(document).ready(function(){
$("#mybtn").click(function(){
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
})
This code is working fine. However it is synchronous POST & it is refreshing my page, However i want to use asynchronous POST. How can i do that? I have never done this asynchronous POST coding. Kindly help.
i tried this & it not throwing error but there is no output. Can someone please check what is wrong in my code.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.post("index2.php", {data :'<?php echo json_encode($json_array);?>'
})
});
})
I assume that index2.php is another php page (not the same) and it is returning the data that you want to update on the page where you run this code on.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.POST("index2.php", {
var myVar = "<?php echo json_encode($json_array); ?>";
});
});
})
you need to add preventDefault in your click handler to prevent the form from being submitted. This will stop the form to be submitted and the page to be reloaded. Inside the POST you can setup the logic to refresh the page with the updated data (without reloading)
Can you try this,
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
});
Also in HTML remove action in form
<form method="POST" id="form-add">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
Edit :
Can you try this please ? Second param for post takes an object .
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
var myVar = <?php echo json_encode($json_array); ?>;
console.log(myVar);
$.post("submit.php", {
'id': myVar
},function(data){
console.log(data);
});
});
});

how to execute php function on html button click

Hello I want to execute bb() function on button click.
I tried following code but it did not work.
echo "<div class ='i2' id=".$x.">";
echo "<button type='button' style='display: none;' id='i' name='delete' onclick='document.body.removeChild(this.parentNode)'>";
echo"</button>";
echo "</div>";
<?php
function bb()
{
echo "hello";
}
if (isset($_GET['delete'])) {
bb();
}
?>
Your button is HTML and your function is PHP. They look like together because they are in the same file, but they are not together. PHP exists only on the server. HTML only works on the client (browser). When you see the button on your browser, the PHP is gone, you only have HTML.
To make a HTML button to call a PHP function, you will have to move your function to a PHP file, then make your button to call it with Ajax. Example:
bb1.html : contains button that uses Ajax to call PHP function.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'bb2.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
<button onclick="myAjax()">Click here</button> <!-- BUTTON CALL PHP FUNCTION -->
</body>
</html>
bb2.php : contains function that returns "hello".
<?php
function bb()
{
echo "hello"; // VALUE RETURNED.
}
bb();
?>
Create two text files with the given names, copy-paste this codes, open your browser and run "localhost/bb1.html".
This is how a button calls a PHP function : Ajax does all the magic.

Pagination with $_GET - in AJAX - is it posible

I'm developing a PHP class for pagination using $_GET. It is standart, found from the web.
Here it works good :
page.php :
<form method ="GET">
<?php
$pages = new Pagination();
echo "<br/>";
?>
</form>
I want to use this page.php in index.php with ajax / jquery and staying in the index.php
<!DOCTYPE html>
<body>
<div id ="result"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.post('./page.php',
function (data) {
$('#result').html(data);
}
);
});
</script>
</body>
</html>
Is this possible way ?
Is it possible that instead of using jquery's $.post, that you can replace $.post with $.get?
So instead of $.post as you said its looking for $_GET['page']
So you could do something like this:
<script>
$(document).ready(function(e) {
var page_num = 1;
$('.nextpage').on('click',function(e){
e.preventDefault(); // stop the link from going anywhere
$.get('./page.php',
{
page: page_num // this is the same as $_GET['page']
},
function (data) {
$('#result').html(data);
page_num++;
}
);
});
$('.nextpage').click(); // emulate the click to get the first page
});
</script>
and in your body something like this:
Next page
It's worth noting that on your page.php you don't need to have that form as i cannot see it's going to be doing much
UPDATE
So to have the pagination manipulated on the index.php from page.php you could have page.php return a hidden div called .hidden_pagination along with its full content.
<script>
$(document).ready(function(e) {
$('.pagination').on('click','a',function(e){
e.preventDefault(); // stop the link from going anywhere
var next_page = $(this).attr('data-id'); // get the next page from the link data-id attribute
$.get('./page.php',
{
page: next_page // this is the same as $_GET['page']
},
function (data) {
$('#result').html(data);
$('.pagination').html($('#result').children('.hidden_pagination').html()); // add the new pagination to the current pagination
}
);
});
$('.nextpage').click(); // emulate the click to get the first page
});
</script>
<div class="pagination">
Next page
</div>
<div id="result">
this will be replaced with the ajax response
</div>

Change value of PHP variable with AJAX

The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it

How do I call MVC Controller from with Javascript function

I have a onclick event on a submit button in my CI app. So when user clicks submit, it goes to my js function that disables the button, but it does not continue processing. I used this “document.forms[“mainFrm”].submit();”, but because of the way the code is written I need it to go directly to a controller and finish processing.
So how do I call a CI controller from my js function?
Here is the function that is being called onClick:
function disableWhenSubmit()
{
alert ("You did get here");
var holdBtnElement = document.getElementById('btn_Add');
holdBtnElement.disabled = true;
holdBtnElement.value = "sending ...";
//document.forms["createRequestForm"].submit();
<?= base_url();?>index.php/request"; //this is what I am working on
}
and here is the button:
input type="submit" id="btn_Add" name="btn_Add" value="Submit">
index.php
<script>
// create a global var before calling your external
// javascript file(s).
var BASE_PATH = "<?php echo base_url();?>";
</script>
<script src="link_to_myjavascript.js"></script>
myjavascript.js (jQuery example)
(function($){
$(function(){
var do_ajax = function(some_params){
$.ajax({
url : BASE_PATH + 'controller/method',
});
}
if(conditions)
{
do_ajax(some_params);
}
});
})(jQuery);
Look at ajax call.
Using prototypejs or Jquery
<input type="button" onclick="dosomething()" />
example
<script>
function dosomething() {
var url = "something.php";
new Ajax.Request(url, {
parameters: {//parameters},
onSuccess: function(transport){
// do something when response is good
},
onFailure: function (request) {
// Do something when somehting goes wrong
});
}
</script>

Categories