Lynds85
Lynds85

Reputation:

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?

Upvotes: 0

Views: 645

Answers (3)

Dave
Dave

Reputation: 185

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);
}

Upvotes: 1

Greg
Greg

Reputation: 321786

You should quote the attribute and escape it properly:

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

Upvotes: 1

Nir
Nir

Reputation: 25369

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.

Upvotes: 0

Related Questions