0

I want to send an array via $.ajax to a PHP Script.

<?php
$arrid=array("a","b","c","d","e","f");
?>

<script src="jquery.js"></script>
<script>
    var request = $.ajax({
      url: 'paidmail.php',
      dataType: 'json',
      data: 'id=<?php print_r($arrid); ?>',
      success: function(data) {
        console.log(data);
      }
    });
</script>

paidmail.php just echo out the id. But my Console always throws this Exception:

unterminated string literal

How is it possible to send an array via $.ajax to another PHP script?

0

3 Answers 3

2

print_r() returns a string, which will contain Javascript meta characters, particularly the single quote ', which will cause syntax errors. Instead of print_r, use json_encode(), which will transform a PHP array into a syntactically valid Javascript data structure.

  data: 'id=<?php echo json_encode($arrid); ?>',
Sign up to request clarification or add additional context in comments.

Comments

1

Replace:

data: 'id=<?php print_r($arrid); ?>'

with:

data: {id: <?php echo json_encode($arrid);?>}

Comments

0

Marc, don't you also want to utf-8 encode?

data: 'id=<?php echo json_encode(array_map('utf8_encode' , $arrid)); ?>',

And you should probably also use POST instead of GET:

type: "POST"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.