Wednesday, April 13, 2011

How can I validate a sentence using PHP and JavaScript?

I am currently trying to validate if the sentence a user enters matches the expected sentence. The expected sentence is stored in a PHP variable $rebuiltSentence, for example 'the cat sat'.

The problem is that when I try to call my JavaScript function formSubmit() I need to give it the sentence to check, therefore ideally I would call formSubmit($rebuiltSentence). I think this won't work because it thinks it is being passed several separate strings.

Here is what I've got:

//sentence.php

<input type='button' value='Submit' onClick=formSubmit('$rebuiltSentence')

and

//validate.js
function formSubmit(correct)
{
var contents = document.getElementById('sentenceBuilder').value;
if(contents==correct){

 alert('The Sentences Match');
}else{
 alert('The Sentences Dont Match');
}

window.location.reload(true);
}

Any ideas how I can solve this?

From stackoverflow
  • It looks like you are passing the string $rebuiltSentence rather than the sentence that this parameter holds in PHP.

    Change to the follwoing

    //sentence.php

    echo "<input type='button' value='Submit' onClick=formSubmit('".$rebuiltSentence."')";
    

    and it will echo the content of $rebuiltSentence.

    Greg : This won't work if $rebuiltSentence contains a single quote, and won't be right if it contains, e.g. an ampersand.
  • You should quote the attribute and escape it properly:

    echo '<... onClick="formSubmit(' . htmlspecialchars(json_encode($rebuiltSentence)) . ');">'
    
  • You could add the sentence as a hidden field to validate against.

    //sentence.php
    
    <input type='hidden' id=rebuiltSentence value='$rebuildSentence'>
    <input type='button' value='Submit' onClick=formSubmit()>
    

    and to validate you could then easily use

    //validate.js
    function formSubmit()
    {
      var contents = document.getElementById('sentenceBuilder').value;
      var correct  = document.getElementById('rebuiltSentence').value;
      if(contents==correct)
      {
        alert('The Sentences Match');
      }else{
        alert('The Sentences Dont Match');
      }
    
      window.location.reload(true);
    }
    

0 comments:

Post a Comment