WonderLand
WonderLand

Reputation: 5674

Strange issue with Json & PHP

There is any reason why a json string fail to be evaluated (transport.responseText.evalJSON();) on the server but works on my local installation ?

I'm doing a simple ajax request like this one:

new Ajax.Request(
        this.saveUrl, {
            method: 'post',
            parameters: Form.serialize(this.form),
            onLoading: function () {
                totals.update('<div class="loading-ajax">&nbsp;</div>');
            },
            onSuccess: function (transport) {
                if (transport.status == 200) {
                    var data = transport.responseText.evalJSON();
                    totals.update(data.shipping_method);
                }
            },
            onFailure: checkout.ajaxFailure.bind(checkout)
        }
    );

On server side I output an array containing some html:

 $data = array(
            'shipping_method' => $shipping_method,
            'payment_method' => $payment_method
        );

echo json_encode($data);       

I have tried to valorize $total and '$other' as empty string '' but I get the same result: transport.responseText.evalJSON(); return an "unexpected token"

As said above the weird thing is that on my local it works ( the output is the same as the server but js doesn't trigger any error )

I'm struggling with this almost all day ... any help is really appreciate thanks

UPDATE:

console.log(transport.responseText) 
-> {"shipping_method":"","payment_method":""}

Inspecting the server response 'network tab' in chrome I can see a small difference, in comparison to my local: there is a small red dot before the response content if ( is say \ufeff if I move the mouse over it, I'm not sure about the meaning ... )

enter image description here

Upvotes: 2

Views: 2949

Answers (2)

WonderLand
WonderLand

Reputation: 5674

After some test I found out that the issue is encoding used in some PHP files, my co-worked had the brilliant idea to switch to ANSI. (ISO-8859)

For some reason these files coded with ANSI produced JSON content to be different:

  • chrome inspector was showing a red dot -> Byte_order_mark \ufeff character (aka BOM)

This probably means the BOM character is missing and this was breaking the json parse.

SOLUTION:

After I parsed and cleaned all my project files from the BOM character, chrome doesn't show the red dot in the inspector and the issue is gone

Still it is not clear why on my local installation the issue was not present while on the server it was ( both linux ) but there are probably multiple settings involved here ...

To clean your files see: Elegant way to search for UTF-8 files with BOM?

Upvotes: 3

manish
manish

Reputation: 68

you can use map function to evaluate json value

       $.map(transport, function (item){    
 totals.update(item.total);;
       });

I think its Working fine

Upvotes: 0

Related Questions