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

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.

Related

Delete previous row in database show the next row in database by clicking button

I need Help on this, base on what I already did: In the output every time I click the button it shows the row (comments) in database. But I want that If I click the next button it will show the row (comments) in the database and when I click it again It will delete the previous row (comments) in the database and show the next row (comments).
Here is the code:
<?php
include 'dbh.php';
$commentNewCount = $_POST['commentNewCount'];
$sql = "SELECT * FROM comments LIMIT $commentNewCount";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['id'];
}
} else {
echo "There are number!";
}
?>
This is for the button:
<script>
//jQuery code here!
$(document).ready(function() {
var commentCount = 0;
$("button").click(function() {
commentCount = commentCount + 1;
$("#comments").load("load-comments.php", {
commentNewCount: commentCount
});
});
});
</script>
You have AJAX tagged in your question, so I am assuming that you are somewhat familiar with the term. This can indeed be done by AJAX, but I don't see any AJAX attempts in your code?
Also, when you say delete, do you mean specifically delete by the literal sense, or simply that your comment display works as sort of a sliding function, removing the previous comment from display, showing the next comment in queue? I am going by the literal sense in my example, since that's what I have to assume really.
What you could do, is to have a file that handles all the comments, and displays them however you like. For instance,
<?php
$sql="SELECT * FROM comments ORDER BY id DESC";
$result_set=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_assoc($result)) {
/*
html construction of displaying comments,
echo'ing the row value that displays the comments.
echo $row['comments']; as a guess
*/
}
?>
Let's call that PHP file comments.php for the sake of referencing later on. Also note, that I chose to make an ORDER BY in a descending order. Assuming your comment id is an auto increment, then this will always display the newest comments first, since the highest id's will be the latest entries.
Then, in another file, display-comments.php as an example, you could make a document.ready function, that loads your comments into an element, <div> element for example.
The AJAX function could look like this:
$( document ).ready(function() {
function loadCommentsAjax()
{
$.ajax({
type : "POST",
url : "comments.php",
data : { },
success: function (html) {
$("#commentContainer").html(html);
}
})
}
});
What I do here, is that I encapsulate an AJAX function in a document.ready function. What this does, is that when the document is ready, it fires the AJAX function.
How the AJAX function works, is that we declare a data type. The most common are probably POST and GET. You can look up the different data types, how to handle them, and what they mean specifically. The main difference between POST and GET for instance, is that GET displays its values as parameters in the URL. Since we aren't parsing any data, we could use a GET just fine, since it will have no influence. However, should you ever need to parse sensitive data, where you don't want the user to mingle with the data, then you should use POST.
We then tell the AJAX function, which page/file it should work with. In our example, it will be the comments.php that we created earlier. It will then in the success function, paste the html content into a container that we defined. In this case, commentContainer. Note that it's an id specific targeting, which means our container element needs to have that specific id. Note, that the container is in our main file, the display-comments.php file.
An example of the container could be the following:
<div id="commentContainer"></div>
This div element will then contain the comments and html logic that we made in our comments.php file.
In your button, you can then have another AJAX function, handling the comment deletion, and call our loadCommentsAjax() function on success, to reload our comments in the appropriate fashion.
The AJAX function handling the deletion of comments, would then again have a PHP file that will perform the delete. We'll call this delete-comments.php in our example.
example of our delete AJAX function:
function deleteNewestComment() {
$.ajax({
type : "POST",
url : "delete-comments.php",
data : { },
success: function (html) {
loadCommentsAjax();
}
})
}
Our delete-comments.php will look something like this:
<?php
/*
since you are deleting the latest entry each time, what we could do,
is make an SQL query that deletes the max id from the comments table
*/
$sql="DELETE FROM comments WHERE id=(SELECT max(id) FROM comments)";
$result=mysqli_query($conn, $sql);
?>
We will then have our button call the delete function like so:
<button onclick="deleteNewestComment();">Delete latest comment</button>
Let me know if this is what you were looking for at all, or whether you really just wanted a sliding kind of logic, where you simply iterate through your comments, displaying one at a time.
But in case you did mean literally delete, then wouldn't it be better to have delete buttons linked to each comment, so that you can delete them seperately, and independantly?

PHP function calling from Javascript not working

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.

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.

How to pass javascript var into a ajax remoteFunction?

I have a view where ill have 3 divs:
Div 1: List of Brands with checkboxs.
Div 2: List of Categories with checkboxs.
Div 3: List of Items.
This last div will be refreshed with the all the items according to what is selected in the first two divs. At beginning it shows all the items, after we select some of the brands and/or categories and press refresh i'll want to refresh the div 3.
In Javascript I can get which of the categories/brands are selected and my biggest doubt is on how to refresh the last div...
Heres what I was trying:
function refresh() {
var brands= /*<code where i get all the brands selected (this will be a js array)>*/
var categories = /*<code where i get all the categories selected (this will be a js array)>*/
<?php echo $ajax->remoteFunction(array('url' => array('controller' => 'items',
'action' => 'men', brands, categories),
'update' => 'itemsContent')); ?>
}
My problems are:
- How do I pass the js vars into the php method?
- How do I receive an js array in a cakephp action? Because brands and categories will be used to filter the query that produce results for the div 3...
You won't be able to use the $ajax helper here, since it just outputs a static script which can't be changed/influenced at "run-time" in the browser. It just wasn't made for something more complex than it is.
So, you'll have to roll your own JS, which shouldn't be that hard though. All you need is:
a Cake action that outputs a list of items based on the data it receives (shouldn't be hard)
a bit of JS that figures out which brands and categories are selected (which you already have)
another bit of JS that packages that data and sends it to the Cake action
another bit of JS that updates the site with the list of items you received back
I'd take a look at jQuery's AJAX functions to accomplish #3. If you POST the data in a format like this, it's very easily accessible in $this->data in Cake:
{
'data[ModelName][categories]' : categories,
'data[ModelName][brands]' : brands
}
Regarding your question:
"How do I pass the js vars into the php method?"
You don't. PHP runs on the server and is already finished by the time the Javascript runs in the browser. The only "communication" between JS and PHP is via standard HTTP GET and POST requests, and there it doesn't matter whether the request comes from a standard browser or JS or Flash or whatnot.
The $ajax helper just has a bunch of pre-fabricated Javascript snippets it can put into your page, but your JS will not be able to "talk to" the $ajax helper in any way.
I had a similar scenario to yours, and I found a few methods on the Javascript helper that are applicable. I used codeBlock() to wrap a chunk of javascript, and event() to wire up the click event, but I'm not sure how much clearer this is than just writing the raw Javascript.
I found the AJAX section of the CakePHP manual to be really helpful for getting the basic set up. Then I took the generated Javascript and made it more dynamic.
In this example, I'm calling the add_topic action whenever the user clicks the link. Every time it gets called, I increment the topicIndex variable and pass it as a parameter in the AJAX call. The AJAX call returns a few rows that are inserted in the table above the link that the user clicked.
<tr id="add_topic_row"><td colspan="3">
<a id="add_topic_link" href="javascript:void(0);">New Topic
<?php echo $html->image('icons/add32.png');?></a></td></tr>
</table>
</fieldset>
<?php
echo $form->end('Submit');
$addTopicUrl = $html->url(array('action' => 'add_topic')) . '/';
$script = <<<EOS
var topicIndex = $index;
var addTopicUrl = '$addTopicUrl';
addTopic = function()
{
new Ajax.Updater(
'add_topic_row',
addTopicUrl + topicIndex,
{
asynchronous:true,
evalScripts:true,
insertion:Insertion.Before,
requestHeaders:['X-Update', 'add_topic']
});
topicIndex++;
}
EOS;
echo $javascript->codeBlock($script);
echo $javascript->event('add_topic_link', 'click', 'addTopic();')
?>

Categories

Resources