Returning information from PHP to javascript - javascript

I have a javascript bootkmarklet that the user can load into what ever webpage they are on.
This then displays a php generated page over the top of the current webpage, this includes some information that the javascript has take from the page the user is on.
What I now need is to be able to have the javascript first run one php file that connects with a mysql database, have the result from the database returned to the javascript which can then call the php file that generates the page overlay.
What I am looking for really is a way for the process to go:
User runs javascript --> javascript runs php for mysql --> javascript gets mysql result back --> javascript runs second php file

Here is a starting point of how to use the ajax features in JQuery.
Edit - separate javascript file
html file:
<html>
<head><title> Ajax test page</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="ajaxfunctions.js"></script>
</head>
<body>
<div id="ajaxResult"></div>
</body>
</html>
js file called 'ajaxfunctions.js':
$(document).ready(function() {
$("#ajaxResult").load("ajaxHello.php");
});
php file called 'ajaxHello.php':
<?php
header("text/html");
echo "hello from php";
?>
To read data from a database the php code needs to be a little longer:
<?php
header("text/html");
$username = "root";
$password = "";
$databaseName = "mydatabase";
$connect = mysql_connect("localhost",$username,$password);
if (!$connect) die("Connection Error");
$result = mysql_select_db("$databaseName");
if(!$result) die("Select DB Error");
$result = mysql_query("select email from users where firstname='Abbey'");
if (!$result) die('Invalid query: ' . mysql_error());
$row = mysql_fetch_assoc($result);
echo "Abbeys email address ".$row['email'];
?>
This examples looks up Abbeys email address from the users table in the users database and returns it. The Database name, username and password are all set at the top of the script.
Usually the ajax request passes some data from the html page, I am happy to add this code if this helps.
Is this something like what you are looking for?

Related

Javascript and PHP to fill WordPress form element

I am using WordPress and want to take the email from a registered user's account to auto-fill a form.
I'm using two plugins: Snippets for the PHP code and Scripts n Styles for the JavaScript.
The PHP code is
<?php global $current_user; wp_get_current_user();
$user_email = $current_user->user_email;
?>
<script type="text/javascript">
var useremail = <?php echo json_encode($user_email) ?> ;
</script>
and the Javascript is
<script type="text/javascript">
window.onload = function ()
document.getElementsByName("element_name")[0].value = useremail;
}
</script>
However nothing is being filled into the element.
Does anyone have any experience using PHP and JavaScript to auto-populate a form element?
I believe the issue is with the PHP code since I can insert a value into the form using the JavaScript if I put the value I want in quotes.
First line in your php should be:
<?php $current_user = wp_get_current_user();
and:
<?php echo $user_email ; ?>
In js, you're missing an open brace {
window.onload = function () {

Pushing updates to a webpage using server-sent events

I would like to post data to my PHP page and then have it update the HTML page. I followed this example of using server-sent events to push updates to a webpage.
Here is what I have right now:
output.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="serverData"></div>
</body>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
}
else {
document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>
</html>
send_sse.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$val = 0;
if (isset($_POST['msg'])){
$val = $_POST['msg'];
}
echo "data: $val\n\n";
ob_flush();
?>
form.html:
<html>
<body>
<form action="send_sse.php" method="post">
Message: <input type="text" name="msg"><br>
<input type="submit">
</form>
</body>
</html>
The problem is that when the form posts the value, it does not update the output.html. It does output "0" and will update whenever I manually change the value of $val and save the file. However, I want the value of $val to be determined outside of the PHP file. What am I doing wrong?
The issue you are having here is that you have missed how SSE conceptually work. Your output.html page is making a GET request to your web server and executing the script send_sse.php and opening up a connection and HOLDING that connection open and waiting for updates.
When you are posting from form.html you are sending a POST request to your web server and executing the script send_sse.php on a completely different thread.
As you have not implemented any shared persistence between these two threads it will make no difference.
So to do what you want to do you will need to have code in send_sse.php that has some form of global persistence (e.g. database) and can detect new data and then flush that down to the browser.
I am not a PHP expert, but I have written an example in Node JS that uses REDIS pub/sub to provide said persistence.
I hope that helps.

How to convert and transmit PHP Variable data Using JSON to HTML page's Javascript

I can't seem to figure it out how to convert the following PHP variable to HTML:
$persondata = "<div id='teach'><h3>Name: " . $row["fname"]. "<br>User Name: " . $row["username"]. "</h3><p>Password: " . $row["upass"]. "</p></div><br>";
I wanted to pass that exact data to my HTML page, so that I can use JavaScript's getElementById function to insert it into a selected data field.
I asked a similar question here, which helped me work out some of logic I need, but I can't work out this part of the equation.
If you could please let me know of a simple way of going about this, it would be very much appreciated, as I don't even know the keywords to search for.
Hope below code help you:
<?php
$persondata = '';
foreach($rows as $row){
$persondata .= "<div class='teach'><h3>Name: " . $row["fname"]. "<br>User Name: " . $row["username"]. "</h3><p>Password: " . $row["upass"]. "</p></div><br>";
}
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#data-row').html("<?php echo $persondata ?>");
});
</script>
</head>
<div id="data-row"></div>
A javaScriptVar equals with an echo in php of your php variable.
That is to put php inside js
<script type="text/javascript">
//Your JS
var jsvar = <?php echo $persondata; ?>
//Your JS
</script>
Put PHP var like above into js.
Continuing from above answer:
That is to put php inside js
<script type="text/javascript">
//Your JS
var jsvar = <?php echo $persondata; ?>;
//Your JS
</script>
Put PHP var like above into js.
If you want to transmit data from a PHP script in a server to a client side HTML page for using in js. Go like following.
First get all your data in PHP in an array and use json_encode() and after that echo that variable.
Now in the client side HTML use jQuery.ajax() and send request to that PHP file in server.
When you have the response in Json use js to fragment it and append
wherever you want.
Above is the basic procedure to send data from PHP to HTML page using JS.

PHP javascript class variable value in php echo

this is simple example i want java script class variable to php echo please fix the following example to php echo value out put
<!DOCTYPE html>
<html>
<body>
<div class="example">The Book</div>
<? echo '<div class="example">The Book</div>'; ?>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>
out put of java-script "The book" but php echo is '<div class="example">The Book</div>' Targeted out put of php The book
Javascript is run on the client, PHP is run on the server. If you want PHP to use the values calculated in javscript you first have to send it to the server, either through something like AJAX, or perhaps just a query string if you don't mind loading a new page or loading the same page again but with a query string appended to the URL.

Retain in the same page and do JS operations

My file structure
front-page
homepage.html
lib
.js
.php
I send the user information to server and doing server side validation. If server side validation fails, i want to load my html page and open log in window if email already exists. I have done the following
if(isset($_POST['submit']) && $_POST['email']!='')
{
$email= $_POST['email'];
$sql1 = "SELECT * FROM Users WHERE emailID = '$email'";
$result1 = mysqli_query($connection,$sql1) or die("Oops");
if (mysqli_num_rows($result1) > 0)
{
//echo "This Email is already used.";
//Write code to go back to register window
//header('Location: ../homepage.html');
echo '<script type="text/javascript">
console.log("cdsafcds");
//jQuery.noConflict();
$(".login_links_login").trigger("click");
</script>';
}
}
I don't see any errors and it isnot triggering the click too. I don't have any restrications. Please provide me the best way to do these kinda stuff. I checked with few sites they loads the separate page if php call fails. But i want to know why can't we do it in the same page if so.
HTML:
<!----head>
<script type="text/javascript" src="lib/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="lib/jquery-validate.min.js"></script>
<script type="text/javascript" src="lib/homepage.js"> </script>
<link rel="stylesheet" type="text/css" href="lib/homepage.css" />
</head!--------->
<form method="POST" action="lib/login_validate.php" class="loginDiv right" id="loginForm">
content goes here
</form>
Submit click: is handled by jquery
Please let me now if any data further needed

Categories