javascript - PHP json_encode add a 1 to the end of the string - Stack Overflow

admin2025-04-20  0

I'm using json_encode throughout my project without issue, except in one instance.

I make an ajax call from one page, as I do in others, and the resulting json appends a 1 to the end of the string for some odd reason.

My return string looks like this

{
"overtime": "yes"
}1

What could be causing this? I have literally mented everything out of the class that returns this string and I simply have the following code.

$reservation = ['overtime' => 'yes'];
return json_encode($reservation, JSON_PRETTY_PRINT);

My ajax request looks like this

    $.ajax({
        type: 'POST',
        url: "{{ URL::action('Controllers\\PurchasesController@calculateReservation') }}",
        data: { 'arrive' : arrive, 'depart' : depart},
        dataType: 'json',
        success: function(response) {
            alert(response);
        }
    });

The alert doesn't fire and doesn't display anything as the json is invalid with the 1 appended to the end of the string.

I'm using json_encode throughout my project without issue, except in one instance.

I make an ajax call from one page, as I do in others, and the resulting json appends a 1 to the end of the string for some odd reason.

My return string looks like this

{
"overtime": "yes"
}1

What could be causing this? I have literally mented everything out of the class that returns this string and I simply have the following code.

$reservation = ['overtime' => 'yes'];
return json_encode($reservation, JSON_PRETTY_PRINT);

My ajax request looks like this

    $.ajax({
        type: 'POST',
        url: "{{ URL::action('Controllers\\PurchasesController@calculateReservation') }}",
        data: { 'arrive' : arrive, 'depart' : depart},
        dataType: 'json',
        success: function(response) {
            alert(response);
        }
    });

The alert doesn't fire and doesn't display anything as the json is invalid with the 1 appended to the end of the string.

Share Improve this question edited Mar 25, 2015 at 18:23 Joshua asked Mar 25, 2015 at 18:20 JoshuaJoshua 7919 silver badges24 bronze badges 2
  • 1 In my experience, I normally echo a response, rather than return it. Try doing that and if necessary, calling die() immediately afterwards. Does that help? – Tom Fenech Commented Mar 25, 2015 at 18:23
  • Wow. Yes, that did the trick, thank you! Very odd as I simply return the json_encode throughout the rest of my project without any issue. – Joshua Commented Mar 25, 2015 at 18:25
Add a ment  | 

1 Answer 1

Reset to default 9

You should echo the response from your controller, rather than returning it:

echo json_encode($reservation, JSON_PRETTY_PRINT);

In some scenarios (for example using WordPress), it is also necessary to call die() afterwards, as well.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745081227a283871.html

最新回复(0)