How to send array to Javascript function from another page? - php

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

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

Passing a Php Variable Through Ajax to Update a Frame

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;
}
}

Can I save serialized form data?

In my continued effort to understand hash tags and page navigation I'm hitting a road block with resubmitting form data if a user uses the browsers navigation buttons (e.g. back and forward).
My function that uses the form data is below:
if(page == "/visits_results") {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits_results=" + start;
});
}
This works fine and dandy if the form is still visible, for instance if I use pagination it performs as I would expect.
My issue is when the user clicks the browsers back button (the form has now been removed) and then they click the browsers forward button. The event gets triggered but my serialized form data is now empty. Is there any way to cache the form data so I can continue to call it?
Any thoughts?
Your best bet (I think) would be to store the serialized data in a cookie. When the user returns to the page which he/she has already filled out, retrieve the data from the cookie, unserialize it, and place it back where it belongs.
Cookies are fairly trivial to work with, there is a decent cross-browser implementation for reading/writing cookies on quirksmode:
http://www.quirksmode.org/js/cookies.html
or if you'd prefer to use a plugin:
http://code.google.com/p/cookies/
http://plugins.jquery.com/project/Cookie
You can save data fairly easily using localStorage like http://jsfiddle.net/zDPjm/
Well, sure, you could do something very simple such as:
if ($("#profile_form_id").serialize() != "") serializedFormData = $("#profile_form_id").serialize();
$.post("visits_results.php", serializedFormData, /* Rest of Code */

How to query database using javascript?

Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.

How can web form content be preserved for the back button

When a web form is submitted and takes the user to another page, it is quite often the case that the user will click the Back button in order to submit the form again (the form is an advanced search in my case.)
How can I reliably preserve the form options selected by the user when they click Back (so they don't have to start from scratch with filling the form in again if they are only changing one of many form elements?)
Do I have to go down the route of storing the form options in session data (cookies or server-side) or is there a way to get the browser to handle this for me?
(Environment is PHP/JavaScript - and the site must work on IE6+ and Firefox2+)
I believe you're at the mercy of the browser. When you hit back, the browser does not make a new request to the server for the content, it uses the cache (in nearly every browser I've seen anyway). So anything server-side is out.
I'm wondering if you could do something very complicated like storing the search result in a cookie during the onunload event of the results page, and then reading the cookie in javascript on the search page and filling in the form - but this is just speculation, I don't know if it would work.
I'd put it in the session.
It's going to be the most reliable and even if they don't go straight "back", it'll still have their search options there.
Putting it in the cookie would also work, but wouldn't be recommended unless it's a very small form.
It's up to the browser, but in most cases you don't have to do anything.
IE, Firefox, etc. will happily remember the contents of the form in the previous page, and show it again when Back is clicked... as long as you don't do anything to stop that working, such as making the page no-cache or building the form entirely from script.
(Putting stuff in the session is likely to confuse browsers with two tabs open on the same form. Be very careful when doing anything like that.)
The problem you have is that the browser will return a cached version of the page, and probably not ask the server for it again, meaning using the session would be irrelevant.
You could however use AJAX to load the details of the previously submitted form on the page's load event.
You would basically have to store it on your server in some way (probably in session variables, as suggested) after the POST. You also have to setup Javascript on the form page to execute on load to issue an AJAX call to get the data from your server (in, say, JSON format) and prefill the form fields with the data.
Example jQuery code:
$( document ).ready( function() {
$.getJSON(
"/getformdata.php",
function( data ) {
$.each( data.items, function(i,item) {
$( '#' + item.eid ).val( item.val );
} );
});
} );
Your /getformdata.php might return data like:
{
'items': [
{
'eid': 'formfield1',
'val': 'John',
},
{
'eid': 'formfield2',
'val': 'Doe',
}
]
}
and it would obviously return an empty array if there were nothing saved yet for the session. The above code is rough and untested, but that should give you the basic idea.
As a side note: current versions of Opera and Firefox will preserve form field content when going Back. Your JS code will overwrite this, but that should be safe.
Another ajaxy options (so it's not good for users without javascript) is to submit the form via javascript and then go the confirmation page (or show the message on the form by replacing the button with a message). That way there is no "back" possible.
Why not store the values into a cookie before submitting? You could also include a timestamp or token to indicate when it was filled out. Then when the page loads, you can determine whether you should fill in the fields with data from the cookie, or just leave them blank because this is a new search.
You could also do everything local by javascript. So you store a cookie with the search value and on pageload you check if the cookie exists. Something like this:
$('#formSubmitButton').click( function() {
var value = $('#searchbox').val();
var days = 1;
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = "searchbox="+value+expires+"; path=/";
});
$(document).ready( function() {
var nameEQ = "searchbox=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) var valueC = c.substring(nameEQ.length,c.length);
}
$('#searchbox').val(valueC);
});
Have not tested this but is should work. You will need jQuery for this.
Cookie functions came from: http://www.quirksmode.org/js/cookies.html
I should say btw that both FireFox and IE have this behaviour by default.

Categories