ajax, jquery with mysql query in js - Is this possible? - javascript

When doing ajax/jquery I normally use the below code to achieve that and it works perfectly fine. To explain what happens below it basically calls the commentS.php script and outputs the data where the id equals to the fieldID and to check for those results every 3 seconds and output the results within the div tags.
<div id="content"> </div>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#content').load("commentS.php?id=<?php echo $fileId; ?>")
}, 3000);
});
</script>
HOWEVER I have several different outputs I would like called and wanted to find out if there was a simplified way to achieve it.
Like I have this line
$delstoriesbyadmin = mysql_query("SELECT count(*) FROM story WHERE deletedby !='0'");
<?php echo mysql_result($delstoriesbyadmin, 0); ?>
I'm asking is there a way in ajax/jquery instead of having an external file with the script just run the mysql query within the call and output the results and have it run that call every 3 seconds. (without the use of an external file). I am new to ajax/jquery. Just want to know if that I want to achieve is possible.
thanks for your answers.

I think you need to do Ajax request nested of load the file....this
solution for your case is build an action page thats return needed
result every request
Ajax Example:
$.ajax({url: "commentS.php", data: {"id": yourId},success: function(result){
// do somthing with success result...
}});
PHP:
$delstoriesbyadmin = mysql_query("SELECT count(*) FROM story WHERE deletedby !='0'");
echo json_encode(mysql_result($delstoriesbyadmin, 0));
In php you need to return data as a JSON type.
Note: if you need to do something every time, and its like get any update comment or something like this behavior, you can use a socket.io for that.

Related

Should I create a PHP file for every SetInterval() that I create?

I use this JS to call a PHP file in header.php every second.
$(document).ready(function(){
setInterval(function(){ $('#show').load('m1.php') }, 1000);
})
<div id="show"></div>
In m1, I get data from a database:
$getvalue=mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM users WHERE user_accID=$user_accID"));
$user_value=$getvalue['user_value'];
echo $user_value;
I want to get another data from database for example user_value30 and call this data with setinterval again.
Should I create another m2.php and call it again with same JS?
This way it would be so complex.
Please don't tell me get the all data in m1.php.
I can't because I want to show this data different places in header.php.

Mysql query result is not giving me the right result

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 .

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

Ajax after success, how to pass data to a variable to php

I have script like this
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
I don't know how I can pass data response to php code ?
For Example: if I alert response, it's show 123 .so I want pass value 123 to a variable in php
$id = 123
response is the result passed BY php, not TO php. What's passed to php is the id and the task.
In your tab.php, you can access these two values :
<?php
$id = $_POST['id'];
$task = $_POST['task'];
//do anything you want with it...
?>
This is not the right workflow. PHP executes on runtime, so every time the page has finished loading you can't really put variables back into PHP (unless you reload the page). This is where AJAX comes in, so you can call PHP scripts from JavaScript / jQuery and don't have to reload the page every time.
The right thing to do is to either store the variable you have generated in the tab.php script in a database, $_SESSION, $_COOKIE or something similar like so:
//put this at the top of all your php scripts you want to use the variable in
session_start();
//now store the variable you wanted to pass (in tab.php)
$_SESSION['returnValue'] = $myValue;
Now if you want to use the variable in other pages just echo it like so (remember to add session_start() at the top of the PHP script.
echo $_SESSION['returnValue'];
First of all, start by reading this
To answer your question,
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
The result from id and task are sent via $_POST (type:"POST") to the page tab.php (url:"./tab.php"). If you want to do that on a different page, just change the url in your ajax call: url:"./any_other_page.php" and the posted values will be sent there
Finally, read THIS post as well. It is greatly written and very well explained.
Hope it helps!
Keep on coding!
Ares.

JQuery/AJAX: How to pass variables to some JS-API?

I have a problem with passing JS-defined Variables from an AJAX response to a JS-API, namely Googles jsapi. What I want to do is display a chart using this API and then use AJAX from time to time to reload the values from a database.
So far, everything works just fine. But as I return these variables by AJAX - how can I get JS to parse the result?
The code:
<div id="t">
xyz
</div>
<script>
window.setInterval(function()
{
$.post('mod/script.php', function(data) { $('#t').html(data) } );
}, 5000);
</script>
Where script.php would return values like
echo "data.addRows($datasets);";
echo "data.setValue($i, 0, '$date $time');";
Problem is, that I dont know, which values are returned by the script. This depends on what is currently stored in the database.
How to do this right? I have some ideas, but I wonder what is the most convenient way here...
If I get you right, you want to execute certain JS callbacks in the context of the current document, is that right?
The proper way would be JSONP.
A really really really quirky "alternative" would be to do this in your script.php:
echo "(function(){";
echo "data.addRows($datasets);";
echo "data.setValue($i, 0, '$date $time');";
echo "})()";
and have this callback:
$.post('mod/script.php', function(callback){ eval(callback); });
Also, see this fiddle: http://jsfiddle.net/EsytA/1/

Categories

Resources