admin管理员组

文章数量:1323502

The below code is to create a campaign. Before creation, I have to validate the form. I have to validate the campaign name which is already existed in database or not. I don't know whether I can use PHP code inside javascript (like below).Anyway it's not working. How can I change my code? How can I validate values with database values?

$this->campaign is an array which contain all campaign details from database.

<script type="text/JavaScript">
function validate()
{
var name = document.getElementById('name').value;
var shape = document.getElementById('shape').value;
     <?
     foreach($this->campaign as $c)
     {
     $old_cname=$c['name'];
     ?>
        if(name==<?=$old_cname;?>)
        {
            alert("same name exists in database. Try again!");
        }
    <?
    }
    ?>

if(!name)
{
    alert("Please enter a name!");

    return false;
}

if(!shape)
{
    alert("Please select shape!");
    return false;
}
    return true;


}
</script>


<form action="create.php" method="post" onsubmit="return(validate());">
Name:
<input type="text" name="name" id="name"/>
Shape:
<select name="shape" id="shape">
<option value="long">Long</option>
<option value="tall">Tall</option>
</select>
<input type="submit" value="Create" name="submit"/>
</form>

Thanks!

The below code is to create a campaign. Before creation, I have to validate the form. I have to validate the campaign name which is already existed in database or not. I don't know whether I can use PHP code inside javascript (like below).Anyway it's not working. How can I change my code? How can I validate values with database values?

$this->campaign is an array which contain all campaign details from database.

<script type="text/JavaScript">
function validate()
{
var name = document.getElementById('name').value;
var shape = document.getElementById('shape').value;
     <?
     foreach($this->campaign as $c)
     {
     $old_cname=$c['name'];
     ?>
        if(name==<?=$old_cname;?>)
        {
            alert("same name exists in database. Try again!");
        }
    <?
    }
    ?>

if(!name)
{
    alert("Please enter a name!");

    return false;
}

if(!shape)
{
    alert("Please select shape!");
    return false;
}
    return true;


}
</script>


<form action="create.php" method="post" onsubmit="return(validate());">
Name:
<input type="text" name="name" id="name"/>
Shape:
<select name="shape" id="shape">
<option value="long">Long</option>
<option value="tall">Tall</option>
</select>
<input type="submit" value="Create" name="submit"/>
</form>

Thanks!

Share asked Jul 31, 2012 at 1:03 ZendieZendie 1,1741 gold badge14 silver badges32 bronze badges 3
  • 2 You want to validate values entered by users? if that's is the case, I think you need to pass the values to the server side, perform the validation there and get the return value. I usually use ajax for that. – artsylar Commented Jul 31, 2012 at 1:11
  • Thank you for your valuable ment. yes, I want to validate values entered by users. I am new to ajax. If you don't mind could you please show me an example? – Zendie Commented Jul 31, 2012 at 1:30
  • 1 @Daedalus already posted a very good example of using ajax and jquery :) – artsylar Commented Jul 31, 2012 at 1:35
Add a ment  | 

2 Answers 2

Reset to default 4

You can't mix php and javascript like that.. php is a server-side language, while javascript is client-side; php renders the page before the user sees it, while javascript modifies the page without refreshing. Any php values in your js will get rendered and output before the js even executes.

In order to do what you need, you need to use ajax, which is asynchronous javascript and xml, a method of client-server munication that allows for what you want to happen.

To do this, I would suggest jQuery, a javascript library which makes such requests very simple. As an example of how you would make such a request in jquery....

The jQuery.ajax() method:

$.ajax({
    url: "validate.php",
    type: "POST",
    data: "username=" + username,
    sucesss: function(data) {
        if (data == 1)
            $("#ajax_div").html("Username is taken, choose another!");
        }
        else {
            $("#ajax_div").html("Username is free :)");
        }
    }
});

That would be how to do it in ajax, while your php file would either return a 1 or a 0 depending on the result of an sql query paring usernames in the database.

To do this without jquery, it would be something like this:

function checkUsername() {
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4) {
            if (xmlhttp.responseText == 1) {
                document.getElementById('ajax_div').innerHTML = "Username is taken, please choose another!";
            }
            else {
                document.getElementById('ajax_div').innerHTML = "Username is free :)";
            }
        }
    }
    xmlhttp.open("POST","validate.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("username=" + username);
    }
}

You should use jquery to validate using a php script. The best way to do this is to disable the submit button until all fields are verified. This requires that you to listen to keystrokes then make a jquery call to validate the input field. A simple example below

script.js

var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example

//on keyup, start the countdown
$('#myInput').keyup(function(){
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$('#myInput').keydown(function(){
    clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
  $.ajax({
      type: "POST",
      url: 'ajax/validate.php',
      data: 'cname='+$('#name').val(),
      success: function(data) {
         if(data == "original"))
           //enable the submit button
         else
          //Update your div that contains the results
      }
  });
}

ajax/validate.php

<?PHP
   //Run your validations here
?>

本文标签: phpjavascript validate form values from databaseStack Overflow