how to get json url with add variable url link - javascript

how do I get the JSON URL with variable for the parameter, please help me, I'm new to learning programming
$(document).ready(function() {
var username=$("#nama_member1").val();
var url = "http://localhost/gps/json.php?username=";
$.getJSON(url+username, function(result) {}

Your code looks almost good. The question is if you have a folder on your localhost which provides a file called json.php and your localhost is a running Server with PHP. If so your json.php could look like:
<?php
// json.php
// Check if Parameter exists
if (isset($_GET['username'])) {
// Query to Database
$json = $result['from']['database'];
}
// return Json
echo json_encode($json);
?>
or much more easier
<?php
// json.php
// check param and return it
if (isset($_GET['username']) {
$json['username'] = $_GET['username'];
} else {
$json = 'Param Username not found';
}
// return Json
echo json_encode($json);
?>
You can put this file in your folder gps and would call it like you did already.
http://localhost/gps/json.php?username=
Not sure if this answers your question fully. If not, provide more info on the expected result or describe it in more detail.

Related

Echo php content into API javascript?

I would need to echo php variables (from the server and related to service behaviour) into javascript. For example, "ssl" => "true" and adapt accordingly in javascript. The thing is I'm doing this for some API files I'm writing and I want the client to have direct access to these files (<script src="... .js">) and this forces me to hardcode info that might change in the future across multiple file references. What I'd like to do was something like this, is it possible? (the content to fetch must remain completely private - from the server folders to the php script files - and so it is really not an option to fetch this info using javascript):
api.js
<? //PHP here. (I know...)
(...)
?>
//some javascript
var is_secure = <? echo "true"/"false" ?>
(...)
So that when doing <script src="api.js"/> the user only fetches:
var is_secure = "true";
(...)
or
var is_secure = "false";
(...)
Any idea on how I could do something similar? Thank you very much...
You could just create your PHP file with this line before everything :
header("Content-Type: application/javascript");
EDIT:
I did misunderstood the question. If you want js in an php file, you should do it like this:
header("Content-Type: application/javascript");
OLD ANSWER:
I don't know if you know, but client can't see your php code...
So if You'd:
echo "Something"
The client would only see Something.
It's not clear, what you're trying to do...
If you don't want to see Something when you go directly into your "secret" php page, then you should do it like this:
JS:
jQuery.ajax({
type: "POST",
url: 'secretfile.php',
dataType: 'html',
data: {apiRequest: 1},
success: function (response) {
yourVar = response;
}
});
PHP:
If ($_POST['apiRequest']==1){
echo "Something";
}
yourVar would be = "Something"
If you'd go to this page, it wouldn't display anything;

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine.
I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.
Here is the PHP code to get the information from the database:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('website.db');
}
}
$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>
Here is the JavaScript where the AJAX is located:
<script type="text/javascript">
function getNews()
{
console.log("firstStep");
$(document).ready(function()
{
console.log("secondStep");
$.getJSON("http://localhost/getNews.php",function(result){
console.log("thirdStep");
$('news').append(result); // display result
});
});
}
I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.
This is the HTML it should be appending to:
<div id = "newsEntry"> <news> test </news> </div>
Any help would be appreciated.
To find out what's going on, you might want to add an error handler:
$(document).ready(function() {
$.ajax({
url: "http://localhost/getNews.php",
dataType: "json",
success: function(result) {
console.log("thirdStep");
},
error: function(err) {
alert(err);
}
});
})
By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.
Include this line before your echo:
header('Content-Type: application/json; charset=utf-8');
Edit
On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:
$array = $result->fetchArray(SQLITE3_ASSOC); // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

How to read a session variable from a php file in JavaScript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
There have been far too many questions on this subject but I still fail to understand.
Case:
Hyperlinked image
OnClick of image: Check if session exists
If session exist, open link
If session does not exist, show login form
onclick is calling a JavaScript function:
var my_global_link = '';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
// .. then show login modal that uses 'js/whitepaper-login.js'
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
Global variable is being saved in another php file as :
$_SESSION['logged_in'] = 1;
I am unable to capture the session value in the var check. Can you advise?
Using jQuery here is a simple example of how to get a PHP $_SESSION into your JavaScript:
session.php
<?php
session_start();
$_SESSION['foo'] = 'foo';
echo $_SESSION['foo']; // this will be echoed when the AJAX request comes in
?>
get_session.html (assumes jQuery has been included)
<script>
$(function() {
$('a').click(function(event){ // use instead of onclick()
event.preventDefault(); // prevents the default click action
// we don't need complex AJAX because we're just getting some data
$.get('session.php', function(sessionData) {
console.log( sessionData ); // session data will be 'foo'
});
});
});
</script>
click
If this is successful you'll see the data and can use it in other JavaScript functions by passing the data appropriately. I often find it handy to json_encode() session data, returning JSON to be used by JavaScript, but there is no need to in a simple example such as this one.
Make the request to someone file.php
$( document ).ready(function(){//run when DOM is loaded
$.post("file.php", //make request method POST to file.php
function(data){ //callback of request is data
var arr = jQuery.parseJSON(data); //make json decoding
if(arr.logged == 1) //arr.logged is value needs
#do
})
})
file.php
<?php
session_start(); //start session for my dear friend Jay Blanchard
$_SESSION['logged_id'] = 1; //init value for example
$array = array('logged' => $_SESSION['logged_id']);//creat array for encoding
echo json_encode($array); //make json encoding for call back
?>
your javascript is not a very good solution, as it can be hacked easily. One can simply change the value of check to whatever one likes, and even without a login one would be able to access the link of the picture.
A better implementation would probably be something like:
<img src="img.png" alt="" />
checklogin.php would then verify the $_SESSION variable. If validated, you can use header("Location: something.html"); to redirect to where you want to bring the user. If not logged in, you can instead redirect to the login page: header("Location: login.php");
#Sarah
You have to first call the php file via ajax and set the javascript variable as the result. Since the javascript is a client side scripting language hence it can't read server side PHP script.
Hence on click call javascript function
function someFunc(){
//Fire Ajax request
//Set check variable
//and perform the function you want to ...
}
<?php include "sess.php"; ?>
<script type="text/javascript">
var my_global_link = 'testr.com';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
</script>
<a href="#" onclick="show_login('test')" >test</a>
file1.php
<?php
session_start();
$_SESSION["logged_in"] = 1;
?>
sess.php
I have done this using two files. You may have not included session file I guess. Its working fine for me.

URL in database to Javascript with PHP

I've added a table in my mySQL database which has two variables: ID and a URL.
ID has the value 1
and
URL has http://www.examplesite.com
I want to get "www examplesite com" from the database into a PHP file.
The PHP file should then send this string to a javascript file which will then open that URL.
So far I've been using getJSON with little success.
I'm new to PHP and Java and would really appreciate some help!
I want something like this in my .js file
$.getJSON('getlink.php', {'link'}, function(e) {
alert('Result from PHP: ' + e.result);
});
window.open(linkVariable'_blank')
I would like linkVariable to be www examplesite com
The javascript is linked to another php file which has a clickable element for the window.open.
How can I get the getlink.php and the .js file to communicate with each other?
EDIT:
My getlink.php would look something like this without any echo. The connection to mySQL is already written.
function get_links($url_link) {
$sql = "SELECT `name` FROM `variables` WHERE ID=?";
$res = $this->db->query($sql, array($url_link))->row_array();
return $res['URL'];
it would be better if you posted what code is in getlink.php.
I'd suggest you proceed like this. In getlink.php query the database to return the correct row.
There is different ways to do that, depending on what framework or library (PDO,mysql_,) you are using.
Then return the result as json
In the same file, call the function you just defined.
It should look to something like this
<?php
function get_links($url_link) {
$sql = "SELECT `name` FROM `variables` WHERE ID=?";
$res = $this->db->query($sql, array($url_link))->row_array();
return $res;
}
$result = get_links(1); //whatever the id is
return json_encode($result);
?>
In your javascrit you can do something like this
$.get(
"getlink.php",
function(data) {
alert(data.URL);
}
);
//My Idea
Read URL from the database and give it to the variable $link code below
$result=mysqli_query($dbconnection, "SELECT * FROM url"); //You can specify conditions
while($row=mysqli_fetch_array($result)){
$link=$row["URL"]; //We have our url from database here
}
//Link between JAVASCRIPT AND PHP
Put this code in a php to take $link and give it to getlink() function as a parameter
<script>
getlink("<?php echo $link?>"); //A java script function from your JS file to get url
</script>

How can i parse php variable to my javascript function result?

I have a script, i have to parse javascript variable to PHP file, i've no problem with this function, in my console i can see that the username variable is sent, it's fine .
$.post("user_add-js.php", { username: username })
.done(function(data) {
alert("Data Loaded: " + data);
});
In my user_add-js.php file , i wrote the variable $data with a value but i can't return the value "test", the variable is empty . I guess i forgot to add something in my PHP code to parse the value from PHP to javascript .
<?php
$data = "test";
?>
you need to set the header
header('Content-type: application/json');
and also you have to encode the variable to json like this
echo json.encode($data);
once you get the result to javascript you should parse the json code
data = JSON.parse(data);
This solution helps you get you data from PHP in any format ( object, array, string ... )

Categories

Resources