URL in database to Javascript with PHP - javascript

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>

Related

Using results from php mysql query, looping it in javascript for ajax function

First time using javascript and ajax here
I have a php mysqli query of customer order id's that I'm trying to write a function for in javascript that loops thru each customer order # from the previously mentioned sql array and attaches the results to an ajax (statement?) that interacts with a page that edits shipping results to on our backend shipping interface and i'm having some troubles getting it to work the way I would like it to.
The code I have so, far along with the Mysql query looks something like this:
<?php
$sql = "SELECT id
FROM table
WHERE shipdate IS NULL;";
$query = mysqli_query($connection, $sql);
$result = mysqli_fetch_array($query);
?>
// Function prints all open order and marks them as: Pending
$('button#printOpenOrders').on('click', function(e) {
if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
e.preventDefault();
// prints all open orders
window.open("/resources/scripts/allOpenPDF.php");
var id = <?php json_encode($result); ?>
id.forEach(open_orders_func);
function open_orders_func(item) {
$.ajax({
url: "/resources/scripts/pending-order.php?id=" + item,
datatype : "string",
success : function(data) {
location.reload(true);
}
})
}
}
});
A little over my head but I feel like I'm on the right track, I'm just not getting the result I expected to get.

how to get json url with add variable url link

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.

Sql queries doesnt work when inside a php function

So the main problem is, when i make some query just after a post[] or whatever and its just in the main code of the php (not in a function) it works perfectly fine..
But, when i try and have that query inside a php function,it never works, and kinda hiding any other code on the rest of the page... I have a few divs after that php and sql query code, and they just dont show when i try to query through the function..
<script type="text/javascript">
function callPhpVoteAdd(name) {
var result = <?php voteAdd(name); ?>;
alert(result);
return false;
}
</script>
<?php
echo '</br>';
$allsql = "SELECT * FROM voting ORDER BY votes DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo '<form method="post">
name: "' .$name. '" - votes: "' .$votes. '" <input type="submit" name="'.$name.'" value="'.$name.'" onclick="callPhpVoteAdd(this.name)"/><br>
</form>';
}
}
function voteAdd($name) {
if($conn->query("UPDATE voting SET votes = votes + 1 WHERE name = '".$name."' ") === TRUE) {
echo "<script>alert('fuck yeah');</script>";
}
echo "shit";
}
So the button pressed calls the js function, which calls the php function
I guess you're misunderstanding the way JS and PHP works. PHP works server side, and JS, in your case, client side. And so, PHP generate the script/page before it's sent to the browser, so when JS runs it, all the <?php ?> are already replaced by static data.
So, to put it shortly and simply, you just can't call a PHP function from JS after your page is loaded, the way you tried to (because the call isn't there anymore - check your source code from your browser).
You need either to :
use a form with an "action" attribute ; this will send the data to server, and call the php script set in "action", where you can handle the sent data, and then reload the page with the new/updated data,
use ajax (almost the same thing : this sends data to server and call a php script to handle them, but instead of reloading the page, the output of the PHP script - with the data you need - will be sent back to JS, to a callback function, where you'll be able to use them to modify the page).

How to pass javaScript values to PHP

How to pass javaScript values to PHP, my code is following
<script>
function a{
var b = a;
}
</script>
<button onclick="a(2)">Values</button>
<?php
$select = mysql_query("select * from tabl1 where id='values'"); // values comes here
echo $select;
?>
There's a lot of thing you could do.
Principal things you have to know is that javaScript run on the client side (browser), while PHP is running on the server.
Then If you want to pass a variable from your JS to your PHP you have to make a server call.
There's various way you can use in order to send variable from client to server.
As I understand from your example, it looks like your php code and your javascript on the same file. so maybe call your file another time will be enough for you.
Let's say your file's name is index.php.
<script>
function yourJavascriptFunction(id) {
window.location.href = "index.php?id=" + id;
}
</script>
Then in change your PHP code to this:
<?php
$select = mysql_query("select * from tabl1 where id='".$_GET['id']."'"); // values comes here
echo $select;
?>
$_GET will get the variable you've sent in your Js function.
Doing like this will refresh the page.
May be you don't want to refresh the page? Then look at the ajax way.
I hope it helps you

PHP inside Javascript in a registration form (for validation)

I'm developing a registration form for my site. Actually when a visitor choose an username, a php query to my MySQL DB is used to control if it's already used and if so, a javascript windowd appear.
Can i use a PHP query inside Javascript for displaing a real-time notice near the form (using HTML5)?
<script>
var username = document.getElementById('username');
var userdb = <? php control_username($username); ?>
var checkUsername = function () {
if (userdb.value == true) {
username.setCustomValidity('Username already used');
} else {
username.setCustomValidity('');
}
};
username.addEventListener('change', checkUsername, false);
</script>
and here there's the php function:
<?php function control_username($username){
$db=connessione_db();
$query = "SELECT username FROM utente WHERE username = '$username';";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[0]==$username){
return TRUE;
}
else{
return FALSE;
}
$query=NULL;
}
how can i do?
You can use AJAX or jQuery AJAX to send a request to a php page, Check if the username exists, return the result, and display it using Javascript again.
Here is the jQuery sample:
<script>
$.ajax({
type: 'POST',
url : 'checkUsername.php',
data: {'username' : $('#username').html()},
cache : false,
success: function(data){
if(data == 'exists')
//username exists
alert('username already exists!');
},
error: function(request , status , error){
alert(request.resposeText);
}
});
</script>
and this should be your checkUsername.php file:
<?php
$db=connessione_db();
$query = "SELECT count(*) as count FROM utente WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[count] > 0)
echo 'exists';
else
echo '';
PHP is run on the server, Javascript is run on the client's machine. Once your PHP script has generated a page and sent it to the user, it doesn't run any longer. Your client has no knowledge of a PHP script. It can't directly run, call, or read anything about your PHP script because it resides solely on the server (never on the client's machine). Your client's machine does, however, know about your Javscript since it has been sent along with the page. If you want to access PHP functionality from your page, you can either send a GET/POST call to the server and reload the page, or use AJAX to make the call in the background. Check out Jquery's implementation of AJAX calls, it makes using it pretty simple.
No you can't do it like that. PHP is serverside, Javascript clientside. The moment Javascript is executed is the code working clientside. All PHP code is fixed.
Compare it to the combination of HTML and PHP in an HTML page. It is fixed there as well. Same applies to PHP in Javascript.
Here are some answers from related questions on stackoverflow:
How to put php inside javascript?
How to embed php in javascript?
Here is an example from ajaxref, showing the basics:
http://ajaxref.com/ch3/asyncsend.html
This is another tutorial showing how an ajax call is handled:
http://code.tutsplus.com/articles/how-to-make-ajax-requests-with-raw-javascript--net-4855
I advice you to first understand this process and later on start using a framework like jQuery.

Categories

Resources