Changing a web page using JavaScript or PHP - javascript

I'm a college business student trying to build a website with a business model.
I'm building a website where I want to allow users to signup. Right now I'm using action: signup.php to store the user into the database. After the user is successfully inserted, I redirect the page back to the index.html where the form was submitted.
My question is, how can I reference JavaScript to change the login from display:block to display:none and sign up confirmation from display:none to display:block through my PHP tag?
I'm currently using $_GET to grab the success/fail status from signup.php and I want to use an IF statement to execute the correct JavaScript code.
UPDATE
I was advised to instead set all div's to block and use a PHP IF statement to display the login or signedup divs. However, after implementing the changes, the index.html still cannot distinguish the success/fail status. Here is my code below:
signup.php:
if (mysqli_num_rows($data) == 0)
{
$qry = "INSERT INTO logins (username, password, email) VALUES ('$username', SHA('$password1'), '$email')";
$result=mysqli_query($dbc, $qry);
if($result)
{
header('Location: index.html?signup=success');
}
}
else
{
header('Location: index.html?signup=fail');
}
index.html: Head
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Site</title>
<link type="text/css" rel="stylesheet" href="home.css">
<script type="text/javascript">...</script>
<?php
if(!empty($_GET['signup']))
{
$signup = $_GET['signup'];
}
?>
</head>
index.html: Body
<body>
<div id="container">
<?php
if(!$signup)
{
?>
<div id="login">...</div>
<?php
}
?>
<?PHP
if($signup)
{
?>
<div id="signedup">...</div>
<?PHP
if($signup == 'success')
{
?>
<div id="confirmation">...</div>
<?php
}
?>
<?PHP
if($signup == 'fail')
{
?>
<div id="failure">...</div>
<?php
}
?>
<?php
}
?>
</div>
</body>
As of now, after the user submits the form they are inserted into the database. The problem is that once they are redirected to the index.html, the php does not recognize the success/fail status and consequently only displays the login form.

That PHP code needs to go in your <head> or <body> section. You have it before <html> right now.
And yeah, onload = function(); should probably be window.onload = function;

This code doesn't do what you think it does:
onload=signedup();
You need to attach to the onload handler correctly:
window.onload = signedup;
Now, this isn't the best way to do things (it waits for EVERYTHING to be loaded), so if you happen to have jQuery included in your page, it'll be more efficient:
$(function(){ signedup(); });
Also, move the PHP to inside the HEAD tag since it prints out a script - and scripts should generally be in the HEAD tag.
Now, to take a different direction - why don't you just do it with PHP by printing out the HTML only if it's needed:
<?php if(!$signedup) { ?>
<div id="login"> ... </div>
<?php } ?>
This is probably the way to go in this case!

Related

How do I display a PHP script as html page after calling it using AJAX?

I am trying to call a php file, which will display a html page, using AJAX from my js. This is my php file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snippet details</title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
require "../server_detail.php";
$con=mysqli_connect($server,$username,$pass);
$connection=mysqli_select_db($con,$database);
if(!$connection)
echo "Connection to database failed! Please try again";
else{
$sql="SELECT `Snapshot` FROM `snippet` WHERE `Date`='".$_POST["date"].
"' AND `newspaper`='".$_POST["newspaper"]."' AND `Subject_desc`='".$_POST["news_desc"]."'";
$result = $con->query($sql);
$temp=explode('.',$result->fetch_array()[0]);
echo "<div style=
'text-align:center; vertical-align: middle;
background-color: #FFFFFF; margin: 0 auto !important;
min-height: 100%; padding: 0; width: 978px !important; overflow:auto;'>";
echo "<h3>{$_POST['newspaper']}</h3>";
if($temp[count($temp)-1]=="pdf" || $temp[count($temp)-1]=="PDF")
echo "<iframe src='{$result->fetch_array()[0]}' height='200px'>";
else
echo "<img src='{$result->fetch_array()[0]}' height='200px'>";
echo "<p>{$_POST["news_desc"]}</p>";
echo "</div>";
}
$con->close();
?>
</body>
</html>
I am trying to call this script from my js (when a li is pressed):
document.querySelector('body').addEventListener('click', function(event) {
if (event.target.tagName.toLowerCase() === 'li') {
var str=event.target.innerText.split('-');
$.ajax({
url: '/all_backend_stuff/view_page.php',
type: 'POST',
data:{
"date":document.getElementById("date").value,
"newspaper":str[0],
"news_desc":str[1]
},
success:function(response){
window.open('/all_backend_stuff/view_page.php'); //shows that all my array keys are undefined
},
complete:function(){}
});
}
});
My POST variables are showing as undefined. Why is that?
Different ways of accessing URLs behave differently.
If you use <a href="..."> then the browser will load the data from the URL and display it as a new page.
If you use <img src="..."> then the browser load the data from the URL and display the image inline at that point in the current page.
If you use <iframe src="..."> then the browser will load the data from the URL display the page in a box in the current page.
If you use Ajax then the browser will load the data from the URL and make it available to JavaScript.
That is the point of Ajax.
It doesn't display the result as a new page because Ajax is designed to not do that.
If you want to display the result as a new page then the best thing to do is not use Ajax. Use a regular <form> submission instead.
If you insist on using Ajax then you need to process the data that you are currently were, before you edited the question, logging and change the DOM of the current page using it. Generally, when you do this you will want to request a URL, with Ajax, that returns structured data (e.g. in JSON format) and then selectively update parts of the page instead of loading a whole new HTML document.

Trying to get data on a webpage through php and ajax

This might go very basic, but I am not able to understand what is the best way to call AJAX on a button click event on page and get the data from the server to be displayed using php.
What I have is a simple webpage called div.php:
<html>
<head>
<title>
Test
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js">
$(document).ready(function(){
$('#btn').click(function(){
$("#data").html('Loading...');
$.ajax({
url:'test.php',
type:'GET',
success:function(data){
$("#data").html(data);
}
});
});
});
</script>
</head>
<body>
<form method="get">
<button id="btn">
Get Data from PHP file
</button>
<div id="data">
</div>
</form>
</body>
</html>
And then a page behind it doing the database operation, test.php:
<?php
include ("config.php");
$sql = "SELECT * FROM userInfo;";
$result = mysql_query($sql);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$count = mysql_num_rows($result);
if ($count > 0) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["userLogin"] . "<br>";
}
}
?>
It is pretty basic and I am supposed to get the query result on the button click, but it doesn't work. Is there something wrong in here?
Any help or ideas to understand PHP to AJAX to JS flow will be really appreciated.
You need to embed the JS separately, you can't do what you've done but need to split as below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btn').click(function(){
... etc
});
});
</script>
This is difficult to debug based on the limited info available, although I think this may be the issue. Your <button> element is inside a <form> element. This means that when you click the button, it is submitting the form and reloading the page. Your AJAX may have worked but the page has reloaded so you won't see the data. Solution:
Either remove your <form> from the page or look into e.preventDefault() for the button click function in jquery.
On another note, you should migrate your code to using another library such as PDO for accessing databases as the mysql_* functions should no longer be used.

Polymer Iron-form not submitting

I am using the iron-form in Polymer 1.0 to submit a login form with paper-inputs and a paper-button.
I am calling submit() on the buttons onclick, but nothing happens. I even tried to put in a native button just to see if there was an error with my JS, but it still didn't submit.
However, it did show the "----- is required" popup which it didn't do with the paper-button.
I am using PHP to dynamically render the HTML, but i have also tried to make it work in a normal HTML file, which gave me the same results.
I don't use gulp to run the webserver, i just use a normal XAMPP setup.
login.php:
<?php
// configuration
require("/includes/config.php");
// if user reached page via GET (as by clicking a link or via redirect)
if ($_SERVER["REQUEST_METHOD"] == "GET")
{
// else render form
render("login-form.php", ["title" => "Log In"]);
}
// else if user reached page via POST (as by submitting a form via POST)
else if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// query database for user
$rows = query("SELECT * FROM users WHERE username = ?", $_POST["username"]);
// if we found user, check password
if (count($rows) == 1)
{
// first (and only) row
$row = $rows[0];
// compare hash of user's input against hash that's in database
if (crypt($_POST["password"], $row["hash"]) == $row["hash"])
{
// remember that user's now logged in by storing user's ID in session
$_SESSION["id"] = $row["id"];
// redirect to portfolio
redirect("/");
}
}
// else apologize
apologize("Invalid username and/or password.");
}
?>
header.html:
<!DOCTYPE html>
<head>
<script src="/bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
<!--<script src="/bower_components/webcomponentsjs/ShadowDOM.min.js"></script>-->
<link rel="import" href="elements.html">
<link rel="import" href="/styles/styles.html">
<?php if (isset($title)): ?>
<title>Test: <?= htmlspecialchars($title) ?></title>
<?php else: ?>
<title>Test</title>
<?php endif ?>
</head>
<body>
login-form.php:
<div class="outer">
<div class="middle">
<div class="inner">
<paper-material elevation="5">
<paper-header-panel>
<paper-toolbar>
<div><b>Login</b></div>
</paper-toolbar>
<div class="content">
<form is="iron-form" id="form" method="post" action="index.php">
<paper-input name="username" label="Username" required></paper-input>
<paper-input name="password" label="Password" required></paper-input>
<paper-button raised onclick="clickHandler(event)" id="loginButton">Submit</paper-button>
</form>
<script>
function clickHandler(event) {
Polymer.dom(event).localTarget.parentElement.submit();
console.log("Submitted!");
}
</script>
</div>
</paper-header-panel>
</paper-material>
</div>
</div>
footer.html:
</body>
</html>
elements.html:
<link rel="import" href="bower_components/font-roboto/roboto.html">
<link rel="import" href="bower_components/paper-header-panel/">
<link rel="import" href="bower_components/paper-material/">
<link rel="import" href="bower_components/paper-toolbar/">
<link rel="import" href="bower_components/paper-input/paper-input.html">
<link rel="import" href="bower_components/paper-button/paper-button.html">
<link rel="import" href="bower_components/iron-form/iron-form.html">
Any help will by greatly appreciated!
The iron-form element submits your request via AJAX (https://github.com/PolymerElements/iron-form/blob/master/iron-form.html#L146). In other words, it's not going to do a full page refresh like the traditional <form> element (which seems like the behavior you're expecting). It's just getting and fetching data.
I've asked the team if it would be possible to create a flag on the iron-form element so users can still get the benefit of having it submit their custom element values in the request, but force it to use the old form behavior where it does a full page refresh (allowing the server to render and send down a new page).
edit
I'd recommend that you replace iron-form in your example with a regular form element, then write the values from your paper-* elements into input type="hidden" fields, and use those to submit the form.

Error message in Javascript

I have a PHP code:
if($billing_total>$limit_to_send){
echo '<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>';
When I am printing this message, it is being printed at the beginning of the PHP page as below:
<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-----------------------------------------------------------
This caused the header (logo) of my page in the browser to move down one line.
and the page will look very bad because all the items there will be moved down one line.
I hope it is clear to you. Please any solution ?
===========================================================================
Thanks for All ...
Solution:
$alert_message=<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>
Printing $alert_message somewhere in the HTML code before the body tag ^_^
Make sure you never output anything before the DTD (doctype declaration).
See this question for more information...
The doctype declaration must be the first element of your html page, it's from what the browser decides how to handle the rest of the html code. Outputting anything before that will probably put your browser in quirks mode so you can't be sure how the browser will render your page.
How to avoid this?
The echo command gets executed as its line is reached, and it seems that the rest of your html code follows after that.
You could either
move the html DTD and header to the top of your php (but sometimes that is not possible) OR
store the error html in a variable, so instead of echo '<script ... do $errorhtml = '<script ... and output that string, if not empty, at a specific place in the head or body generating code of your php.
If you have no control over the original source, you could consider redirecting to an error page with its own html DTD, header and body which you can design as fits you best.
Either append die() into the if codeblock or have your php print the script somewhere in the body or head.
This shows a bad design of your application. I would suggest you change it to something like:
$errors = array();
if($billing_total>$limit_to_send){
$errors[] = 'Sorry, you do not have enough credit';
}
Then on your HTML file, before the <body> tag closes, read your array and display any errors
<?php if(is_array($errors)): ?>
<script type="text/javascript">
<?php foreach($errors as $error): ?>
alert('<?php echo $error; ?>');
<?php endforeach; ?>
</script>
<?php endif; ?>

"Message send" confirmation popup with PHP and JS

I am just started with PHP and have a rather simple problem I can't seem to figure out. I have set up a basic PHP script with will send me the content from my sites contact page. The script itself is fine - and so is the validator. Now what I am trying to achieve is getting a simple popup (similar to an alert function in javascript). Here is my try:
if ($valid) {
//*isUTF8($subject);
//*isUTF8($formcontent);
sendMail();
$body = $successMarkup . $backMarkup;
$title = "Form sent";
#header("location:formsent.php");
} else {
$body = $errorMarkup . $errorMarkupEnd . $backMarkup;
$title = "Form errors";
}
The file formsent.php I am refering to here only includes basic html markup as well as an javascript alert which is executed as soon as you open the page:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Contact Success</title>
</head>
<body>
<script language="Javascript">
<!--
alert ("Thank you for your message! I will come back to you as soon as possible!")
//-->
</script>
</body>
</html>
Here my question:
After I send the filled out contactsheet via the send button I get a popup with the message shown above - BUT to do so it leaves the actual page I am on and shows me only a white screen.
How can I get that popup message implemented without leaving the page I am on?
Try using this one: http://jquery.malsup.com/form/ with jQuery to make an Ajax form submit simple.
The examples, shown on that page are quite enough to implement your type of a story.
just put:
<script>
$(document).ready(function(){
$('form#form_id').ajaxForm(
function(data){
alert(data);
}
)
})
</script>
And so everything you need to do in your sendmail script is to echo the needed message, no redirecting required.
header("Location: <url>") results in a proper redirect. You need to use Ajax here to send the data (when the user submits it), receive the contents of the popup box and then display it.

Categories

Resources