<?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
Related
I've had a look around and unfortunately the solutions I've found on the site don't appear to address my issue below.
Basically I'm doing a project where I need to effectively set up a diary - the user writes in a textarea element and this is passed via PHP to a database and stored for the user. In the lecturer's video, it appears he's doing without using a submit button (even if he's not, I think it'd be an interesting thing to learn how to do).
I'm having some issues though. Here's my PHP:
<?php
session_start();
if(array_key_exists("id", $_COOKIE)) {
$_SESSION['id'] = $_COOKIE['id'];
}
if(array_key_exists("id",$_SESSION)) {
echo "Logged in: <p><a href='secretDiaryFinal2.php?logout=1'>
Log out</a></p>";
} else {
header("Location: secretDiaryFinal2.php");
}
/* I'm putting in the database update later, for now I just wanted to check if I could
actually create the POST variable below*/
$msg = "";
if(array_key_exists('diaryEntry',$_POST)) {
$msg = $_POST['diaryEntry'];
} else {
$msg = "Some kind of PHP error";
}
?>
The relevant HTML:
<body>
<div id="testDiv">
<? echo $msg ?>
</div>
<div class="container" id="diaryArea">
<form method="post">
<textarea id="diary" value=""></textarea>
</form>
</div>
The relevant JQuery (I'm very weak on Ajax and I suspect there's a lot of issues here - also note the url I'm using is actually in the same script as the JQuery, I'm not certain if that works?) is below.
The basic idea is that every time the user types, the database should be updated (I realise this is a lot of calls to the server, I'll probably replace it with a timed command):
<script type="text/javascript">
$("#diary").keyup(function () {
var dataString = $("#diary").val();
$.ajax({
type: "POST",
url: "loggedInPageFinal.php",
data: ({diaryEntry:dataString}),
success: function(data) {
console.log(data);
}
});
return false;
});
</script>
Many thanks in advance and apologies for my poor code!
var DataString = $("#diary").val();
$.post( "loggedInPageFinal.php",{dataString:DataString }, function( data ) {
console.log(data);
});
Your ajax script actually does work.
But your php code isn't returning anything. put exit($msg); at the end of the code and see what happens.
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.
I'm just a PHP starter and now I want to learn JQUERY, on my learning process I practice on validating inputs usually I validate my inputs using a pure PHP code only and every time I validate the inputs the page reloads and now I want to improve in doing things I found some articles like http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.post/ (can't post other links) but I am more confused because they have different approach and I want to use the approach from the JQUERY tutorial but I haven't found any good tutorials and there is no tutorials on JQUERY's site that is using a database, usually I code like this:
<form method="post">
<label for="Username">Username:</label>
<input id="Username" type="text" name="username">
<?php
session_start();
if(isset($_SESSION['msg'])){
$msg=$_SESSION['msg'];
echo '<label for="Username">'.$msg.'</label>';
?>
<input type="submit" name="reg">
</form>
<?php
if(isset($_POST['reg'])){
$result=//check username from database here
if($result){
$_SESSION['msg']='username not available.';
}
else {
$_SESSION['msg']='username available.';
}
}
?>
Now I want to learn how can I validate inputs directly from the database without reloading the page? I don't know where should I start, what to add in my code. Any help, advice or suggestions will be really a big help for me :)
first, in your form add a onSubmit function
<form name='myform' type='POST' action='http://www.action.fr' onSubmit="return check_form()">
you can do this in ajax like that
function check_form()
{
var user = $('#Username').val(); // Username is the id of your input
var password = $('#password').val(); // password is the id of your input
$.ajax(
{
type:"POST", // or get as you want
url:"myfile.php", // it is the php file which can do the job
data: "user="+user+"&password="+password, // the param to send to your file,
success:function(msg)
{
;// msg is the result of your 'myfile.php', everything you write is in the msg var
}
});
}
in your php file you can get your data like this :
$user = $_POST['user'];
$password = $_POST['password'];
// if your type is get then use $_GET instead of $_POST
tell me if you have any problem with my code.
Write your validation script as though you're expecting a page refresh. Instead of outputting error messages, put them in a JSON array and print the JSON data. Then call the script from the AJAX function. It's really that simple.
<?php
// validate.php
$sampleInput_number = isset($_POST['sampleInput_number']) ? $_POST['sampleInput_number'] : "";
$errors = array();
if (trim($sampleInput_number) == "" || !is_numeric(trim($sampleInput_number)) {
$errors[] = "SampleInput_number must be a number!";
}
// sample input must also match a value from the database
if (!matchesDBValue($sampleInput_number)) {
$errors[] = "SampleInput_number must match a value from the database!";
}
function matchesDBValue($value) {
$retval = false;
// compare to db values here...
return $retval;
}
echo json_encode($errors);
Your form would look something like this:
<form action="" method="post" id="theForm">
<input type="text" name="sampleInput_number" id="sampleInput_number" />
<input type="button" id="formSubmit" value="Submit" />
</form>
And your javascript would look like this:
<script language="javascript" type="text/javascript">
$(#formSubmit).on("click", function() {
$.post("validate.php",
{
sampleInput_number: $("#sampleInput_number").val()
}, function(data) {
// check returned json data
// perform action based on results
if (no_errors) {
$("#theForm").submit();
}
}, "json"
);
});
</script>
Is it possible to trigger a PHP function by just clicking a link? Or should I stick with the form submit method? If clicking the link will work, where should the link refer to?
Here is a sample code:
<?php
session_start();
function listMe($username){
$username = mysql_real_escape_string($username);
$query = mysql_query("INSERT INTO List (Usernames) VALUES ('$username')") or die(mysql_error());
}
?>
<html>
<head>
<title>SAMPLE</title>
</head>
<body>
Add my username to the list
<?php
listMe($_SESSION['Username']);
?>
</body>
</html>
Maybe someone can point me in the right direction. Thanks!
You can do this by means of loading the entire page over again by the use of form submission, or by loading specific page contents directly into the page without needing to go from page to page. The second method is called "AJAX" (Asynchoronous Javascript and XML). Here are two examples, one of each specified.
Form submission approach
form.php
<?php
function get_users(){
}
if(isset($_GET['get_users']))
{
get_users();
}
?>
...
<form method="get">
<input type="hidden" name="get_users">
<input type="submit">
</form>
AJAX approach
ajax_file.php
<?php
function call_me(){
// your php code
}
call_me();
?>
form.html
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
// do something if the page loaded successfully
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
click to call function
</body>
</html>
HTML
list me
PHP
<?php
if (isset($_GET['list_me'])) listMe();
(EDIT although this works, it's a bad idea as it is. One should never read from $_GET without sanitising it first)
You can pass it as a query parameter of the link.
http://example.com/?command=listMe&username=tom
However that way everybody will be able to run the function by loading that URL
List me
and in the PHP
<?php
if( isset($_GET['list_me']) && isset($_SESSION['Username'] ) ){
listMe( $_SESSION['Username'] );
}
?>
To trigger a function on link click with php the only way I know would be to append a param in the url of the link and then listen for that
Add my username to the list
Then check for link
if (isset($_GET['function'])){
runFunction();
}
This is because php is a server side technology if you want to fire something without refreshing the page you would need to look at something like javascript
I found this code in a plugin, they have user a foreach look to trigger the action:
$actions = unset($meta[$key]);
foreach ( $actions as $action => $value ) {
echo '<li>' . '<i class="fa fa-times"></i></li>';
}
In this basic jQuery, AJAX, PHP form I want to display errors next to inputs instead of the bottom of the form. I use if(empty(something)) { jQuery here }. Why won't this work? Whats the best practice to do this? Thank you.
HTML:
Name:<input type="text" id="name" /> <span id="name_error"></span>
<input type="button" value="Update!" id="update" /> <span id="name_error"></span>
<span id="update_status"></span>
PHP
<?php
include('init.inc.php');
if(isset($_POST['name'])) {
$name = mysql_real_escape_string(htmlentities($_POST['name']));
if(empty($name)) {
?>
// Why wont this work here? It just outputs the the whole thing as text. in the update_status div (You can see that in the ajax part at the bottom of the code).
<script>
$('#name_error').text('Name required');
</script>
<?php
if(!empty($name)) {
$query = mysql_query("UPDATE users SET
name = '$name'
WHERE user_id = ".$_SESSION['user_id']."
");
if($query === true) {
echo 'Your settings have been saved';
} else if($query === false) {
echo 'Unable to save your settings';
}
}
}
// This is the jQuery / AJAX part -- no issues here. Just have it to include both parts.
$('#update').click(function() {
var name = $('#name').val();
$('#update_status').text('Loading...');
$.ajax({
type: 'POST',
url: 'page.php',
data: 'name='+name,
success: function(data) {
$('#update_status').text(data);
}
});
});
CODE UPDATED
Why aren't you checking for empty before the form submit?
You can stop the form submission and check for empty values with javascript, if all is clear then you can submit the form.
You can do this, but you are specifiying .text()
What you need to do is jQuery("#update_status").html(data);
jQuery("#update").click( function(){
if(jQuery.trim(jQuery("#name").val()) == ''){ alert("empty"); return false; }
jQuery.post("page.php", {name:jQuery("#name").val()}, function(html){
jQuery("#update_status").html(html);
});
});
Note that you PHP page is going to return more than just your intended code as it is now. It is going to try and return the form again also.
You need to wrap your processing and from in separate if/else statement. Better to put them in two separate files and keep ajax stuff separate.
That's a really bad way to do it. The reason it doesn't work is because that JavaScript needs to be parsed and run by the browser first, that's a whole different story and would involve using eval(). The better way to do it would be to send back a JSON object, then use it in your JavaScript to display the message to the user.