Javascript – How to 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:


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


function formSubmit(correct)
var contents = document.getElementById('sentenceBuilder').value;

    alert('The Sentences Match');
    alert('The Sentences Dont Match');


Any ideas how I can solve this?

Best Solution

You should quote the attribute and escape it properly:

echo '<... onClick="formSubmit(' . htmlspecialchars(json_encode($rebuiltSentence)) . ');">'