Share config in php with javascript + ajax (json) in usage - javascript

I am trying to share a config.inc.php in php with javascript. It works, but not with ajax... there is always the "error-function" called. Is there any way to share the config file with an working ajax?
I am using it in an apache cordova project, with bootstrap and jQuery.
Here is a part of my index.html file:
<html>
<head>
<title></title>
<link rel="stylesheet" href="lib/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="lib/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="lib/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="config.inc.php"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
console.log(config_url);
jQuery.ajax({
url: config_url,
type: "POST",
dataType: "json",
data: "param=no",
success: function(html){
doSomething();
});
}, error: function(e){
alert(e); //always an alert :/
}
});
});
</script>
</head>
<body></body>
</html>
Here is my config.inc.php:
<?php
global $config;
$config["url"] = "http://192.168.1.Y/fetchdata.php";
$config["db"]["host"] = "localhost";
$config["db"]["database"] = "myDatabase";
$config["db"]["username"] = "root";
$config["db"]["password"] = "";
$config["db"]["port"] = null;
$config["db"]["socket"] = null;
?>
var config_url = <?php echo json_encode($config["url"]); ?>; //if i remove this line, ajax will work and call the "success part".
And finally the last file "fetchdata.php" for database connection:
<?php
// Allow access via php
header('Access-Control-Allow-Origin: *');
// Load configuration
require 'config.inc.php';
global $config;
$sqlconn = mysqli_connect($config["db"]["host"], $config["db"]["username"],
$config["db"]["password"], $config["db"]["database"], $config["db"]["port"],
$config["db"]["socket"]) or die(mysqli_error());
$dataquery = mysqli_query($sqlconn, "SELECT * FROM table_profil");
$arr = array();
while($row = mysqli_fetch_object($dataquery)) {
array_push($arr, array("key" => $row->key, "value" => $row->value));
}
print_r(json_encode($arr));
?>
I used XAMPP for testing. The output is
var config_url =
"http://192.168.1.Y/fetchdata.php";[{"key":"size","value":"150"},{"key":"color","value":"green"}]
Without the ''var [...] .php";'' output, it will work... But I liked to share the config.

you used javascript var in php without <script> tag? How come? use
<script>
var config_url = '<?php echo json_encode($config["url"]); ?>';
</script>
instead of
var config_url = <?php echo json_encode($config["url"]); ?>;
with that way you can pass config_url with javascript but your ajax will not work .. cause ajax not work through servers so you can't use "http://192.168.1.Y/fetchdata.php" in your ajax url .. in your ajax url just use url:'fetchdata.php', and check you link to its path

Thanks mohamed-yousef and Michael, I solved it with a part of your answers. You shown me the error and gave me hints for the solution :).
Ted wrotes the solution in Shared JSON data for php and Javascript/Ajax . I use a "GET"-Param for supporting javascript. Because my "fetchdata.php" won't have any javascript, I use it without the param => no javascript output if not needed.
My index.php includes the config with a "js" parameter; looks like ...
<script type="text/javascript" src="config.inc.php?js"></script>
... and my "config.inc.php" looks like
<?php
global $config;
$config["url"] = "http://192.168.1.Y/fetchdata.php";
....
if (isset($_GET["js"])) {
echo
'
var config = [];
config["url"] = "' . $config["url"] . '";
';
}
?>
No changes in "fetchdata.php".
This solution is working for me. Thanks everybody!

Related

JQuery , PHP and mySQL Help. I do not understand why this is not working

Rookie coder here trying to learn from mistakes. :)
I have three files (jquery.js, php.php and html.html).
I am trying to fetch information from mySQL database name trial1. It has only one table called Score_Sheet.
Below is the code for html.html
<!DOCTYPE html>
<html>
<head>
<script type="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src= "jquery.js" type = "text/javascript"></script>
</head>
<body>
<button id = "button"> Click to see value from SQL table</button>
<div id= "content"></div>
</body>
<html>
Below is the code for php.php
$link = mysqli_connect("localhost","root","","trial1");
$query = "SELECT * FROM Score_Sheet";
$show = mysqli_query($link, $query) or die ("Error");
echo "<table><tr><td>ID</td><td>UserID</td><td>Score</td></tr>";
while ($row = mysqli_fetch_array($show)){
echo "<tr><td>" . $row['ID'] . "</td><td>" . $row['UserID'] . "</td><td>" . $row['Score'] . "</td></tr>";
}
echo "</table>";
}
Below is the code for jquery.js
$(document).ready(function(){
$("#button").click(function(){
function show_all(){
$.ajax({
type = "POST",
url = "php.php",
success: function (data){
$("#content").html(data);
}
});
}
// show_all();
});
});
This
{
type = "POST",
url = "php.php"
//...
}
is not the way you should define object literals in JS. Try this:
{
type: "POST",
url: "php.php"
//...
}
By the way, browser's debugging console is the best friend of any coder, not only the rookie one ;)
Learned a good thing today. Thank you everyone. I had to use Developers tool to see what error was happening. Error was ReferenceError: $ is not defined. Then I googled the error and used this Inline Link forum to fix it.

Trying to refresh JavaScript variable that is assigned to a PHP variable

I have assigned two variables that are equal to a PHP variable that can change at any time. I am trying to update a div every 5 seconds; for example, to update the number. I am assuming this doesn't work because the PHP doesn't run again once the page has loaded. What is the best way to get around this? I don't mind linking to another page if necessary. Here's my code:
$(document).ready(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
setInterval(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, 5000);
});
Yeah - that won't work as you know.
setInterval(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, 5000);
That is a javascript + php. The browser runs javascript and php runs on the server. They run at different times and are mutually exclusive. The work apart from each other.
What you want to do (probably) if you are trying to update realtime is to use an ajax call.
http://api.jquery.com/jquery.ajax/
I find the api documentation good for reference but bad for example.
var jqXHR = $.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
}).done(function (data, status, jqXHR) {
$("#container").html(data);
alert("Promise success callback.");
}).fail(function (jqXHR,status,err) {
alert("Promise error callback.");
}).always(function () {
alert("Promise completion callback.");
})
That makes a pretty good example. Google "jqXHR" for other working examples
$(document).ready(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
setInterval(function() {
$.get('/get_prices.php', function( data ) {
buyprice = data.buy;
sellprice = data.sell;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, "json" );
}, 5000);
});
And in your backend (/get_prices.php in this example, change it!)
<?php
$buy = 1;
$sell = 1;
echo json_encode(array(
'buy' => $buy,
'sell' => $sell,
));
exit;
You can make a simple ajax get request to a seperate php file that returns the data as json:
setInterval(function() {
$.get('/prices.php', function(data){
$('#currentbuyprice').html(data.buyprice);
$('#currentsellprice').html(data.sellprice);
});
}, 5000);
prices.php:
//code that creates $cointTicker and $coin vars goes here
header('Content-Type: application/json');
echo json_encode(
[
'buyprice' => $coinTicker->price($coin2[1] , 'buy'),
'sellprice' => $coinTicker->price($coin2[1] , 'sell')
]
);
You can't update static PHP variables, because the PHP-script gets an request, works and answers to the client, so the session is closed. The are two ways to handle that.
Way 1:
You have to connect your PHP to an Database. So you will send a request to a PHP-file, which updates the numbers in the database, so the values will be safed, also for the next request.
Way2:
You can make PHP Sessions php.net link. So you will save your values temporary in a session. That session will deleted after a while, and maybe that is not that, what you need. sessions are similar to cookies.
Both ways work through an AJAX-Request. So you need an Javascript-Function, that will send your request to that PHP-file, which will update the Database or the Session. You should also have a function to get that values from the Database or the Session.
Using the same approach (making a polling) you can make an ajax query
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<meta charset="utf-8" />
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js" charset="UTF-8"></script>
</head>
<body>
<script>
function send(){
$.ajax({
url: "a.php/",
type: 'GET',
success: function(res) {
var myVars = JSON.parse(res);
console.log(myVars[0].buyprice);
$('#currentbuyprice').html(myVars[0].buyprice);
$('#currentsellprice').html(myVars[0].sellprice);
}
});
}
setInterval(function(){ send() }, 3000);
</script>
currentsellprice:
<div id="currentbuyprice">
</div>
currentsellprice:
<div id="currentsellprice">
</div>
</body>
here the minimal part of the server
<?php
$out = "[";
$out .= '{"buyprice":"'. time(). '",';
$out .= '"sellprice":"'. time()/2 . '"}';
$out .="]";
echo $out;
?>
You can find a lot of information related with this topics (ajax and json) in internet.

$.ajax post loads html code from current page instead of requested php

im new to javascript, but have to use it for an ajax load of a .php
This is my ajax.js
$(document).ready(function(){
var url = $(location).attr('href');
var uA = navigator.userAgent;
$.ajax({
type: "POST",
url: "neo4j.php",
data: {"url": url, "userAgent": uA}
});
alert(url);
});
It should post the datas to neo4j.php.
My Start.php looks like
<head><title>Start</title></head>
<?php
include("db.php");
$sql = "SELECT * FROM category_paths LIMIT 10";
$pattern = mysql_query($sql);
while($row = mysql_fetch_object($pattern)){
if ($row->descendant_id == 1) {
echo "<a href='http://localhost/2play/Start.php'>$row->descendant_id</a><br>";
}else {
echo "<a href='http://localhost/2play/Section.php/?sec=$row->descendant_id'>$row->descendant_id</a><br>";
}
}
?>
<footer><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script></footer>
Here my code works.
But if I click on a link to section.php
<head><title>Section</title></head>
<?php
include("db.php");
echo "<a href='http://localhost/2play/Start.php'>1</a><br>";
if(isset($_GET["sec"])) {
$sec = $_GET["sec"];
}
$sql = "SELECT * FROM category_paths WHERE ancestor_id = $sec AND length = 1";
$pattern = mysql_query($sql);
while($row = mysql_fetch_object($pattern)){
echo "<a href='http://localhost/2play/Game.php/?game=$row->descendant_id'>$row->descendant_id</a><br>";
}
?>
<div id="js">test</div>
<footer><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</footer>
My ajax.js dont load the js code, instead it load the html-code of the current page. Copy from loaded section.php with firebug:
<html>
<head>
<title>Section</title>
</head>
<body>
1
<br>
123
<br>
124
<br>
125
<br>
156
<br>
197
<br>
<footer>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="ajax.js" type="text/javascript">
<--Here the script should be loaded, but it relaods the raw non-php code from section.php-->
<head><title>Section</title></head>
<a href='http://localhost/2play/Start.php'>1</a><br>
<footer><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</footer>
<--End-->
</script>
</footer>
</body>
</html>
What I already found out:
If I manually add some get-vars to the Start.php url like
http://localhost/Start.php?foo=bar
the script wont work and do some failure as above.
SOLVED
Ok I found my mistake, and cant believe it.
It is because i had an slash in the link before I set the get-vars http://localhost/2play/Section.php**/**?sec=$row->descendant_id'> . After deleting it, the problem disappeared.
You should nod declare variable inside $.ajax. Try something like this
$(document).ready(function(){
var data1 = "foo",
data2 = "bar";
$.ajax({
type: "POST",
url: "foobar.php",
data: {"data1": data1, "data2": data2}
});
alert(data1);
});
More about AJAX can follow the link
Ok I found my mistake, and cant believe it. It is because i had a slash in the link before I set the get-vars
http://localhost/2play/Section.php**/**?sec=$row->descendant_id'>
After deleting it, the problems disappeared.

AJAX cannot print elements onclick

I have got 2 files, one named index.php and one named api.php. I am trying to retrieve some data from my DB and I've done this simple example before trying to put the code into my project. In the api.php file I ve got the following:
$connessione=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
$scelta_db=mysql_select_db(DB_NAME) or die(mysql_error());
$idM=67;
$result = mysql_query("SELECT * FROM map_comment WHERE idMap ='$idM'");
$array = array();
while ( $row = mysql_fetch_row($result) )
{
$array[] = $row;
}
echo json_encode($array);
While in the index.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<h3>Output: </h3>
<div id="output">Attacco qua sotto</div>
<button onclick ='show_comments'>Carica commenti </button>
<script id="source" language="javascript" type="text/javascript">
function show_comments()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var idU = row[1];
var text_map = row[3];
$('#output').append("<b> idU: </b>"+idU+"<b>text </b>"+text_map)
.append("<hr />");
}
}
});
};
</script>
</body>
</html>
The problem is that it does not seems to "append" nothing and I dunno what I am doing wrong. I KNOW I should use mysqli, I'll fix that. Plus: HOW can I "send" a $idM to the api.php from the index.php (for example an $id already defined in the index.php)?
Your function is not called when you click the button, in an onclick attribute you're not setting a function but rather writing code to execute. See example below
<button onclick ='show_comments()'>...
To send the id, you can use the data parameter
data: {id: 67},
Since this is a GET request you can use the php super global $_GET to retrieve the value $_GET['id'].

How do I pass a variable from one php file to a javascript file?

I am currently trying to make a site where I put in info in on my html side, it send the info to the php file and grabs info from another site depending on what you put in on the html side.
To make this more clear this is how it works:
You put in your username in the html site(where the javascript code
is).
Then it sends your username to the php file.
The php file gets the information, puts it in a link and request it.
It grabs information from this request (highscores page).
This is where it stops.
I don't know how to return the information to my javascript file.
This is my code:
html/javascript page:
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<script>
function test() {
var username = "Exzib";
window.location.href = "grabinfo.php?username=" + username;
}
</script>
</body>
</html>
This is my php file: (grabinfo.php)
<html>
<head>
</head>
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
echo $formatxp;
}
?>
<body>
</body>
</html>
So how do I proceed to send the $formatxp to my javascript?
Thanks
So what you do is execute:
window.location.href = "grabinfo.php?username=" + username;
This causes the browser to navigate to grabinfo.php and display the information that you want. Except that you don't want the information to be displayed, you want to retrieve it into a JavaScript variable, right?
To do so, don't set window.location.href. Instead call your script using AJAX. You'll find plenty of tutorials on AJAX out there. This will allow you to capture the output of your PHP script.
Change the following line
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
to
$formatxp = str_replace(array('$',',','.',' '),'',$xp);
And to pass the variable to Javascript you can do something like this.
<script type="text/javascript">
var $formatxp = '<?php echo $formatxp; ?>';
</script>
Write a script tag and set the variable equal to your PHP variable.
<script>
var thing = '<? echo $formatxp; ?>';
</script>
This is going to be easy as you already include jQuery. (Using ajax)
Look
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<label>Type your username:<input id="username" type="text"></label>
<input id="submit-button" type="button" value="Get my highscores!">
<p id="response"></p>
<script>
//When user clicks "submit-button" button
$("#submit-button").on('click', function() {
var username = $("#username").val();
//We request our php with the username
$.get("grabinfo.php?username=" + username, function(xpValue) {
//When we receive the response from php then we add it to a "p" tag
$("#response").text("LOL your xp is: "+xpValue+". NOOOOOOOB!!");
});
});
</script>
</body>
</html>
And that's it!
More info at http://api.jquery.com/on/
And http://api.jquery.com/get/
http://api.jquery.com/text/
http://api.jquery.com/val
And well the whole jQuery API documentation http://api.jquery.com
EDIT:
OH. You have to change grabinfo.php. It should only have this:
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
if(empty($formatxp)) {
echo "ERROR: Invalid could not find xp with username {$username}";
}
else {
echo $formatxp;
}
}
else {
echo "ERROR: Invalid arguments";
}

Categories