Javascript – How to validate a sentence using PHP and JavaScript

javascriptphp

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?

Best Solution

You should quote the attribute and escape it properly:

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