Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So in my php page I have this code :
<div id="test"></div>
<script src="test.js"></script>
And in my external javascript I have :
document.getElementById('test').innerHTML=
"<div id='abc'><a href='index.html'><?php echo 'Welcome '.$_COOKIE['user'].'<br>' ;?></a></div>";
Cookie has been set and if I put the script inside the php page, it does work but why isn't it working when it is external script ? Did I do something wrong here ? or is there a rule for doing this ?
Please educate me.
Thx in advance. =D
While using PHP and javascript together is absolutely possible, you have to remember, that PHP is executed on server-side while javascript is executed on client-side.
So you cannot have PHP in your javascript, as the page lifecycle is like this:
Get the request from client browser
Execute the PHP of the requested page and provide the html
Send the html to the client browser
Render the html in the client browser
Execute the javascript of the page
So after the page is sent, the php processing is done.
You can however embed variable via php for later use with javascript. If you echo out something like this, your java scripts can use it:
<script type="text/javascript">
var myCookie = "<?php echo $_COOKIE['user'];?>";
</script>
If you do a lot of stuff with cookies in your javascript, you may even better have a look at jQuery Cookies and fetch the cookie value directly. This will make you end up with much cleaner code.
You can't use PHP in a javascript file like that. They are two totally different languages.
You can't render php on a Javascript file, but you can do this:
on your php file:
<script>
var cookie = "<?php echo 'Welcome ' . $_COOKIE['user'] . '<br>'; ?>";
</script>
<div id="test"></div>
and in your js file:
document.getElmentById('test').innerHTML = cookie;
Regards
We cannot add php code inside the js file.
PHP is server side scripting language which will executed in the server and response will returned to the browser, while Javascript is client side scripting language which is executed in the browser.
This is a solution but just use ajax to get the required information from the server.
<div id="dom-target" style="display: none;">
<?php
$output = "42"; //Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
<script>
var div = document.getElementById("dom-target");
var myData = div.textContent;
</script>
Related
The architecture I use to load contents onto a common area on the web page is as below
I have a java script function within the form as shown below called javaScriptFunc which never gets invoked.
Is it possible to invoke a java script function within a form?
Please do let me know if more clarity is needed. I'll try to clarify. I'm stuck with this for a while now. I'd appreciate any help please
I think you are missing some PHP tags if I understand what you are trying to do correctly. Try this:
<form method="post" action="" id='somdId'>
<?php
require_once 'some_php_file.php';
if (isLoggedIn()) {
// Some PHP code here
?>
<script>
javaScriptFunc(<?php echo formatJson(someArgs); ?>);
</script>
<?php
}
?>
Not very clear what you want. You need to echo the script like this
echo ("<script type='text/javascript'>javaScriptFunc(" . formatJson(someArgs) . ");</script>");
provided you have already defined the function javaScriptFunc somewhere else in script.
For some reason, I the JS function doesn't seem to fire from within a form. I've worked around by re-writing the load logic to load the whole PHP page instead of a form. just a different way of doing things.
This question already has answers here:
Call php function from JavaScript
(5 answers)
Closed 7 years ago.
I was wondering how would I make it so that when a button is clicked in my form, it runs a php function that is on the same file?
I tried doing something like this:
<form>
<input type=button name="button" value="Submit" onClick="hello()">
</form>
<?php
function hello(){
echo "Hello"
}
?>
But when the button is clicked, nothing happens, neither of my functions are called. How would I go about doing this?
PHP is a server side language.
You need a client side language "JavaScript".
If you need really php execution : You need ajax requests on a url (script.php).
This:
<?php
function hello(){
echo "Hello"
}
?>
exists on the remote server and the rest of HTML in your browser. Even though they are in the same file they don't see each other.
Use AJAX PHP to make PHP functions run from within HTML pages
Here is the link AJAX PHP
I have one javascript named func.js, in that there is one function called show which takes 2 arguments, what I need to do is I want to call that function from php, I can't use any click or onload event here my script looks like this
<html>
<head></head>
<script type='text/javascript' src='path/to/func.js'></script>
<body>
some div etc
<form method='post' action="" >
.....
.....
</form>
</body>
</html>
<!-- after submit of form validation is in php -->
<?php
/* here I want to call javascript, where arguments are php variables
show('argument1','argument2'); */
// I tried to echo like this
echo "<script>show('$argument1',$argument2')</script>";
?>
So what's the solution for my case ?
The code you have should work… most of the time. Unfortunately, you haven't told us why it doesn't work - is there a PHP error? Is there a JS error? — and you haven't shown us either the resulting JavaScript that PHP is outputting or the contents of the variables so we can figure it out for ourselves.
The two most likely explanations (and the only ones that occur to me at the moment) for the problem are:
There is a problem with the data in the variables
That the variables contain characters which cannot appear inside JavaScript strings or ' characters which must be escaped inside JavaScript strings.
JSON is a sufficient subset of JavaScript that the json_encode function will escape (and quote) most data so it is suitable for use in JS.
<script>
show(<?php echo json_encode($argument1); ?>, <?php echo json_encode($argument2); ?>)
</script>
There is a problem with your timing
You have an HTML comment saying "after submit of form validation is in php", but there is nothing in the code you have shared to enforce that.
You need to have something like if (isset($_POST['some_data_from_your_form'])) { ... } wrapped around the generation of the script so it only appears when the form is submitted and not when it initially loads.
If that doesn't work, then you really do need to look at what the variables are, what the generated JS is, and what your JavaScript error console says.
Script elements are not allowed after the end of the HTML element. While browsers will recover from that error, you really should move the script inside the BODY.
It could be to do with the data inside the arguments, what sort of data is it?
echo "<script>show('".str_replace("'", "\'", $argument1)."', '".str_replace("'", "\'", $argument2)."')</script>";
If you're passing information such as J'min it will cause an issue. Does the data have multiple lines? Then it needs to be filtered.
First of all, your tags are broken
<script type='text/javascript' href='path/to/func.js'</script>
You should change href to src and close the script tag, so it becomes
<script type='text/javascript' src='path/to/func.js'>
Also, javascript is client-sided which means you can't call javascript functions in PHP.
I think a good solution here would be to use an AJAX call to validate your form.
Have you tried putting the arguments outside the quotes?
echo "<script>show('".$argument1."', '".$argument2."')</script>";
echo '<script type="text/javascript">show(' . $argument1 . ',' . $argument2 . ');</script>';
above might work for you.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
This is my first foray into Javascript and AJAX (I'm reading JavaScript and JQuery, The Missing Manual). I've written this code to try to send data from a form using AJAX, to a php file which queries a database (queries work fine phpMyAdmin), return the data and display on screen using Javascript to append a div.
My sticking point is making the AJAX work with the server php page. I'm also wondering if there are steps along the way I can take to check to see if my code is working properly.
Here is what I've written so far, thanks for any help and insight:
<html>
<head>
<meta charset="UTF-8">
<title>Sidework Review Screen</title>
<link href="./_resources/_css/site.css" rel="stylesheet">
<script src="./_resources/_js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
//var sw = "testing";
var sw = $("#switcher").val();
var tech = $("#id_techs option:selected").val();
// alert(tech);
$.post('side_work_controller.php',
{
switcher: sw,
id_techs: tech
},
function(data, status){
alert("Date: " + data + "\nStatue: " + status);
}); // end post
}); //end click
}); // end ready
</script>
</head>
<body>
<?php
try {
$username = "xxxx";
$password = "xxxx";
$dbh = new PDO('mysql:host=10.5.44.12;dbname=SideProjects', $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $dbh->prepare("SELECT DISTINCT tech_fname, tech_lname, extension
FROM `techs` ORDER BY tech_lname
");
$sth->execute();
$sql = $sth->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="top"></div>
<div id="dropshadow"></div>
<div id="container">
<div id="left">
<div id="logo"><img src="logo.png"></div>
</div>
<div id="right">
<!--<form action="side_work_controller.php" name="switcher" method="post">';-->
<h1>Sidework Review</h1><p>
<label for="tech_ids"><h2>Choose a Technician</h2></label><p>
<select name="id_techs" id="id_techs"> //Builds drop down menu-->
<?php foreach ($sql as $row){
echo '<option value = "' . $row['extension'] . '">' . $row["tech_fname"] . ' ' . $row["tech_lname"] . ' - ' . $row['extension'] . '</option>';
} ?>
</select><p>
<input type="hidden" name="switcher" id="switcher" value="search">
<div id="button"><button>Review</button></div>
</div>
</div>
<div id="bottom"></div>
</body>
</html>
EDIT:
I've discovered that part of the problem is with my button, it needs to be
<button>Review</button> not
echo '<input type="submit" id="button" onclick="click()" value="Review">';
for this to work.
EDIT:
Also just worked out that the <select> and <input> tags needed id="[id name]" in order to work with the .val() function.
EDIT:
I've written a bit of the AJAX and is does send to the php file and gets some data.
I am reposting my changes for the benefit of newbie like me. The AJAX doesn't work correctly yet.
As others said, you forgot to put some quotes around a selector.
There's many other mistakes:
you forgot a ; after data array variable initialization
this code has a problem : where is the $('#container').html(newHTML); when requests finish ? He does not exist.
$.post('side_work_controller.php',data,function(data, status){
var newHTML = data + '.</P>';
//$('#container') does not exist at this moment
$('#container').html(newHTML);
}); // end post
You could append to document instead :
$(newHTML).appendTo(document);
As I said in a comment on your question, things like echo '<div id="top"></div>'; are bad : unreadable, hard to maintain. Your IDE (if you use one) can't detect HTML errors. Have a look at this very interesting post, or templates engines like Smarty
What are those </body> and </html> at the end of the php file ? If you choose to 'echo' your HTML (bad choice I repeat), do it until the end.
Correct this code and try to debug things by yourself. By this way I mean you should use a javascript debugger : integrated browsers consoles are pretty good nowadays. You can access it with F12 shortcut. Read documentations about it, here for chrome.
Hope this helps.
You're missing quotes around your selector when you define the click action.
$(#button).click(function(){
Becomes:
$("#button").click(function(){
I'm trying to update the action property of the form tag by calling a JavaScript function when a user presses the submit button. The action property is updated depending on what is selected in the select box called "proceed". However the following script does not work and I don't know why.
Javascript:
<script type="text/javascript">
function updateAction() {
<?php
if (empty($errors) && isset($_POST['submit'])) {
echo 'document.newStudent.action = document.newStudent.proceed.value';
} else {
echo 'document.newStudent.action = "newStudent.php"';
}
?>
}
</script>
<form name="newStudent" method="POST" onsubmit="updateAction()">
Select box which is much further down in my code:
<?php //PROCEED
echo '<tr>';
echo '<td><p>Proceed To:</p></td>';
echo '<td>
<select name="proceed">
<option value="newSchedule.php">add student\'s schedule</option>
<option value="newStudent.php">add another student</option>
<option value="staff.php">staff page</option></td>';
echo '</tr>';
?>
You can not write PHP code inside a JavaScript method like that. You have to understand difference between server-side scripting and client-side scripting. In your scenario write a JS code which accomplish your task. Read this Client side vs server side basics, PHP vs JavaScript For Dynamic HTML Pages
Javascript and PHP allow website developers to create dynamic Web pages. Javascript is a client-side language, so it runs on the reader's computer. PHP is a server-side language, so it runs on the Web server. These two languages are combined to create interactive website's for readers. Each of these languages are combined, but they interact with the Web browser differently.
There are situation you can write PHP inside a Javascript function but not in your scenario.
Read More