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.
Related
Let's say I want to create a web page where users can inputs information and the page will see if that information exists in a file and then displays it to the user. This information could be an email address or a password or anything. Can this be done just with Javascript?
The front-end side can be JavaScript AJAX requesting system which will contact the server and server will process the request and give the answer to the AJAX request and display the results in real time to the user.(just as search engines do)
Only using JavaScript would be hard,as the server side requires to do a search through the given text.
The server side can use some basic string searching.
/HTML and jQuery/
<input type="text" id="txtInputStr"/>
<button type="button" id="btnFind"/>
<script>
$("#btnFind").on("click",function(){
var postData = [];
postData.push({name:'inputstr',value:$("#txtInputStr").val()});
$.ajax({
type:'post',
url:'findMe.php',
data:postData,
success:function(json)
{
var obj = $.parseJSON(JSON.stringify(json));
console.log(obj.success);
}
})
});
</script>
/php findMe.php/
<?php
$contents = file_get_contents($_SERVER['DOCUMENT_ROOT'] . $your_file_name);
$res = array("success"=>false;);
if(strpos($contents,$_POST['inputstr']) !== false)
{
$res['success'] = true;
}
echo json_encode($res);
where your_file_name is your file name where you want to search.
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).
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.
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>
I have encountered a huge error for an idea I came up with. So I am working on a project, on my main website and we needed to put up a being worked on page, yadayda but I wanted to add the functionality of letting the user send us their email , but after we received that data a pop dialog would show.. But this doesn't work as I would like for it to.
So what I need help with, is actually the PHP and the JavaScript event to make it acknowledge that the message and email was sent, then show the dialog box. Does anyone know how to do this? Or maybe at least how to make a dialog show after a user did something, like entered information rather then just clicking a button? If anyone can help I would ridiculously appreciate it!
If you use jQuery, you can make an AJAX call to your serverside script and use the success callback to initiate the dialog on the client side.
$.ajax({
url: 'ajax/test.php',
data: { name: "WeLikeThePandaz", email: "panda#gmail.com" },
success: function(response) {
if (response.status == "OK"){
// Show dialog
}else{
// Let the user know there were errors
alert(response.error);
}
}
},'json');
Here is the relevant documentation for using the $.ajax method -
http://api.jquery.com/jQuery.ajax/
Your server side PHP code in ajax/test.php can then decipher the data that was sent and assemble a json object to be returned to the jQuery -
<?php
$err= '';
$name = sanitizeString($_POST['name']);
$email = sanitizeString($_POST['email']);
// note the sanitization of the strings before we insert them - always make sure
// to sanitize your data before insertion into your database.
// Insert data into database.
$result = mysql_query('INSERT INTO `user_table` VALUES...');
if (!$result) {
$status = "FAIL";
$err = mysql_error();
}else{
$status = "OK";
}
echo json_encode(array('error'=>$err,'status'=>$status)); // send the response
exit();
?>