samedi 1 septembre 2018

Unable to populate a field w/ data containing ' (single quote, apostrophe) in JavaScript w/ Laravel and PHP

I am trying to populate a form field with some data from a database that contains a single quote. The data was stored in a MySQL database with PHP (and Laravel) using htmlentities() with the ENT_QUOTES option and I confirmed that the single quotes are converted to ' when saved in the database.

I can display this with no issues on my PHP page by echoing it out, but when I try to use javascript or jquery to populate the field, it does not work. I have tried .replace to substitute the ' with \' to escape the quote but I still had no luck. The field is called "note" and here is the relevant code, where $data represents the data as retrieved from the database:

<?php $data = "&#039;Twas The Night Before Christmas"; ?>
<form method="post" name="my_form">
  <input type="text" name="note" id="note" value="" /> 
  <input type="button" value="Edit" onclick="editNote('<?php echo $data; ?>')" />
  <!-- other elements here ... --> 
</form>

and here is my javascript:

//I have tried:
function editNote(data){
    $('#note').val(data);
}

//I also tried:
function editNote(note){
    var form = document.getElementById('my_form');
    form.note.value = data.replace(/&#039;/g, "\\'");
}

I also tried using PHP's addslashes() in my javascript call but that did not work either. I'm not sure why, but any data with &#039; is not escaped properly and so my field is not being populated. Data without single quotes is fine. Data with double quotes using &quot; is also fine. So now I'm stumped and I figured I'd reach out to the community for guidance. Any ideas as to what could be the cause? Did I miss something trivial? Any help would be appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire