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

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/

Related

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

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.

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.

A method to pass a variable to Javascript currently run in the header

Please excuse me ignorance, I'm completely new to Javascript.
I have this code that is currently run in the header, however I need to pass it $_GET variables before it runs.
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc');
jQuery('#mintpal-price').load('http://<site>/realtime/mintpal-realtime.php?symbol=ltc');
});
function refresh() {
setTimeout( function() {
jQuery('#bittrex-price').fadeOut('slow').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc').fadeIn('slow');
jQuery('#mintpal-price').fadeOut('slow').load('http://<site>/realtime/mintpal-realtime.php?symbol?ltc').fadeIn('slow');
refresh();
}, 10000);
}
It's pretty simple, all it does is pull the latest price from another PHP script.
I need to append a $_GET variable to the URL as current I have no way to change the ?symbol=ltc depending on which page the user is visiting. Because Wordpress is being awkward, I've had to save this function in a .js file and add a hook in functions.php otherwise it won't load at all. Ideally, I'd like to be able to run the function in the body so I can modify, but I can't get that to work either :/
I hope this makes sense, I'm open to any suggestions as I'm clearly missing the point somewhere here.
Thanks
You need to use the language that is building the web page to output some javascript for use in your functions.
Thus, if you're using PHP to build your page you could do something like this in the <head> section of your page:
<?php
print '<script>';
print 'var symbol = ' . $_GET['your_get_variable'] . ';';
print '</script>';
?>
Then, in your later javascript code you have your GET variable string stored in 'symbol' and can use it however you like.
The 'your_get_variable' is what is coming in via the query string in the URL that got you to the current page. Just make sure you put this code above where you want to use 'symbol' in your later javascript.
Also, It's not really a good idea to use $_GET data directly like that without some validation, but I'm just keeping the example clean.

Set a PHP Variable through jQuery function

Hey guys i have a system where when you click one div it loads up one div and the other loads up another but instead of this i'm trying to get it to load up content based off a variable to consolidate things betters
So the main question it, how do i set a PHP through a jQuery function e.g.
<script>
$(document).ready(function () {
$('.redboothApp').click(function(){
<SET VARIABLE>
$('.whiter').fadeIn(250);
});
});
</script>
So then in the PHP it will be something like:-
<?php
if (($appLaunched) == 0) {
echo "0";
}
else if (($appLaunched) == 1) {
echo "1";
}
?>
Thank you in advance, help would be greatly appreciated :)
You can't set a PHP variable with JavaScript. PHP is parsed and executed on the server and then outputs the data to the browser. Once output to the browser any JavaScript is run. It can't then "talk back" to the PHP that processed it. That would be like Harry Potter giving advice to J.K. Rowling on how best to progress the story.
The closest you can get to this kind of behaviour is with an AJAX call -- using JavaScript to determine the data to send to a different PHP script, potentially with return data which can then be processed by JavaScript. However, I don't believe that this is the sort of thing you're looking for.

Categories

Resources