PHP function calling from Javascript not working - javascript

I am working on a posting system in PHP. The posting system goes through a SQL database and then prints out data from the database. I am trying to use javascript to see if the system has been updated. Basically, I want to use javascript to check whether any new posts have been added. I have some code that goes into the database
function minicheck (){
$query= "SELECT * FROM posts";
$result= mysql_query($query);
return mysql_num_rows($result);
}
The function returns the number of rows in the database every 10 seconds.I use javascript to call this function.
<?php
echo(" <script>
killPage();
function killPage () {
setInterval(function(){
x++;
alert(".minicheck().");
}, 10000);
}
</script> ");
?>
THe issue i am facing is that the function returns the exact same value no matter whether or not a row has been added into the sql databse. Even if I add a row into the sql database, the value that is returned by this function is the exact same every time.
How can I fix this?
Thank You,.

You cannot call PHP functions from JavaScript like that.
What you are doing is calling the function once when building your JavaScript, which is then being sent to the browser.
The browser only ever gets the static value you've put in the string, so naturally it can never update.
If you want to call something in PHP from JavaScript, you'll probably want to use XMLHttpRequest (or any of the readily available libraries like jQuery that can help w/AJAX) to query a PHP file that runs the function and returns the value.

Related

Is it possible to use Ajax to call an internal function?

completely new to PHP, so this is a complete first for me. Right now, I want to try dynamically update a drop down list from 1-10 based on a previous drop down list.
The first drop down list is a table selection, which allows you to choose tables 1-35, and the second drop down list is a seat selection from 1-10. I wish to have it so that 1-10 will update depending on the table to say who has booked the seats on the table already.
I've already found a way to populate the list properly, however I'm having some issues when I try to update it upon the first drop down changing.
I've researched lots of Ajax calls to different files of PHP, however my code is dependent on where the PHP is in the index.php file to populate the drop down. I have a function currently which populates the list when it firsts loads, and I have a small Ajax call towards an internal function inside the same file.
This is the PHP code roughly that fully works (There's a bit more that I left out as it's irrelevant)
<?php
function populateDropdown2(){
for ($i=1; $i<=10; $i++)
{
if ($row[1] == $_POST['TableNum'] && $row[2] == $i)
{
$result = $i . ' - ' . $row[0];
break;
}
}
?>
<option value="
<?php echo $result;?>
"
<?php if(strlen($result) > 2){echo "Disabled";}?>
>
<?php echo $result;?>
</option>
And this is my attempt at the Ajax call:
$(document).ready(function(){
$('#Tabl').change(function(){
console.log("CLICKED");
$.ajax({
url: "index.php",
type: "post",
success: function(response){
populateDropDown2(response);
}
});
});
});
I've read quite a lot about Ajax, however is it possible to call a function that exists within the same file as it inside a different code block? Thanks.
Edit: The function I'm calling has to be in the position it is right now in the PHP file as it's just below all the other input fields for the form
Edit2: I'm getting my values from a CSV file for the PHP.
PHP and JavaScript (your AJAX function) are entirely separate and you can not directly call PHP from within JavaScript:
PHP: Runs on the web server and returns data via HTTP.
JavaScript: Runs locally in the client's browser.
Your AJAX call will have to call specific PHP code, which will then return data to JavaScript, which you can then use to modify the HTML currently being displayed.
If you create HTML in your PHP code, which is then returned to your JavaScript function, you can inject it into your DOM with $.html().
Preferably you'd want to return the data of interest as JSON (see json_encode()) tho and then use that to manipulate your DOM in JavaScript accordingly (see JSON.parse()).
Be sure to return your JSON wrapped into an object instead of arrays for security, see this post regarding the vulnerability.

Ajax, input for searching rows in table, live search

user types something in input, it calls ajax defining it to go on some function in controller. then according to that input it should short list the table rows, matching it with 2 or 3 columns of that database. i have working code of this in simple php. which calls ajax and display the output from another page that ajax calls in the script. but i need it to work in codeigniter. i'm not sure how will i get this working. Any help or advice?this is the function that ajax calls on input change. i've tried to convert my simple php working page code into codeigniter. + i'm calling brandlookup1 which is another page then my current page. any syntax error or best practice? for this kind of issues.
You should try this:
In Controller
function fetch_brands(){
$search = $this->input->post('query');
$data['record1] = $this->Model_Name->Function_Name($search);
}
In Model
function Function_Name($search){
$this->load->database();
$search = $this->db->escape_str($search);
$sql = 'select * from brand where brand like "%'.$search.'%" OR description like "%'.$search.'%" OR status like "%'.$search.'%"';
$query = $this->db->query($sql);
return $query->result();
}

How to transfer a value on DB to JAVASCRIPT through PHP

<?php
// Connect to database server
mysql_connect("192.168.1.101/phpmyadmin/", "root", "praticas") or die (mysql_error ());
// Select database
mysql_select_db("logs_history") or die(mysql_error());
//---> at this point, I want yo pull a VALUE from a column called potencia_ativa and insert in
// the code JS below
mysql_query($strSQL);
// Close the database connection
mysql_close();
?>
//JS code-------------------------------------------------------------------------------------------
<div id="graphHolder" style="height:75%;width:100%"></div>
<script type="text/javascript">
setInterval(
function() {
var d1 = [];
for (var i = 0; i < parseInt(document.getElementById('number').value,10); i += 0.5) {
d1.push([ //----------> pull the value from the php/DB as a FLOAT
]);
}
$.plot("#graphHolder", [{
label: "Label",
data: d1,
lines: { show: true, fill: true }
}
]);
}, 1000);
</script>
Remember, PHP executes on the server and GENERATES the page that runs the Javascript on the client. Putting a value from PHP into the JS code is as simple as:
<script>
var foo = <?php echo json_encode('bar'); ?>;
</script>
If you need to send the PHP data over AFTER the page was generated and already send to the client, then you need to have the client execute an AJAX request to fetch that data from the server. Once PHP has shoved the page out the door, it's basically done and can't "reach out" to the client to do updates on its own.
Also: Note the use of json_encode(). You should NEVER dump output from PHP directly into a Javascript context without it. Anything else puts you at risk of generating JS syntax errors, which will kill the entire JS code block.
Why are you using Interval? Are you trying to update the displaying page data/value automatically after some time passed? That won't work, because if anything changes in database, It won't change in the displaying page, unless you use AJAX to call your php script and return some values, and then, change in the displaying page.
To get a value from PHP script to JAVASCRIPT, you just need to use the php clausule;
var test = <?php echo $variable; ?>
// echo for strings, ints, floats.
// print_r for arrays.
Of course, if your PHP script already injected the data into the page/the data is in the same page you're using JAVASCRIPT, assuming that you have already fetched the data, handled it and etc.

What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing

THE QUESTION
What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing.
I have a MYSQL database and have a PHP script that creates an indexed row array of the database information.
Now that this information is within the array i am comfortable about echoing this data on screen from within PHP.
i.e.
echo $lastplayed[1]['artist'];
My next step is to take the array into JavaScript so that i can use the variable information to display data on screen, make calculations and create an Ajax timer that looks for a value from a variable and refreshes the page..
Its basically a internet radio station that will display what is and has been played and when a counter reaches zero will refresh the page. (the counter being time left of a song)
I could echo each variable into a separate PHP script and then use JavaScript to call each of those PHP scripts that contain the different variables (This seems long-winded) AND puts unnecessary request strain on the MYSQL server
**I really feel that there must be a better way of transferring and handling the data, surely there must be some type of bridge between PHP and JavaScript, should i be looking into JSON ?
So my end result is to be able to take an indexed array from PHP, transfer this array into JavaScript and be able to call on different variables from within the array using indexing (i.e call the variable that resides in result 3 column 3)
And while this is happening i will be using separate PHP and JavaScript files...
Here is my code for the PHP part.
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>
Any thoughts on this would be greatly appreciated and thanks so much for your time.
Justin.
PROGRESS:
Thanks for the comments, i really need to take a JavaScript course at this point...
Now i have created a new output.PHP file that does the following
<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>
So this file now echo's out the data i need in a JSON format from my array $lastplayed.
#VCNinc you say that i now can use the following code to take the data into JavaScript
<script>
var array = <?=json_encode($lastplayed)?>;
</script>
Please could you detail where i put the path information in this code so that the program knows where to look for the .PHP file output.php
Am i doing this right.. should i be printing the data into another .PHP file and then use your code to take the array into JavaScript..
Thanks
Justin.
JSON is the bridge!
You can "export" the variable to a json string and print on the output:
echo json_encode($lastplayed);
TIP: if the php file is used to show a html GUI AND you still want output a JSON too, you can create a GET variable like "&json=1" and, before output your HTML GUI, you do a IF. This way tou can use the same php file to output a GUI and the JSON. WHen you do the request via ajax, you call using the "&json=1".
if(isset($_GET['json']) && $_GET['json']==1){
echo json_encode($lastplayed);
exit;
}
Then, use AJAX to download this JSON string by calling your php script.
$.getJSON(url, function (json) {
//here the 'json' variable will be the array
//so you can interact on it if you want
$.each( json, function( key, value ) {
alert( key + ": " + value ); //here you can do anything you want
});
});
If you have a PHP array $array, you can easily export it into JavaScript like this:
<script>
var array = <?=json_encode($array)?>;
</script>
(and from that point you can manipulate it as JSON...)

How to check if table is empty using cakephp and AJAX?

how do we check if table is empty with cakephp and ajax? In my index.ctp I have an image that when clicked, it will inform the user if the table is empty or not. If it's empty, an alert box will appear, and if it's not, it will be redirected to another page.
<?php
echo $this->Html->image('movie.png', array('onclick'=>'check()'));
?>
JAVASCRIPT:
function check(){
//check browser comp, create an object
object.GET("GET", url, false);
//rest of the code here
}
MoviesController.php
function index(){
//something here
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
I know how to do it using the normal PHP coding, but with cakephp, and since I am new, I dont know yet. For regular PHP coding, I used the GET method for AJAX, and I can specify the URL for the PHP query inside the GET function. I don't know how to do it using cake.
You need to set the layout to AJAX then render your view. I strongly recommend not to use the index() method for this. Instead you can define a whatever() method in the MoviesController:
function whatever(){
//It is not a bad idea to do this only for GET - use the RequestHandlerComponent
$this->layout = 'ajax';
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
The in the view file whatever.ctp:
echo json_encode(array('moviecount' = $moviecount));
//It is a good idea to add an isset() ternary check here like:
// echo isset($moviecount) ? json_encode(array('moviecount' => $moviecount)) : json_encode(false);
Notice that I am creating an array and encoding it to JSON. This is the way to convert variables to and from JSON. To decode use json_decode() of course.
The Client-side code really depends on what you're using to make the AJAX call but let us say that the call succeeded and you got the data back in the data variable:
//Make the AJAX call to example.com/movies/whatever via GET
//Check what data is but it should definitely be an array
if (data['moviecount']) {
//If moviecount is 0 it will go in the else statement - 0 i falsey
window.location = 'example.com/redirect/url';
} else {
alert('No records');
}
I advice against using alert() to inform the user that there are no records. Better put it somewhere in the page - in some div or whatever. Since this is an AJAX request it could be repeated many times. Consecutive use of alert() is not really user-friendly in this case.

Categories

Resources