Passing a Php Variable Through Ajax to Update a Frame - php

I have a server-side PHP page that draws data from an SQL database to populate an array of PHP variables. I use the last array value for each variable to initially populate the data into the 3rd frame of a form (i.e., value = ). This form has a "previous" and "next" link that I want to use to populate the 3rd frame of the form with the "previous" or "next" set of variable values (i.e., value = ) dynamically without loading the entire page. While I'm very familiar with javascript, php and sql this will be the first time I've tried to use AJAX. What I'm trying to do is pass the array number or counter, which is a php variable, to an AJAX function which increases or decreases the array counter (i.e., $counter) so that the values for the next set of variables appears in frame 3 of the form. My problem is that I'm sure that I can pass the current $counter value to the AJAX function which will process it as a javascript variable but how can I then pass the result back to update the php variable in frame 3 of the form? Any help will be very much appreciated.
Blacksquare:
My php web page does the first part. It gathers data from the underlying SQL database and places it into a php array. When the web page initially loads, the most recent or last record is used to populate the form fields that are all in a single frame using something like this (value=$dataField[$counter]). This works when the page is initially loaded populating all of the frame fields with data from the last record in the SQL database. What I'm trying to do is create an AJAX function activated by clicking on the "next" or "previous" link (i.e., an onclick event) that takes the $counter value and increases or decreases it by one (1) and then refreshes the frame displaying fields from the "next" or "previous" php array record in the same frame without reloading the page.

You need to create a php file which will handle the ajax request (passing the variable as post parameter) and echo your response in the php file.
Then in ajax file you will get response in success, update the response using jQuery into the form.
Note: Don't forget to put 'exit' after the response in php file.
For example:
$.post( "test.php", { counter: <?php echo $counter; ?>}).done(function( data ) { alert( "Data Loaded: " + data ); });

What about altering appropriate HTML elements using JavaScript after you get results of the ajax call? There is no need to set the php variable and then to use that field to set a value in HTML when you can alter that HTML value directly from JavaScript.

You can't pass a variable back into a static page generated by php. Probably the best approach is to load only the form on page load. Then grab the dynamic data using an ajax call to another php script on the server side (I'm using jQuery for the ajax).
$.ajax({
type: "GET",
url: someURL, //A link to your php script that will load the data
dataType: "json" //Ask for json data from the server
}).done(function(data) {
nextRecords = data;
getNextRecord();
}).fail(function(resp) {
console.log("Something Went Wrong");
});
Move your sql logic to a separate php script accessed at someURL and have php pass back an array of json data like this
$query = ...Your select query returning an array of results
echo json_encode($query);
exit;
Now when a user hits the next/previous button, you can easily grab the latest record without posting to the server.
function getNextRecord() {
if (nextRecords.length > 0) {
var record = nextRecords.pop();
var node = document.getElementById(node_name);
node.innerHTML = record;
if (currentRecord){
prevRecords.push(currentRecord);
}
currentRecord = record;
}
}
function getPreviousRecord() {
if (prevRecords.length > 0) {
var record = prevRecords.pop();
var node = document.getElementById(node_name);
node.innerHTML = record;
if (currentRecord) {
nextRecords.push(currentRecord);
}
currentRecord = record;
}
}

Related

Click counter on PHP and MySql

If someone click on clickme div the counter increases in the database. Currently when the page refresh the counter increases.
<div class="Hello">Click Me</div>
<?php
$find_counts = mysqli_query($conn, "SELECT * FROM ad_section");
while($row = mysqli_fetch_assoc($find_counts)){
$current_counts = $row['no_of_clicks'];
$new_count = $current_counts + 1;
$update_count = mysqli_query($conn, "UPDATE `ad_section` SET `no_of_clicks`= $new_count");
}
?>
Alright... so I am going to help you understand what AJAX is in a simplified practical manner.. because once you understand AJAX.. You'll be able to solve this and many other problems.
AJAX is not a 'language' or a 'technology' .. It's just an upgrade to how browsers can interact with servers.
Earlier (before AJAX, long before AJAX), when a browser had to request data/page from the server, it had to either refresh the page or request a whole new page.. and display it on a new window.. but it had absolutely no way of doing so in the "background" .. and then updating the currently displayed HTML page without any disturbance.
This is what AJAX solves.
So now.. through Javascript or Jquery.. (same thing) .. you can send a request to a server (to any end point on any web-server) with data... and the server.. then potentially has the ability to read the data you sent, process it in any way..and return back result in the form of data ..
The data going and coming is in the format of JSON (Javascript Object Notation) ..which is nothing but a way to encode data and arrays
So you send a JSON and the server gives you a back a JSON or an error page (404, etc.. )
The magic happens now...
Your page.. after receiving back the result from the server.. still on the same function execution that had sent the request ... will be able to open up the result.. and using Javascript/Jquery/DOM Manipulation.. plug in the results to the current HTML page or take any new action.. like display an alert, redirect, animate, etc..
So this is how it works:
Imagine you got a DIV upon which a click should set data update on the server and then get result from the server and refresh itself..
<div id='clickme'>People clicked ... <span id='howmany'>1</span></div>
<script>
//Not accurate code, I'm just writing from what I remember .. jquery
$('#clickme').click(function() {
//event captured on click on 'click me'
var nothing = ''; //there is no data to be sent, really.. because we will be getting the update from the server on how many people have clicked it..
//AJAX NOW... //sending a post request
$.post(
'https://mywebsite/index.php/incrementMe',
{data:nothing},
function(data)
{
//this is the function that will receive in its data the result back from the web-server function incrementMe
var result = JSON.parse(data); //parsing the JSON into javascript object/array
$('#howmany').html(result['updatedInfo']); //updatedInfo is the variable within the result that was sent back from the server.. which I then.. using DOM manipulation, plug it back into the span ID
}
);
//End of AJAX request... you didn't have to refresh the page..
</script>
On the server.. you'd have something like this: (writing PHP YII style)
public function actionincrementMe()
{
$data = json_decode($_POST['data']); //got the posted variable and decoded using a PHP function .. to get a PHP array/object
//well in fact, you don't even need this.. because.. there is no info coming to you from the front end .. but if you had, then this is how you'd receive it..
$newnumber = SQL to find out latest number + 1;
print json_encode($newnumber); //this is the function that will just answer back the front-end with a json formated data point..which is the variable new number..which you would then have received in the javascript function.
}
One of the ways is by doing it like this (only the steps i have included)
- Create a table with image id and click counter
- Implement a function on the image click or div click (if there are more images then you can use a generalized image click function
- Inside the function use ajax to implement the count increasing functionality

Jquery/Php returning processing status with Ajax POST

I'm working on a page to process Excel data.
Currently I have an index page where I once submit JSON data (filename, selected columns, worksheet,..) via $.ajax POST to a PHP page for processing (iterate every row with posted selection). But I would like to have some progress response from the processing page. Because now, it just submits and processes everything in the background without knowing if it's done or not.
Is there some kind of way to:
Redirect to the processing page, along with the JSON POST data, instead of an ajax post?
OR
Return multiple JSON responses from one PHP page (like started, stopped,..) and fetch those responses in the same $.ajax success function? Add some kind of check function like
IF last response-line == started, show image
..after a while (keep checking json response..),
IF last response-line == finished, hide image?
I couldn't use the form submit action, because I'm sending a full JSON string instead of seperate input values.
Am I overlooking something here or is this just not possible (with my way of processing)?
You need to use ajax calls to a different PHP file that gets the progress from a session. I also did this once and I did it like this:
Javascript
function getProgress(){
//console.log("progress called");
$.get( "getprogress.php", function( data ) {
//console.log(data);
var p = data.progress;
if (p!=100){
//set your progressbar here
}
}, "json");
}
And in the function where you start the job you just set a timeout
timeout = setInterval('getProgress()', 1000);
Getprogress.php
ob_start();
session_start();
session_write_close();
$output = array();
$output['progress'] = $_SESSION['progress'];
echo json_encode($output);
In your PHP file where you do the actual work, you need to set the progress like this:
session_start();
$_SESSION['progress'] = $progress;
session_write_close();
Remember to use session_write_close() because the session can only be open in one process at a time.

How to send array to Javascript function from another page?

I have a static site (let's call it settings page), and my Javascript function takes with AJAX data from mysql table and draws table on a HTML document.
It works like a charm - it takes all the data I need and doing it in a proper way.
Here's my function:
function get_people()
{
$.post("/controller/get_people", function(data,status,xhr)
{
if(status=="success")
{
people_data = data;
draw_table();
}
})
}
The thing is, on ANOTHER PAGE I have table with all people and checkboxes next to them.
I'm checking this checkboxes, clicking a button and I want to get into settings page - and my get_people function will select data from mysql only about people checked on previous page.
technically the problem is - how can I pass an array to javascript function from another page? Can I save it on a DOM or something and read it from JS?
Please provide me some ideas : ]
You can use sessionStorage and JSON.parse.
On your first page:
var arrayJSON = JSON.stringify(yourArray);
sessionStorage.setItem("tabledata",arrayJSON);
On your second page:
var tableData = JSON.parse(sessionStorage.getItem("tabledata"));
This will save the data as a string in your browser for the duration of the current session. If you want it to be stored more permanently, you can use localStorage instead of sessionStorage (same syntax) and it will be stored even if the user closes the browser and comes back later.
There's more on sessionStorage and localStorage at the MDN docs

sharing variables in between php and javascript

Following is my job:
Consist two iframes
In 1st a form asks for user name and address and have a button "Add".
On clicking Add this info is added to mysql database, and again the form is shown with a message that your info has been inserted to database.
In the 2nd iframe there is some interesting. It will show in a table all the users in database. In background a php function will regularly checks for new user added to database at some interval(say 5 sec), and if any new row is found in MySQL DB (which is not in the table in HTML iframe), it will be added to the table in HTML iframe page (may be using javascript functions).
I have done with first 3 steps. Please help me for the 4th step. I want to use PHP and Javascript.
Use AJAX - acquire new rows or all rows. And just write it in database.
Example (with jQuery - without JSON-driven data transfer):
1, getData.php
$dbData = array(); // YOUR DB DATA HERE
$output = "";
foreach ($dbData as $row) {
$output .= "<tr><td>{$row['name']}</td><td>{$row['email']}</td></tr>";
}
echo $output;
2a, JS code (using jQuery - downloading whole table from database)
function autoRefresh() {
$.get('getData.php', null, function(data){
$("#myUltimateTable tbody").html(data);
}, 'text');
setTimeout("autoRefresh();", 5000);
}
2b, JS code (using jQuery - downloading only new rows from database)
function autoRefresh() {
$.get('getData.php', null, function(data){
$("#myUltimateTable tbody").append(data);
}, 'text');
setTimeout("autoRefresh();", 5000);
}
Try to create hidden text box and assign php variable value to that textbox and than you can access that value by doing
document.getElementById('id_of_textbox').value;
Or in your case for accessing HTML elements in iframe maybe you need to do:
top.frame_name.document.getElementById('id_of_textbox').value;

display html select (from PHP) via jquery?

So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed
if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.

Categories