-1

I was working on project in which I have to get some text from the database and display it in the text area. Working fine with no line breaks and tabs. but when a line breaks occurs it gives the error

Uncaught SyntaxError: Invalid or unexpected token

My java script code is as :

<script type="application/javascript">


$(document).ready(function () {


    document.getElementById('job_type').value = "<?php echo set_value('job_type') ?>";
    document.getElementById('job_cat').value = "<?php echo set_value('job_cat') ?>";

    if("<?php if(validation_errors() == false) echo "false"; else echo "true"; ?>"=="false")
    {
        $('#job_title').val("<?php echo $job[0]->job_title ?>");
        $('#job_type').val("<?php echo $job[0]->job_type ?>");
        $('#job_cat').val("<?php echo $job[0]->job_cat ?>");
        $('#salary').val("<?php echo $job[0]->salery ?>");
        $('#job_descp').text("<?php echo $job[0]->job_desc ?>");//error here



    }


    });


});


</script>

The text it was trying to set was

Error details are shown in images

Debug info

I have tried using .html() and .val() too but nothing worked. How can I handle it.

Alex
  • 878
  • 1
  • 10
  • 25
Arsii Rasheed
  • 324
  • 1
  • 5
  • 18

2 Answers2

1

This has already been answered here https://stackoverflow.com/a/4270709/3004335

However, you can use json_encode

<script type="application/javascript">
$(document).ready(function () {
    document.getElementById('job_type').value = "<?php echo set_value('job_type') ?>";
    document.getElementById('job_cat').value = "<?php echo set_value('job_cat') ?>";

    if("<?php if(validation_errors() == false) echo "false"; else echo "true"; ?>"=="false")
    {
        $('#job_title').val(<?php echo json_encode($job[0]->job_title); ?>);
        $('#job_type').val(<?php echo json_encode($job[0]->job_type); ?>);
        $('#job_cat').val(<?php echo json_encode($job[0]->job_cat); ?>);
        $('#salary').val(<?php echo json_encode($job[0]->salery); ?>);
        $('#job_descp').text(<?php echo json_encode($job[0]->job_desc); ?>);//error here
    }
    });
});
</script>

You do however need to be careful about cross site scripting

See here https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet in particular rule #0

MC57
  • 329
  • 1
  • 5
0

Remove line break(CR LF) in job[0]->job_desc like this:

$('#job_descp').text("<?php echo str_replace (array("\r\n", "\n", "\r"), '<br>', $job[0]->job_desc);?>");
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17