Having trouble calling external javascript function through PHP - javascript

I'm building a website, and I am incorporating PHP and Javascript into the website. What I am trying to do with this website is to use an interface that allows a user to "log in" in a sense, and then store the information entered through the use of cookies. I am trying to call an external js function using php, however for some reason, although the script tag is being added into the html document as desired, the function is not being called at all and can't figure out why or how to fix it. I have attached a portion of my code below. Thank you very much in advance.
My PHP code:
<?php
$fail="";
$success="";
if (isset($_POST['submit'])) {
echo "<script>console.log('Submitted');</script>";
$first=$_POST["first"];
$last=$_POST["last"];
$city=$_POST["city"];
if ($first!="test"||$last!="test"||$city!="test"){
$fail="This is an error message";
}
else{
echo "<script>console.log('This is working from html');</script>";
$success= "<script src='main.js'>
console.log('success variable is working');
createCookie('first',$first);
createCookie('last',$last);
createCookie('city',$city);
</script>
<script>
console.log("Hello World!");
</script>";
}
}
?>
Portion of my HTML:
<div id="container">
<?=$fail?>
<form action="" method="POST">
<p>Enter Family Name (as it appears on your invitation): </p>
<input class="entry" type="text" name="first" placeholder="FIRST NAME" required><br><br>
<input class="entry" type="text" name="last" placeholder="LAST NAME" required><br><br>
<input class="entry" type="text" name="city" placeholder="CITY (ONLY)" required><br><br>
<input name="submit" type="submit" style="margin:auto; display:block">
</form>
<?=$success?>
Javascript code:
function createCookie(name,value){
document.cookie=name+"="+value;
console.log("This is working");
console.log(document.cookie);
console.log("This is too");
}
function getCookie(name){
var split=document.cookie.split(";");
for (let i=0;i<split.length;i++){
if (split[i].indexOf(name)===0){
return split[i].substring(name.length+1);
}
}
}

This portion of code is creating a conflict in behavior in the web browser (you have both src and code in the same script tag):
$success= "<script src='main.js'>
console.log('success variable is working');
createCookie('first',$first);
createCookie('last',$last);
createCookie('city',$city);
</script>";
You should change this, by simply making a second script tag (splitting them up):
$success= "<script src='main.js'></script>
<script>
console.log('success variable is working');
createCookie('first',$first);
createCookie('last',$last);
createCookie('city',$city);
</script>";
That way the src does not negate any code content of the script tag.
Second, you should also quote the strings being added from php in those js function calls. Like so:
$success= "<script src='main.js'></script>
<script>
console.log('success variable is working');
createCookie('first',". json_encode($first) .");
createCookie('last',". json_encode($last) .");
createCookie('city',". json_encode($city) .");
</script>";
The use of json_encode here is to ensure the values are javascript safe to pass through and not break the script.

Related

Run a JavaScript function from a php if statement

I would like to create a php IF statement so If it receives the key "test" by POST, <h2> hello </ h2> should be output, otherwise <span> error </ span>
How can I make that?
<div id="rre">
<h2 class="desktop">Hamburg,a major port city in northern Germany.</h2>
<h2 class="mobil">Berlin,is the capital and the largest city of Germany.</h2>
</div>
<form action="viereck.html" method="POST">
<input type="text" name="check"?>
<input type="button" value="Klick" onclick="klick();" />
</form>
<script type="text/javascript">
function klick() {
jQuery('#rre').html('<h1>Hallo</h1>');
}
</script>
The response that you return needs to be inside script tags like:
echo '<script type="text/javascript">alert();</script>';
Why you don't do that with jquery: Try smth like this
<script type="text/javascript">
function klick() {
if($("#text").val() == 'test'){
jQuery('#rre').html("<h1>Hello there!</h1>");
}else{
jQuery('#rre').html("Error");
}
}
</script>
Html
<div id="rre">
<h2 class="desktop">Hamburg,a major port city in northern Germany.</h2>
<h2 class="mobil">Berlin,is the capital and the largest city of Germany.</h2>
</div>
<form action="viereck.html" method="POST">
<input type="text" name="check"? id="text">
<input type="button" value="Klick" onclick="klick();" />
</form>
JSFIDDLE
If the page you're posting to is viereck.html, you're going to be unable to use PHP on it.
If you can change the file to viereck.php, you can POST to it like you're doing, with action="viereck.php" method="POST" Then, at the top of your page, check for POST values in PHP like:
<?php
if(isset($_POST['check'])){
$check = '<span>error</span>';
if($_POST['check'] == 'test'){
$check = '<h1>Hallo</h1>';
}
}
?>
And if your jQuery is on the same page, you can insert the PHP like:
<script type="text/javascript">
function klick() {
jQuery('#rre').html(<?= $check; ?>);
}
</script>
Doing it this way though can lead to some serious headaches as your project grows, I wouldn't recommend it. Why not look into using AJAX? You can submit a form and return a message indicating success or failure, as well as why. You can then create your HTML in jQuery instead of a PHP string like:
// On form submit
$.ajax({
url: "viereck.php",
type: 'POST',
success: function(result){
var msg = $('<h1>').text('Hallo');
$('#rre').html(msg);
},
error: function(result){
var msg = $('<span>').text('Error');
$('#rre').html(msg);
}
});

JS function called from PHP works well in Chrome but it doesn't in Firefox

I have this simple code that allow users to search for certain content within a webpage. The code works well in Chrome and Opera but it does not in Firefox and Explorer. In this last two browsers mentioned, once the form is posted, the page just refreshes itself instead of redirecting to the result page.
What would I need to add or modify in order to make this work in all major browsers?
Thank's for you attention.
The code:
<?php
if($_POST[search2]){
if(!empty($_POST[text_search])){
echo "<script type='text/javascript'> window.open('search_results.php?q=".$_POST[text_search]."','_parent'); </script>";
}else{
echo "<script type='text/javascript'> alert ('You must enter something'); </script>";
}
}
?>
<html>
<head></head>
<body>
<form method="post" action="" name="formsearch">
<input name="text_search" class="input_search" type="text" placeholder="Enter your search">
<input type="image" src="search.png" id="search2" value="search" name="search2"/>
</form>
</body>
</html>
input type="image" defines an image as a submit button but never carry the value in the post array to server. Alternative to use image as submit, try to use button.
Replace
<input type="image" src="search.png" id="search2" value="search" name="search2"/>
With
<button type="submit" name="search2" value="search"><img src="search.png" alt="search"></button>
Also use quotes for $_POST elements.
if($_POST['search2']){
if(!empty($_POST['text_search'])){
echo "<script type='text/javascript'> window.open('search_results.php?q=".$_POST['text_search']."','_parent'); </script>";
}else{
echo "<script type='text/javascript'> alert ('You must enter something'); </script>";
}
}
<html>
<head>
<?php
if($_POST['search2']){
if(!empty($_POST['text_search'])){
echo "<script type='text/javascript'> window.open('search_results.php?q=".$_POST['text_search']."','_parent'); </script>";
}else{
echo "<script type='text/javascript'> alert ('You must enter something'); </script>";
}
}
?>
</head>
<body>
<form method="post" action="" name="formsearch">
<input name="text_search" class="input_search" type="text" placeholder="Enter your search">
<input type="image" src="search.png" id="search2" value="search" name="search2"/>
</form>
</body>
</html>
You just need to put your php tag that generates the JS between .
and I also put quote in the $_POST index.

checking isset at bottom of page not working

I have a dilemma (which I am yet to find a way around). For some reason, PHP doesn't want to check if $_POST["login"] at the bottom of the <body> tag within my document.
It will work if it is put at the very top of the document, or even the top of the <body> tag. However, if I put it at the top of the document / <body> tag, the output JavaScript will not execute!
For example, this is the document (where the PHP will not execute):
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
<?php
if(isset($_POST["login"])){
echo "
<script>
document.getElementById('example-element').style.display = 'block';
</script>"
}
?>
If I am to do something like this, however (the PHP will execute):
<?php
if(isset($_POST["login"])){
echo "
<script>
document.getElementById('example-element').style.display = 'block';
</script>"
}
?>
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
But due to how JavaScript compiles, it will throw an error saying how it cannot set a style on a null element.
I have no idea how to get around this dilemma, so all help is appreciated!
Cheers.
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
<?php
if(isset($_GET["login"])){
echo "<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('example-element').style.display = 'block';
}, false);
</script>";
}
?>
Check if this works..... I've added the display code inside the DOMContentLoaded event and change the $_POST variable to $_GET. Works fine in my local system.
You can do it as follows
<style>
.someClass {
display: block;
}
</style>
<?php
if(isset($_POST["login"])){
$hasClass = true;
}
?>
<form method="post">
<span id="example-element" class=<?php if(isset($hasClass)==true) echo "someClass"; ?> >Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
The other problem with your code is that you are not setting method of your form and by default it is GET where as in php you were looking for POST request.
You could solve it either by using $_REQUEST in php when you are not sure about the method.
Actally php executes before javascript.
Change like this
<script>
var isSubmit = "<?php isset($_POST['login'])?true:false; ?>";
if(isSubmit){
document.getElementById('example-element').style.display = 'block';
}
</script>"

calling for javascript function in php form

I am using a contact form on my website and I want it to use a javascript function to use a popup box to tell the user that they have not filled all fields. I have this code:
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
*Name:<br>
<input name="name" type="text" value="" size="30"/><br><br>
*Email:<br>
<input name="email" type="text" value="" size="30"/><br><br>
*Message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<script type="text/javascript">
function requiredFields() {
alert("Please fill in all fields!");
}
<?php
}
else /* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "requiredFields();";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("email#email.com", $subject, $message, $from);
echo "Email sent!";
}
}
?>
</script>
However, the website displays this error:
Fatal error: Call to undefined function requiredfields() in /home/a8502709/public_html/test/contact.php on line 46
The line above is the line that it echoes the calling for the function. How can I properly call the function in echo?
You didn't quote your echo output:
echo requiredFields();;
It should be:
echo "requiredFields();";
Otherwise you're telling PHP to execute the requiredFields() function, which doesn't exist in PHP. Hence the error. Your intent here is to tell the JavaScript on the rendered page to execute the function. So as far as PHP is concerned you're just outputting a string to the page.
Note also that this is a syntax error:
echo "Email sent!";
What this will do is emit the following to the JavaScript in your <script> block:
Email sent!
Which, of course, isn't valid JavaScript. You probably meant to output that somewhere else in the page.
Edit: You also seem to have a significant logical error in your code. If you remove the unrelated lines, your structure is essentially this:
if ($action=="") /* display the contact form */
{
?>
<script type="text/javascript">
<?php
} else {
echo "requiredFields();";
}
?>
</script>
So... You only open the <script> tag in the if block, but you use that tag in the else block. By definition both can't execute. Only one or the other. So you're going to have to restructure this a bit.
Maybe close the <script> tag in the if block too, and then open another one in the else block? Or have multiple if/else blocks for the HTML and for the JavaScript? There are a couple of different ways to structure this. But you should see what I'm talking about when you view the page source in your browser. You'll see that, in the event of the else block, you're never creating a <script type="text/javascript"> line and therefore aren't actually executing any JavaScript.
Though, thinking about this some more, it doesn't make sense at all to have the JavaScript start in the if block. Since only the else block uses it. You can't define the function in the if and then try to use it in the else because, again, by definition only one or the other would execute. Maybe just move all of the JavaScript to the else:
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
*Name:<br>
<input name="name" type="text" value="" size="30"/><br><br>
*Email:<br>
<input name="email" type="text" value="" size="30"/><br><br>
*Message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<?php
}
else /* send the submitted data */
{
?>
<script type="text/javascript">
function requiredFields() {
alert("Please fill in all fields!");
}
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "requiredFields();";
}
else
{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("email#email.com", $subject, $message, $from);
echo "alert('Email sent!')";
}
?>
</script>
<?php
}
?>
Honestly, this mix of PHP/HTML/JavaScript you have here is a little confusing. Which isn't making this any easier for you. You'll probably want to re-structure this a bit once you get it at least working.

jQuery.get to read a file and use the data into a form

I want the script to do the following:
On page load, read a text file with a number (just one line)
Increment the number by 1
Insert the number in an <input> box of the form
Once <form> is submitted, write the number to the text file
When the form gets loaded again, it will rerun the code and the number will increment by 1. This is basically to pre-populate a field with a unique and progressive number prior to form submission.
I am currently using jQuery, PHP and of course HTML:
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
$.get("http://www.domain.com/tools/formdata.txt");
function test(){
$.get('http://www.domain.com/tools/formdata.txt', function(data){
x = data++;
});
}
</script>
</head>
<body onload="test()"/>
<form action="save_json.php" method="post">
Contract: <input type="number" name="contract" id="contract" value="x" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
PHP
<?php
if(isset($_POST['contract'])) {
// if form fields are empty, outputs message, else, gets their data
if(empty($_POST['contract'])) {
echo 'All fields are required';
}
else {
// adds form data into an array
$formdata = $_POST['contract'];
if(file_put_contents('/var/www/domain/tools/formdata.txt', $formdata)) echo 'Data successfully saved';
else echo 'Unable to save data, try again or contact IT';
}
}
else echo 'Form fields not submitted';
?>
First: I recommend that instead of javascript, you do this with PHP file_get_contents('formdata.txt') at the start of your file, and then you echo it in. That way, the value will be there on load, rather than having to wait for the HTML to render and the javascript to run. Also, it is a much better practice and will let you do a lot more things if you choose to expand the page.
However, here's the solution to the issue presented:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
var x;
function test(){
$.get('file.txt', function(data){
console.log('data',data);
var x = ++data;
console.log('x',x);
$('#contract').val(x);
});
}
</script>
</head>
<body onload="test()"/>
<form action="aoeu.php" method="post">
Contract: <input type="number" name="contract" id="contract" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
The things to note:
Close off your <script> tag including the jquery library, then open another one after it.
No need to do the first $.get() you have - save it for the function.
var x = data++; - this increments data AFTER its value has been assigned to x. So, it will never increase. Do ++data instead, and it increments before.
You need to place it somewhere afterwards. How you had the input (value='x') is just trying to put the character "x" into the input. Use javascript to edit the functions value, as in my example.
Your PHP works fine.

Categories

Resources