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;
Related
I have a div which contains comments for a post ... when user add a comment the div containing comments get updated immediately ( i have set a function which is called when user press enter )
Here Is my code for that :
$(document).on('keydown','.addComment',function(e){
var id = $(this).attr('id').match(/\d+/);
var p_id = Number(id);
var comment_box = '#comment_box_'+id;
var content = $(comment_box).text();
if (e.which === 13 && e.shiftKey !== true) {
content = content.replace(/\s\s+/g, ' ').replace(/\n/g, '<br>');
if (content.length > 0 ) {
$.ajax({
type : 'POST',
url : 'update.php',
data: ({
content: content,
id: p_id,
act: "add_cmnt"
}),
success : function()
{
update_ca("comment_area_"+id, true);
}
}); //End of Ajax
}
return false;
}
});
but a user logged in from another account must have to refresh the page to see new comments ... now what i want to do is that all users see the latest comments without refreshing the page i.e when ever a new comment is posted by any user the div containing comments should be updated ... now one way is to do this is that a function is called out after every 10 seconds which refreshes the div via ajax
Here is code :
setInterval(function(){update_comment_area();}, 10000);
this line of code refreshes the comment area after every 10 seconds but i want this function to be called only if a new row ( comment ) is inserted into a database
can anyone help me that how this can be done ??
Create a function that checks for a new row in the database i.e checkNew().
Then try:
if (checkNew()) {
refreshAjax();
}
Note: for the checkNew(), if a new record has been inputted, return true;
Else return false;
Here is a way to implement the checkNow():
Let it retrieve the value gotten from a PHP page that performs the SQL: SELECT lastupdated FROM commentTable ORDER BY id DESC LIMIT 1.
What that does is that it retrieves the last value in the commentTable which would obviously be the last inserted comment. Then update your page with intervals. The comment will continue to change as long as more comments are being added
Since it sounds like you already have an event for the submission of a comment, and assuming you're using javascript to push the comment to the server:
You can just use a callback and have it refresh then. Of course, that would only show up for the user that submitted the comment.
Example for that: JQuery Ajax calls with callbacks
Since you haven't mentioned your back-end coding language or database structure there are only a limited amount of suggestions I can give. However, one that would work would be to use AngularJS, or Socket.io to establish 2-way binding.
UPDATE:
Based on your code and how you're calling it I'm going to assume that update.php has the ability to know whether the record (comment) was added successfully. Once it's been added, have update.php set a global javascript variable to a new value (increment it, use a random number, doesn't matter as long as the value changes)
Then setup an object.watch() that will do your ajax call to update the comments when that variable changes. This is probably the simplest way to do it without using something like socket.io or angular.
How to use object.watch in javascript
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;
}
}
Curiosity killed the cat...
Here's a good one that I need some help with, long story short I am trying to update information on MySQL databases, I understand how to do this with a form on the website and a bit of PHP coding. However, what I am trying to do is create a link on my webpage, just a standard html link, which - once clicked will do the same thing as a form almost (without all the information) which would change a piece of info in the database. Example:
Click "here" to change set number from 0 to 1
Once the user clicks "here" the number in the database changes from 0 to 1.
I would use Ajax. Even though you need to use another PHP file, that won't refresh the HTML page.
1) The link should be something like:
Click here to set number from 0 to 1
2) The Javascript/JQuery code:
function changeValue(value) {
$.ajax({
type: "GET",
url: 'changeIt.php?value='+value,
success : function() {
//does nothing
}
});
}
3) And finally, the code in changeIt.php file should be something like:
$value = $_GET['value'];
//Use MySQL to change the value in the Database
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
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.