Split out jquery code from html that is echo'd in php - php

So I'm just dabbling in this and most likely doing it wrong. But it's a proof of concept so I can get the powers that be to get someone to do it right.
I am using a php script for login and for posting variables from forms.
The problem: I am echocing out an html code that includes the css, html, and jquery scripts all in one file. Which is fine for the css and html portion, but the jquery stuff doesn't work.
Is there a way to place the jquery portion in my php script to make it function, or does it need to be split out and referenced/loaded in the html. (I believe that is the correct way, but I don't know how or where to start.)
code: (after binding to ldap and authenticating, this block is triggered)
// verify binding
if ($ldap_bind) {
echo "
<head>
<link - stylesheet \link>
</head>
<form class=\"form-horizontal\" action\"form.php\" method=\"POST\" enctype=\"multipart/form-data\">
<fieldset>
<body>
html code....lots of div boxes
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>
<script>
$(document).ready(function(){
Various Jquery functions that hide/unhide div boxes
});
</script>
</body>
</fieldset>
</form>
";
} else {
echo "<p class='text-error'>Unable to log you in:</p>";

First, your HTML structure is quite mixed up. Have a look at how I "reorganized" it below and feel free to read tutorials like this one about it.
Second, you can use the PHP tags (<?php and ?>) to avoid the multi-line echo and all the quote escaping mess. What is outside these tags won't be processed by PHP and sent as-is to the browser. So you can write "usual" HTML there.
Third, having your scripts outside HTML like <form> is a good practice. And the library calls commonly are placed in the <head>... But it's also common to have it near the end of the document, just above </html>, instead of the <head>. For sure, not oddly everywhere in the markup.
// verify binding
if ($ldap_bind) {
?>
<head>
<title>My page title</title>
<link rel="stylesheet" href="...">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form class="form-horizontal" action="form.php" method="POST" enctype="multipart/form-data">
<fieldset>
html code....lots of div boxes
</fieldset>
</form>
<script>
$(document).ready(function(){
//Various jQuery functions that hide/unhide div boxes
});
</script>
</body>
<?php
} else {
?>
<p class='text-error'>Unable to log you in:</p>

Related

PHP Autocomplete using SQL [duplicate]

This question already has answers here:
jQuery autocomplete with callback ajax json
(6 answers)
Closed 1 year ago.
I'm new to PHP and trying to implement an autocomplete as a proof of concept for a project for work.
The following is the code for the web page.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- jQuery UI library -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- Initialize autocomplete -->
<script>
$(function() {
$("#skill_input").autocomplete({source: "search.php",});
});
</script>
</head>
<body>
<div class="container">
<h4>Auto complete Input for countries</h4>
<form method="post" action="submit.php">
<label > Your Skills:</label>
<input type="text" id = "skill_input" name="skill_input" placeholder="Start typing..."/>
<input type="submit" name="submit" value="SUBMIT">
</form>
</div>
</body>
</html>
The page displays as it should. As I type a valid search term for what is in the DB nothing happens. e.g. "Ger"
I'm running the site on xampp.
My DB is loaded with countries.
I put an echo in my DB module to see if it is reached. It is not displaying unless I use the URL of the DB module directly. When I go to the DB module directly using the URL http://localhost:8012/Managers/search.php?term=Ger
I receive the following
we are in the search php file
[“Algeria”,”Germany”,”Niger”,”Nigeria”]
This seems to indicate that the DB module is working e.g. accepting a search value, accessing the DB and returning data as expected.
So it appears to me that the script
$(function() {
$("#skill_input").autocomplete({
source: "search.php",
});enter code here
});
</script>
is not sending any data to the "search.php" page.
My question is why? Can anyone help me understand why the page is not sending any data to search.php? I would assume that it is not even calling search.php as I'm not seeing the echo message unless I use the URL directly.
The return of data is resolved.
/* Toss back results as json encoded array. */
$json_array = array();
$json_array = json_encode($return_arr);
echo json_encode($return_arr);
The above code coverts the response from the DB to json and then returns the data.

Change img attribute and disable inputs with jQuery after PHP form validation

I am trying to change the 'src' of an image element and also change the properties of input elements to 'readonly' after a form has been validated and submitted. The validation of the form occurs in PHP so I cannot attach an on submit event handler as it will trigger even if the form has not passed validation. Is there any way to do this without a plugin of some kind?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>
</head>
<body>
<script>
$(document).ready(function()
{
$("#button_img").click(function ()
{
alert("button clicked");
$("#course_name").css("background-color", "yellow");
$("#course_name").attr("readonly",true);
$("#button_img").attr('src','../images/edit_course.png');
});
});
</script>
<form id='design_course' action="<?php ($_SERVER['PHP_SELF']); ?>" method="post">
<label id="course_name_label">Course Name:</label>
<input type=text id="course_name" name="course_design_name" value="default">
<button id="create_course" type="submit" ><img id="button_img" src="../images/create_course.png"></button>
</form>
</body>
</html>
Since the validation logic you're using for this is server-side, the page is going to be changing during a reload. So your logic for conditionally setting values in your HTML would be server-side.
You can conditionally output to the page from PHP based on any if statement. You're not showing the validation logic, but let's assume for the sake of example that if validation passes then there is a boolean variable called $passedValidation. Then you can do something like this in your code:
<?php if ($passedValidation) { ?>
<img id="button_img" src="../images/something_else.png">
<?php } else { ?>
<img id="button_img" src="../images/create_course.png">
<?php } ?>
So note that if the form "passed validation" then the image used is something_else.png instead of create_course.png. So when the page reloads after having passed the validation logic, the user will see the other image.
The same can be done for other HTML output. How you organize it is up to you, as it could get ugly to re-use this same if/else structure for a variety of attributes on the page. Perhaps you can just have two complete forms wrapped in a single if/else block or something like that.
Note also that you'll want a default case of false for $passedValidation to handle when the page is first loaded and no form has been submitted at all.

How to process and display the outer layer of html first before 'loading' the content?

How can I ask PHP to process and display the outer layer of html first before 'loading' the content? For instance,
<html>
<body>
<p>Please wait, we are processing your request</p>
<?php include 'article.php';?>
</body>
</html>
I want to print this on the client browser first,
<html>
<body>
<p>Please wait, we are processing your request</p>
</body>
</html>
before showing whatever is included here,
<?php include 'article.php';?>
Is it possible?
You can do it with Jquery:
<html>
<body>
<div id='article'>
<p>Please wait, we are processing your request</p>
</div>
<script>
$("#article").load("article.php");
</script>
</body>
</html>
The .load command gets the contents from whatever URL you provide, and sticks it in the named DOM element (#article).
Read all about it:
http://api.jquery.com/load/

Get inner html with php

I started learning php and I came accross this issue. I have the html code in my form:
<label for="u">Usability <span id='u_score'>0</span> / 7</label>
I want to get the inner html of the span with id u_score. How do I do this in php? Any help would be appreciated.
I have already tried
$u_score = $_POST["u_score"];
but that returns undefined because there is no value associated with the span.
Thank you
What you can do is to copy the span text content into a hidden input which will be posted:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function copySpanContent() {
document.getElementById("u_score_value").value =
document.getElementById("u_score").firstChild.data;
}
</script>
</head>
<body>
<form method="POST" action="PHPSCRIPT.php" onsubmit="copySpanContent()">
<label for="u">Usability <span id='u_score'>0</span> / 7</label>
<input type="hidden" name="u_score_value" id="u_score_value">
<button type="submit">submit</button>
</form>
</body>
</html>
Then you can get the value from PHP with $_POST['u_score_value'].
You can use Simple HTML DOM, it is an HTML parser for PHP. Download it then use this snippet:
include('simple_html_dom.php');
$html = file_get_html('yourHTMLfile.html');
$IDs = $html->find('span #u_score');
foreach($IDs as $id)
{
echo $id.'<br />';
}
Hope this helps!
php actually generates the html and does not perform any work (unless called via a method like ajax) to affect the page after it has completed building.
Javascript can get DOM element values, but PHP can not.
the method you are using will not work as the variable was not a $_POST variable but just an HTML element.
Please learn the dividing line between client (Javascript) and server (PHP).
You could use PHP to deliver the HTML that you require.
You could also use Javascript to look at the DOM via getElementById to do the business.

Pass variable into an input

I made an html file called test.html then I navigated to it as "http://site.com/test.html?test1=a" but the textbox stayed blank. Why is this?
Super simple code
<html>
<head>
<title>Test</title>
</head>
<body >
<input type=text name="test1">
</body>
</html>
The file should be a PHP file, so test.php.
Then maybe something like this:
<html>
<head>
<title>Test</title>
</head>
<body>
<input type="text" name="test1" value="<?php echo htmlspecialchars($_GET['test1'], ENT_QUOTES); ?>">
</body>
</html>
The reason it stays blank in your example is because there is no PHP code to put the value into the field. It isn't automatic. Also, on most servers (but not always), a file with an .html extension will not be parsed by PHP.
Also, passing it to the htmlspecialchars function will help prevent cross-site scripting.
HTML is just another file extension to a webserver, it's not going to do any kind of processing unless you've done something to make that so. Would you expect to open http://site.com/foo.txt?contents=helloworld and see "helloworld" in the browser?
I suggest you google up some tutorials (w3schools is usually good for this sort of thing) on PHP, then on "query strings" and how server side scripting works. You should be up and running with basic site scripting pretty fast.
It might be possible to read the URL via javascript and populate the textbox that way if you must use static html.
<html>
<head>
<title>Test</title>
</head>
<body >
<input type=text name="test1" value="<?php echo htmlspecialchars($_GET['test1']);?>">
</body>
</html>

Categories