0
votes

Using json_encode($phpArray); to send data back to my javascript. The problem is in javascript there's extra data added to the beginning. Below are simplified examples of my files that still demonstrate the problem.

days.php:

<?php
$phpArray = array(
  0 => "Mon",
  1 => "Tue",
  2 => "Wed",
  3 => "Thu",
  4 => "Fri",
  5 => "Sat",
  6 => "Sun",
);
echo json_encode($phpArray);

processDays.js:

$.ajax({
  url: 'days.php',
  success: function(response) {
    console.log(response);
  },
)};

I'm expecting to get (which I get if I just run the php file on it's own):
["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]

But I'm getting:
22["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]

Where is this 22 coming from??

2
"Where is this 22 coming from?" Code (or raw text outside of any <?php ... ?> section) in your PHP file prior to the code you've shown. Neither echo nor json_encode is broken (search for "broken" on this page for an explanation of that). Voting to close as typo / non-repro. - T.J. Crowder

2 Answers

1
votes

you should also add datatype for ajax call, if want to get response in json add datatype as json, as below,

$.ajax({
  url: 'days.php',
 dataType: "json", 
  success: function(response) {
    console.log(response);
  },
)};
0
votes

when you are using json you should declare dataType:"JSON" in ajax