jeffreyb
jeffreyb

Reputation: 163

jquery ajax returning extra data

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??

Upvotes: 0

Views: 446

Answers (2)

jvk
jvk

Reputation: 2201

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

Upvotes: 0

Gautam Rai
Gautam Rai

Reputation: 2505

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);
  },
)};

Upvotes: 1

Related Questions