JS script that reacts to PHP script - javascript

I have such a request: I have to do JS script, that works with PHP script.
Right now i have such a PHP code:
~~~~~~ PHP ~~~~~~
<?php
$email = filter_input(INPUT_POST, 'email');
if (!empty($email)){
$host = "localhost";
$dbusername ="root";
$dbpassword ="";
$dbname = "email";
$conn = new mysqli ($host,$dbusername, $dbpassword , $dbname);
if (mysqli_connect_error()){
die('Connection problem('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else{
$sql = "INSERT INTO `email` (`email_id`, `email`) VALUES (NULL, '$email');";
if ($conn->query($sql)){
echo "<script type='text/javascript'>alert(\"Email has been written to subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
else{
echo "<script type='text/javascript'>alert(\"Your email is already in our subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
$conn->close();
}}else{
echo "<script type='text/javascript'>alert(\"Don't forget to include your email address !\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
?>
And here is a challenge. Instead of currently js scripts in php (that they activate on clean page without any content) JS script has to work on page, without reload - on the same page, when the request was sent from. I don't know how to do that ( i'm quite new to JS ) and i hope for your hints
Thanks for advices

If you don't want to reload the rendered page, you will have to work the other way around: not PHP is generating the whole page, but a JS script is pulling information from a PHP script and uses this information to display the according note.
There are multiple ways to fetch information from a server using JavaScript, the most prominent being AJAX to load HTML chunks or JSON responses. Please search for those topics as this is a relatively broad topic and your question is much too broad as it is.

Related

how to display form content after php processing

Im creating a forum for a little project of mine.
So far I have been able to get the form contents and use php to process (YES I HAVE NOT ACCOUNTED FOR SQL INJECTION).
Anyway, the php code is as follows:
test.php
<?php
if (isset($_POST["add"])){
// "Save Changes" clicked
$title = $_POST['title'];
$message = $_POST['message'];
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$dt = date('Y-m-d h:i:s');
$sql = "INSERT INTO threads (title,author,date_posted,post) VALUES ('$title', 2, '$dt', '$message')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
header('Location: http://127.0.0.1:5500/RuneScape_website/RS.com/aff/runescape/forums/ForumThread/~tm10CE.html');
}
?>
Now what I really want to do, is after this data has been saved to the database, I want to display the newly created blog comment to the direct page on load up. For example, When you click submit, the comment should appear in the directed html page.
The only way I think about it, is that I need either javascript to create a new attribute and append it to the list of existing attributes (e.g. ), or in the php create the div and use javascript/JQuery to access the php file and collect the html.
So I want the $title and $message to be used in the html page where its directed to.
A real example is like stack overflow. After I write an answer the page appends my response. This is what I want to achieve.
I'm curious how to go about this. Thanks :)
Don't you need to know which forum page this submitted comment belongs to?
If you add a column to threads table and store the name of the forum page in it (in this case: ~tm10CE.html), then from your html page, you can make an ajax call to a php file and include the name of the page as a querystring value. Inside the php file, query the threads table for the name of the page and return all the entries related to that page.

PHP login algorithm not redirecting to next page (unsure on connection to database)

I am setting up a login page to take a users username and password then check that against a local database, however nothing is echoing form the database connection and there is no redirecting to the next page 'welcome.php' happening.
I have already tried many different ways of connecting to the local database and redirecting to different pages with different methods, none of which gave any error message or worked. using XAMPP Apache and mySQL modules to provide the local server.
<?php
if (isset($_POST['Login']))
{
$link = mysql_connect('localhost','root','password','budget');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
session_start();
$username= $_POST['username'];
$password= sha1($_POST['password']);
$_SESSION['login_user']=$username;
$query = mysql_query("SELECT accounts.username, passwords.password_hash
FROM accounts
INNER JOIN passwords ON accounts.account_id = passwords.account_id
WHERE accounts.username = '$username' AND password_hash = '$password';");
if (mysql_num_rows($query) != 0){
?>
<script type="text/javascript">window.location.replace(welcome.php);
</script>;
<?php
mysql_close($link);
}
}
?>
I expect it to redirect to 'welcome.php' but instead it just refreshes the same page and nothing is echoed or given as an error
What isn't working?
Your JavaScript location.replace method needs a string as an input, you're not giving it that (as the input value is not quoted). It would be window.location.replace('welcome.php'); instead.
How to solve it?
The better solution is to redirect in PHP instead of in JavaScript, using header().
Additional remarks
I took the liberty of converting your code to use mysqli_ instead of the old, outdated and deprecated mysqli_ library. With this, you can use a prepared statement, as I have shown below. Use this approach for all your queries, bind the parameters through placeholders.
session_start();
if (isset($_POST['Login'])) {
$link = mysqli_connect('localhost','root','password','budget');
if ($link->connection_errno) {
die('Could not connect: ' . $con->error);
}
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $link->prepare("SELECT a.username, p.password_hash
FROM accounts a
INNER JOIN passwords p
ON a.account_id = a.account_id
WHERE a.username = ?
AND p.password_hash = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->bind_result($resultUsername, $resultPassword);
$stmt->execute();
if ($stmt->num_rows) {
$_SESSION['login_user'] = $username;
header("Location: welcome.php");
}
$stmt->close();
}
What's next?
Fix your passwords. Using sha1() is highly insecure for passwords, look into using passwords_hash()/password_verify() instead.
You need to add single quote around welcome.php
As welcome.php is neither a JavaScript keyword like this nor a number, single quote is mandatory also it is not a variable/object.
JS considers welcome as object and php as its method in welcome.php
Without it, a JavaScript error will be displayed:
ReferenceError: welcome is not defined
<script type="text/javascript">window.location.replace(welcome.php);
</script>
Also, there is no need of semi-colon ;.
JavaScript redirect without any condition.

How to add refferer url in script's src link

Our client have below link added in their site (given by us) which call our test.php file to use it as library and we return some script as well as we store some data.
Script tag is as per below on client's side,
<script src='https://example.com/test.php?id=194&referer='WHAT SHOULD I Write Here'></script>
test.php is as per below on our server,
<?php
$id = $_GET['id'];
$clientsrefferer = $_GET['referer'];
$ip = $_SERVER['REMOTE_ADDR'];
//below referer becomes address of client's webpage visited by their customer
$visitedwebpage = $_SERVER['HTTP_REFERER'];
try{
$dbh = new PDO("mysql:host=XXXXXX;dbname=XXXXXX", "XXXXXX", 'XXXXX');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query = "insert into table (ID,IP,Referer,Page) values(?, ?, ?, ?)";
$sth = $dbh->prepare($query);
$sth->execute(array($id, $ip, $clientsrefferer, $visitedwebpage));
echo "document.write('Returning some script')";
}
catch(PDOException $e) {echo $e->getMessage();}
?>
We want to check if client's website is searched and visited using any search engine referer. To get it from javascript,
document.referrer
can be use.
But I want to attach document.refferer value to the tag only which we gave it to our client. Is it possible?
Is there any other way to do that?
If question is not clear, let me know so I can try to do more clarifications.
You can retrieve the referrer detail and dynamically add the script tag on client side. Like below
<script type='text/javascript'>
var my_script = document.createElement('script');
my_script.setAttribute('src','https://example.com/test.php?id=194&referer=' + document.referrer);
document.head.appendChild(my_script);
</script>

how to create a dynamic redirect link with js and php?

PHP has no relation and behavior with browsers and in some times it makes some mistake. For example we can't set for header function to redirect to a page in a blank page. Because it has no relation with the browsers and for doing this, we should use JS .Now I'm mixing these two languages to reaching the goal.
<?php
$word = $_POST["tagTxt"];
$tag = "https://www.example.com/" . $word;
echo '<script>window.open("Location: <?php $search;?>");</script>';
?>
The goal is this code but it doesn't work. I want get a string from a first page then post it with post method and then past it to a static address for redirecting with blank target. Thanks.
I think you are trying to open a new url when the page is loaded.
So if you trying to do this check the code below.
This way you are mixing the parameters received from client, processing them and them sending back to the client.
Then you use the javascript with the window.onload function to execute the redirect page when the page is loaded with the received parameter.
<?php
$word = "1";
$tag = "www.yahoo.com/" . $word;
echo '<script text="text/javascript">window.onload = function(){window.open("'.$tag.'");} </script>';
?>
Not sure I fully understood your question, but have you tried something like this:
<?php header("Location: $search");
If you are "changing" the web page. Do not use window.open
Use window.location = 'http://www.google.com/';
in your example do this
<?php
$word = $_POST["tagTxt"];
$tag = "https://www.example.com/" . $word;
echo "<script>window.location = '$tag';</script>";
?>
(copy the code above, and it should work perfectly for what you're asking for)
I fount the way.
thanks all.
<?php
$word = $_POST["tagTxt"];
$tag = "https://www.example.com/" . $word;
echo "<script>window.open( '$tag' );</script>";
?>

use json and javascript to populate a table

I'm using php to fetch a db query that I want to make a table from. I want to put the query results into a json object and then use javascript from there to output the results into a table. I used json_encode to create the json object in php.
I'm fairly new to javascript so I'm a little confused as to how I can send the json object I've created to javascript and then output the results using javascript? Should I include the javascript in the same file as the php page or a different one?
If you can explain what you're doing that would be awesome because I really want to know what's going on at each step.
Here's what I have so far:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT Name,
Location,
ID,
Price
From ProdTable
where ID>=2000";
$encode=array();
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
?>
Update:
So I went ahead and made xyz.php my backend page and made a main.php for displaying the results. I started off with this sample function to make sure my jquery was fetching the results from the xyz.php page. Now, I don't know how to display the results in a table using jquery.
Here's what I did for my main.php page:
<?php
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("xyz.php");
});
});
</script>
<div id="div1"></div>
<button>Show JSON Results</button>
What you can do is:
Make the PHP file as backend. So that,
xyz.php:
// PUT YOUR CODE HERE
$sql = "SELECT Name,
Location,
ID,
Price
From ProdTable
where ID>=2000";
$encode=array();
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
?>
AND it should be accessible from the URL.
For example: xyz.php?id=2000
Now, on the page from where you want to populate this data, use jQuery
$.post
And manipulate this json.
This will ensure your page loads faster as dynamic data is getting populated after initial page load.
Hope it works for you.

Categories