sdf
sdf

Reputation: 21

error while using single quote in the value and gets done when no single quote is used in datatable

i'm trying to make a call to the file using ajax using the following code

var text = '<?php echo urlencode("hello world"); ?>';

var dataTable = $("#datatable-pan").DataTable({
  "ordering": false,
  "searching": false,
  "bProcessing": true,
  "serverSide": true,
  "ajax":{
    url :'my_response.php?text='+text, // json datasource
    type: "POST",  // type of method  ,GET/POST/DELETE
    error: function(){
      $("#employee_grid_processing").css("display","none");
    }
  },
});

This works fine but if i change the value of var text to

var text = '<?php echo urlencode("hello 'world'"); ?>';

it doesn't proceed and does not call the file it shows something like xhr error

Upvotes: 2

Views: 207

Answers (2)

Gratien Asimbahwe
Gratien Asimbahwe

Reputation: 1614

This works fine but if i change the value of var text to

var text = '<?php echo urlencode("hello 'world'"); ?>';

it doesn't proceed and does not call the file it shows something like xhr error

it can not work that way. since your php script is wrapped under single quotes, the next single quote that will be found within the statement will be considered as the end of the instruction and all other characters will be considered as unexpected and though may throw a SyntaxError.

If world is variable and you want to display its value you can do this:

var text = '<?php echo urlencode("hello $world"); ?>';

or var text = '<?php echo urlencode("hello ".$world); ?>';

And that will work using php inside a javascript script. You can also escape the quotes using \ this way:

var text = '<?php echo urlencode("hello \'world\'"); ?>'; here single quotes will be considered as part of the string to encode and not limiters.

Upvotes: 0

JS:

var text = encodeURIComponent('<?php echo urlencode("hello world"); ?>');

PHP:

$code = urldecode( $_POST['text']);

Last string:

var text = '<?php echo urlencode("hello \'world\'"); ?>';

Upvotes: 1

Related Questions