This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to call a JavaScript function from PHP?
I'm working on a project for school, and I'm struggling with the login page. In my PHP code, if the user enters an incorrect username or password, I want to call a Javascript function that displays a message and briefly changes the background colour where the message is shown. Here are my JS and PHP code blocks:
<script>
var flashContent = function () {
document.getElementById("outputlogin").style.backgroundColor = "#ffff00";
document.getElementById("outputlogin").innerHTML = "Incorrect login.";
function proxy() {
updateColor(0);
}
setTimeout(proxy, 50);
}
var updateColor = function (newColor) {
var hexColor = newColor.toString(16);
if (hexColor.length < 2)
hexColor = "0" + hexColor;
var colorString = "#ffff" + hexColor;
document.getElementById("outputlogin").style.backgroundColor = colorString;
function proxy() {
updateColor(newColor);
}
if (newColor < 255) {
newColor = newColor + 5;
setTimeout(proxy, 50);
}
}
</script>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if(($username == "Ben") && ($password == "thepassword")){
//echo "SUCCESS";
session_start();
$_SESSION['bensedmgallerysesh'] = session_id();
header("Location:../index.php");
}else{
if($username != "" && $password != ""){
javascript:flashContent();
}
}
?>
Right now, after hitting the login button, I get the error message:
Fatal error: Call to undefined function flashContent()
How do I fix this?
You're trying to call a client side function in a server side script. You COULD do this:
if($username != "" && $password != ""){
?>
<script type="text/javascript">
flashContent();
</script>
<?php
}
But it might be smarter to actually separate the logic in a way that prevents you from trying to write server side processing like this. Organizational skills go a long way in this business.
Have you tried doing this:
echo '<script type="text/javascript"> flashContent(); </script>';
Instead of:
javascript:flashContent();
I dont think there is such thing like javascript: functionName()..
Javascript runs in user space, interpreted by the browser.
PHP runs in server space, and is processed by a preprocessor.
What you should do there is test the username and password in PHP, and if they are wrong send back a JSON reply to the client. In the client, parse the JSON data and show the corresponding message. You may want to do this with AJAX.
Hope that works
You cannot call a Javascript function like that with php, you would need to echo out the script calling the function in javascript. Something like this might work:
<?php
echo '<script> window.onload = function(){ flashContent(); } </script>';
?>
But that might not be a great way to do it. Php runs on the server before javascript runs on the browser. One better way to have the two languages communicate is to send AJAX calls to the php script.
EDIT
To clarify: You can echo out a call to a Javascript function in the script, and it will be run where you echoed it. But here, php will still just treat Javascript as a string to be printed on the document.
Related
I am currently working on a Chat Application and ran into a slight hiccup, I want a message that is addressed to a user to only be visible to the user and the sender.
<script>
//PRIVATE MESSAGE
var username = '<?=$_SESSION['username'];?>'.toUpperCase();
$('#chatbox').children('.msgln').each(function(){
var msgln = $(this);
$$select = msgln.find('.messagelinebox');
$message = $$select.text();
if($message.indexOf('#') !== -1){
var $product = $message.substr($message.indexOf("#") + 1);
$$product = $product.substring(0,7).toUpperCase();
var receiver = $$product;
if(username = receiver){
$(this).show();
}else if(receiver = username){
$(this).show();
}else if(receiver != username){
$(this).hide();
}else{
$(this).show();
}
}
});
</script>
Any help will be appreciated.
As pointed out by everyone, you're going about things the wrong way.
However, there are some serious problems with your if() statement. This code:
if(username = receiver) {
/* code */
}
is exactly equivalent to the following:
username = receiver;
if(username) {
/* code */
}
If you want to test if two things are equal, use ==, not =. Also, if a==b, then there is no need to test for b==a. Your entire if ... else structure can be reduced to the following:
if (username == receiver) {
$(this).show();
}
else {
$(this).hide();
}
Your code only checks for messages that were sent to the current user. It doesn't check for messages sent by the current user. That's another thing you will have to fix.
But really, do this all on the server. Not in client-side Javascript.
Your question is not comprehensive. I would like to see the result of what you have done so far if at all the sample you gave works. And as a matter of fact, you need to sieve your codes (code structuring is important) so that I'll be able to help you.
file_name.php
<?php //your PHP codes here ?>
file_name.html
<html>Blah blah</html>
file_name.js
$(function(){
//your jquery...
})
<?php
if(isset($_POST["username"]) && $_POST["username"] != "")
{
$username= $_POST['username'];
if (strlen($username) < 4) {
echo '4 - 15 characters please';
}
if (is_numeric($username[0])) {
echo 'First character must be a letter';
}
}
?>
php code not working: please help me validation using java script or ajax
e<script type="text/javascript" language="javascript">
function callme()
{
var showme = document.getElementById("show");
var user = document.getElementById("uname").value;
//for check new browser show ajax from
if(user!=="")
{
showme.innerHTML=' loading.....';
var hr = new XMLHttpRequest()
{
hr.open("post","index.php",true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.readystatechange=function()
{
if(hr.readystate== 4 && hr.status==200) {
showme.innerHTML= hr.responseText;
}
}
var v="username="+ user;
hr.send(v);
}
}
}
</script>
<body>
<span>username:</span>
<input type="text" name="uname" id="uname" onBlur="callme();"/>
<div id="show"></div>
</body>
all code working fine only php code not working please help me
when we enter some text in textbox only loading.....
any type of validation are not showing ...
I think your problem is here hr.readystatechange. What you need is hr.onreadystatechange
Maybe this is not the solution but you can echo or print_r or in a file what you receive from the browser in php and see if $_POST['username'] is coming with this name and no with uname.
print_r($_POST);
Your code is very old, now you can use jquery to make things easy with javascript and for php there are lots of frameworks out there that can do your php easy. Tags like onclick into html are deprecated or very near to be.
Is better if you expect an string
$_POST["username"] !== ""
Try to store the message in one variable and at the end of the php function, return it, is better to have only one exit than multiple along the function.
Next time try to put the question and the code in order, for readability and understanding.
Thanks, and sorry for my english... XD
I have a php script, only for learning purposes. I would like to use on my web app ajax form. Never did it, this is testing php script. So I would like to send via ajax form name and password, in php script will be checked if its correct and it will return either success(when login and password correct) or error(when no match). My problem is how to send it and receive it correctly in js or jQuery. Anyone who could help me maybe with better idea and/or better secure function of doing this?
I found on stackoverflow and tryed this script:
//bind an event handler to the submit event for your login form
$('#login_form').live('submit', function (e) {
//cache the form element for use in this function
var $this = $(this);
//prevent the default submission of the form
e.preventDefault();
//run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request
$.post($this.attr('action'), $this.serialize(), function (responseData) {
//in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page
});
});
And I was wondering if in php script it could work like this?:
<?php
$username = $_GET["name"];
$password = $_GET["password"];
if($username="*****" && $password==********)
{
header('Location:http://*****************/jaz/imes/index.html?login="success"');
}else{
header('Location:http://*****************/jaz/imes/index.html?login="error"');
}
?>
And as I said this is just a test script just for learning more about it.
First of all, try to use on() method if you're using jQuery 1.8+
Another thing is that you should set the session for that user in the PHP script, then redirect the user using the js:
jQuery:
$('#login_form').on('submit', function(){
$.post($this.attr('action'), $this.serialize(), function (responseData) {
if(responseData == 'success'){
window.location = "userpanel.php"
}else{
alert('NO MATCHES');
}
});
});
PHP:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// VALIDATING HERE, in db maybe?
if($username == 'blah' && $password == 'blah'){
$_SESSION['username'] = $username;
echo "success";
}else{
echo "failed";
}
?>
And in your HTML form you need to have 2 inputs with IDs as "username" and "password" so the above code could work.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
In an ExpressionEngine template, I'm setting a PHP session variable in a javascript file like this: (Yes, EE will parse the PHP and add plug the values to the javascript)
<?php session_start(); ?>
function check_someone_else_result(data) {
waiting_list_flag = false;
<?php $_SESSION['waiting_list_flag'] = false; ?>
if(data.CanBuy=='YES'){
show_for_someone_else();
} else {
waiting_list_flag = true;
<?php $_SESSION['waiting_list_flag'] = true; ?>
$('#sm_content .oblcontent').html($('#waiting_list').html());
$('#sm_content a.closebtn').click(function(){location.reload(true);});
$('#sm_content a.yeswaitbtn').click(function(){show_for_someone_else();});
} // if(data.CanBuy=='YES')
} // function check_someone_else_result
Now, in the show_for_someone_else() function, I'm redirecting to another page that loads another javascript file and I'm trying to set a javascript variable to the same value that I set the session variable to above.
<?php session_start(); ?>
var CART_URL = '{site_url}store/checkout/cart/';
$(document).ready(function(){
// attach the validationEngine to the form
$("#voucher_form").validationEngine('attach', {
scroll: false
}); // $("#voucher_form").validationEngine
// handles the NExt button click
$('#checkout-step-billing a').click(function(){
$('#checkout-step-billing .voucher_form').submit();
}); // $('#checkout-step-billing a').click
// handles keypresses in all the fields in the form to submit the
// form when the press enter
$("#checkout-step-billing .voucher_form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#checkout-step-billing .voucher_form').submit();
return false;
} else {
return true;
}
}); // $("#checkout-step-billing .voucher_form input").keypress
// set the wait_list_flag from the session variable
var wait_list_flag = <?php $_SESSION['waiting_list_flag']; ?>
}); // $(document).ready
But I am not getting anything at all.
How do I need to do this?
var wait_list_flag = <?php $_SESSION['waiting_list_flag']; ?>
should be
var wait_list_flag = <?php echo $_SESSION['waiting_list_flag']; ?>;
^^^^ ^
Without the echo, the PHP block doesn't output anything, so nothing gets inserted into the Javascript block. You're also missing the trailing semicolon in the javascript, which may also cause a fatal parse error.
To set the value, you will need to echo / print the $_SESSION['waiting_list_flag']; in the second snippet.
Keep in mind, in the first snippet, PHP will be run first (it's not run with the JavaScript), so the session var will always be true. (Unless that is what you meant wrt EE)
//this is in php.
function msgbox($msg, $type)
{
if ($type == "alert")
{
// Simple alert window
?> <script language="JavaScript"> alert("<? echo $msg; ?>"); </script> <?
}
elseif ($type == "confirm")
{
// Enter Confirm Code Here and assign the $result variable for use
// Should include "OK" and "Cancel" buttons.
?>
<script language="JavaScript">
if (confirm("<? echo $msg; ?>"))
{
<? $result == "ok"; ?>
}
else
{
<? $result == "cancel"; ?>
}
</script>
<?
}
}
if ($page_title->exists())
{msgbox("page exists,do you want to delete", "confirm");
}
if ($result == "ok")
//code..
The problem is that $result is not reading the value from the confirm box i think because the if clause is not being executed and the program flow is going where it would go without the if clause.
You have to understand when is your PHP and JavaScript code executed. First the server runs your PHP code. This generates HTML output, that gets passed to your browser and the browser executes the JavaScript code. This means that when you run confirm() in JavaScript, your PHP code is already finished (and probably serving another request).
You will need to rethink the user interaction.
(Btw, JSP means Java Servlet Pages, not JavaScript)