Mysql query result is not giving me the right result - javascript

I'm updating my php page each 5 seconds
window.setInterval(function(){
console.log(<?=mysql_num_rows(mysql_query("select * from records"))?>)
}, 5000);
If I have 5 records in my table, the output will be 5,
but when I insert a new record, the output remains 5 unless I refreshed the whole page, then it will be 6..
What's wrong?

You have a fundamental misunderstanding of how PHP and Javascript work. Don't worry, it's very common when first learning web development!
When you use PHP to print things onto the page (for example the code inside <?= ?>), the code is executed on the server. Try viewing the source of your page, and you'll see that when the browser receives the page, the PHP code has already been replaced by its result.
This means that when your Javascript loop runs, it's simply writing out the same precomputed value repeatedly.
To accomplish what you're going for, you'll either need to accept simply refreshing the page every 5 seconds, or read up on AJAX. AJAX is how you can load new content from the server (so, anything from the database) without reloading the page. It's what StackOverflow uses to show "1 new answer to this question", for instance.

This is because you are mixing PHP with JS, PHP value is written on page load and it remains that for all the time you stay in the page.
You should use a Ajax request that request again the value.
Do a PHP page that only returns this value:
<?=mysql_num_rows(mysql_query("select * from records"))?>
Then extend you JS with something like this:
setInterval($.ajax({
url: 'your-url-with-php-result',
type: 'GET',
cache: false,
success: function(result){
console.log(result);
}
}), 5000);
You need also to include Jquery to do this

you can not use php in javascript codes
you soulde save php in example.php and you call example.php in javascript code
your example.php like this
<?php
echo mysql_num_rows(mysql_query("select * from records"));
?>
and you can now get data from example around 5 second time by this code (load is jquery function)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
setTimeout(function(){
$("#showRes").load("example.php");
}, 5000);
</script>
</head>
<body>
<div id="showRes"></div>
</body>
</html>

you are normally mix the concept of jaavscript and php .you can solve this very easily . by passing php value into ajax and that value u should catch in that javascript .Try viewing the source of your page, and you'll see that when the browser receives the page, the PHP code has already been replaced by its result.
write php code in php page like:-
<?=mysql_num_rows(mysql_query("select * from records"))?>
and use js as different page . call that value as your requirement.
like:--
setInterval($.ajax({
url: 'your-url-with-php-result',
type: 'GET',
cache: false,
success: function(result){
console.log(result);
}
}), 5000)
if u need some jquery then you also include that in your code .

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

PHP file called by javascript and another php file

I have a php file (I will call ORIGINAL) which do some calculations (through db mysql). I want to read this php from javascript. For that operation I have used ajax function and my php uses echo $result to print the data I need.
Everything is perfect here.
What happends now, I am creating another php file which need to call the ORIGINAL php file. If I want to call it, I must change the echo to return which is normal. This causes that my javascript call doesnt work.
Do you have a solution which work for both situations?
Thanks in advance.
Do you mean something like this?
original_php_file.php:
<?php
require_once "other_php_file.php"; // include all of the other files contents
// all code contained within original_php_file
?>
You were being pretty broad with your request (not including file names or code), so this is all I can assume you need.
Tell me if it helps :-)
Just send one more parameter into your ajax request to tell that ORIGINAL php file what type of output it should return.
Into your ORIGINAL file check for that output so you can understand from where that request come and what output you should return.
$.ajax({
url: 'ORIGINAL.php',
data: 'data=test&output=1',
success: function(r){
// here you have your output
}
});

How do I execute a PHP function every two seconds inside JavaScript?

I have this PHP function called GetTotalItemsPercentage() which gets the amount of entries in my MySQL database and returns a percent based on the maximum amount of entries that are allowed (returns 50, 40, 39 etc.). However, I want this to update a div's height depending on this percentage. I currently have this code, however after the first update, it doesn't update again.
<script type="text/javascript">
setInterval(function() {
$("#filled-jackpot-display").animate({height:'<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>%'});
}, 2000);
</script>
So how would I go about getting it to update every two seconds and constantly change the size of the div? I'm guessing I will have to run a loop in the PHP code and then use echo inside the PHP file to run JavaScript rather than the other way.
PHP executes on server, javaScript on the client, you have to make a new php file with
<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>
in it, let's call it 'getTotalIP.php' then you call it with ajax.
<script type="text/javascript">
setInterval($.ajax('getTotalIP'), 2000); //Short answer with jQuery
</script>
If your script is intended to print something then you need more code to parse the answer. A good way to do it is printing the php result in json and parse it with javaScript.
Here you have more cross-browswer ajax information: https://www.w3schools.com/php/php_ajax_php.asp
You cannot execute PHP on the client side. The way to do this would be to call the php code with ajax() and then animate in the success handler
myscipt.php
<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>
myscript.js
setInterval( function() {
$.ajax({url: 'myscript.php', success: function(data){
$("#filled-jackpot-display").animate({height: data});
}, 2000);
Note, since ajax is asynchronous, it may not smoothly animate in 2 second intervals. If you only need the height once, then load it on ready and proceed to animate in 2 second intervals

JS/jQuery passing array/variable/data to PHP in same page?

Im hoping you can point me in the right direction.
I have a php page, that includes some HTML markup and some JS/jQuery routines to build an array of 'user choices' based on the 'user input' (checkboxes..etc).
my question is, how can I pass off this (multidimensional) array to PHP, that is in the same page? (ultimately I want to save this data/array to my PHP session)
While looking around, I read about using another (external) .php script to do,, which is NOT what Im after, I'm hoping to do this to the SAME PAGE I'm in... WITHOUT A REFRESH.
will $.post() do this for me? without a page refresh (if we suppress the event or whatever)...
and -not- using an external .php script?
I understand PHP runs/executes FIRST... then everything else..
I'm not really trying to get PHP to do anything with the data being sent from JS/AJAX.. outside of save it to the SESSION array..
Ajax seems like it will be needed?
To summarize:
1.) PHP and JS are in/on same page (file)
2.) No page refresh
3.) No external PHP script to do 'anything'.
4.) Trying to get (multidimensional) array to PHP session in same page.
5.) I am trying to 'update' the PHP SESSION array each time a user 'clicks' on a checkbox.
I have read a little on using AJAX to post to the same page with the URL var left empty/blank?
edit:
to show the data, I want to pass...heres a snippet of the code.
its an array of objects.. where 1 of the poperties of each object is another array
example:
var somePicks = [];
somePicks.push({casename:caseName, fullname:fullName, trialdate:trialDate, citystate:cityState, plaintiff:plaintiff, itemsordered:itemsOrdered=[{name:itemOrdered, price:itemPrice}]});
when from all the checkboxes.. I update the 'sub-array' (push or splice..etc)
somePicks[i].itemsordered.push({name:itemOrdered, price:itemPrice});
'this' is the array/data I want to get into my PHP session from JS using whatever I can AJAX most likely.
You can sort of do that, but in essence it won't be any different than using an external PHP file. The PHP code gets executed on the server before ever being sent to the browser. You won't be able to update the PHP SESSION array without reconnecting with the server.
If you really want to use post to call the current page (I don't think you can just leave the url blank, but you can provide the current file name), you can just have the PHP handler code at the top of the page. However, this would be the exact same as just putting that handler code in an external file and calling it.
Either way, the page will not refresh and will look exactly the same to the user.
You can use $.ajax function with $(#formid).serializearray (). And use url as ur form action in $.ajax function.
I hope it will work for you
<form id="formId" action="post.php" methor="post">
<input type="checkbox" name="test1" value="testvalue1">TestValue1
<input type="checkbox" name="test2" value="testvalue2">TestValue2
<input type="button" id="buttonSubmit" value="click here" />
</form>
<script>
$("document").ready(function ()
{
$("#buttonSubmit").click(function () }
{
var serializedata=$("#formId").serializeArray();
$.ajax(
{
type:"post",
url:$("#formId").attr("action"),
data:{"data":serializedata},
success:function()
{
alert("yes");
}
});
});
});
</script>
<?php
if(isset($_POST))
{
session_start();
$_SESSION["data"]=$_POST["data"];
}
?>
I suggest to use the .post method of Jquery, to call a PHP file, sending the array and processing in the PHP called.
Can find the jquery documentation about .post() here: http://api.jquery.com/jquery.post/
Edited:
I used this case some time ago:
document.getElementById("promotion_heart_big").onclick = function(e){
$.post("' . URL_SITE . 'admin/querys/front.make_love.php",
{
id_element: ' . $business["promotion"]["id"] . ',
type: \'promotion\',
value: $("#field_heart").val()
},
function(data) {
if (data.result) {
//some long code....
}
}
},
"json"
);
from some preliminary testing..
this does NOT seem to be working, (will do more test tomorrow)
$.ajax({
type : 'POST',
//url : 'sessionSetter.php',
data: {
userPicks : userPicks,
},
success : function(data){
//console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
});
It was mentioned that posting to external .php script -or- posting the same page would produce the same results..
no page refresh
$_SESSION would update for future pages
Does anyone have an y example for that?

auto reload: how it works?

i need to change something in my site, if some fields changed in database, but without reloading the page! but i have no idea how i can do it.
could you give me an idea? thanks
example:
for example, i have a forum, and i need to show a image, if new comment resieved! i can write all functions, but i don't understand when i must call the function?
maybe window.onload?
Then you need AJAX!
Explanation:
You need two pages, the main page which does not "reload". And a second one which returns two versions of the small image based on the database field.
Page one has this JavaScript in it:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
/* normal ajax without periodical refresh
$.ajax({
url: 'page2.php',
success: function(data) {
$('#database_status').html(data);
}
});
*/
var refreshId = setInterval(function() {
$('#database_status').load('/path/to/your.php');
}, 3000);
</script>
// Or you use the jQuery plugin Heartbeat: http://www.jasons-toolbox.com/JHeartbeat/
And a div <div id="database_status">empty</div>
The second page, returns a image tag based on the database setting for example in PHP:
<?php
// do db request
if ($request) {
echo '<img src="true.gif"> TRUE';
} else {
echo '<img src="false.gif"> FALSE';
}
Ajax
Once you've familiarized yourself with the concept, you can reference the jQuery AJAX documentation for information on how to implement it with jQuery.
You can use jQuerys load- or JSON-method to get data from your server.
In your case the following scenario is possible:
The site loads.
Your JavaScript loads the initial data from the server.
Now, every couple of seconds or minutes (Depending on your use case), the JavaScript asks the server if anything changed since it last asked (Use timestamps in your request, for example).
If so, change the website accordingly.
Goto 3.
Please keep in mind that excessive polling might but enormous strains on your server, especially if you have a lot of users. Long-polling or Comet are advanced techniques to handle the load.
The easiest way to perform an ajax request with jquery is the load method. On that page you can also see plenty of examples.
There are two basic approaches you can take:
Use setInterval to make an Ajax request periodically that ask the server if there are any updates.
Use Comet to fake server push
Try Ajax, e.g: using jquery which allows you to handle those in a high level js.
example in this site when you do the send email

Categories

Resources