Nahser Bakht
Nahser Bakht

Reputation: 930

PHP JSON does not work, can anyone tell me why?

myfile.php

header('Content-type: application/json');

echo json_encode( array( 'error' => 'jkfshdkfj hskjdfh skld hf.' ) );

the above code works.

but when I alter it it stops working:

if( isset( $_GET['customerID'] ) ){

       // do something else error

} else {

   header('Content-type: application/json');
   echo json_encode( array( 'error' => 'jkfshdkfj hskjdfh skld hf.' ) );

}

both outputs are correct:

{"error":"jkfshdkfj hskjdfh skld hf."}

but I get an ajax error:

myfile.phtml

        <?php 
            if( isset( $_GET['custID'] ) )
               echo "var custID = " . htmlentities( $_GET['custID'] ) . ";";                             
            else
               echo "var custID = null;";                             
        ?>

        $.ajax({

            url: 'php/viewCustomer.php',
            type: 'GET',
            data: {customerID: custID},
            dataType: 'json',
            cache: false,
            beforeSend: function(){

                $('#display').append('<div id="loader"> Lodaing ... </div>');

            },
            complete: function(){

                $('#loader').remove();

            },
            success: function( data ){

                if( data.error ) {

                    var errorMessage = "";

                    $.each( data, function( errorIndex, errorValue ){ 

                        errorMessage += errorValue + "\n";

                    });

                    alert( errorMessage );

                } else {

                    //$('div#customer-content table tr td').eq(0).text( '1234' );
                    //$('div#customer-content table tr td').eq(1).text( '1234' );
                    //$('div#customer-content table tr td').eq(2).text( '1234' );
                    //$('div#customer-content table tr td').eq(3).text( '1234' );
                    //$('div#customer-content table tr td').eq(4).text( '1234' );
                    alert( data );

                }                       

            },
            error: function( jqXHR ){

                alert( 'AJAX ERROR' );

            }

        });

    });

Upvotes: 1

Views: 106

Answers (1)

Tim Fountain
Tim Fountain

Reputation: 33148

From the comments it sounds like you are passing a null customerID and are not expecting it to go into the if condition. But even if the value is null, $_GET['customerID'] is still set. Change the check to empty() instead and it will work as you expect:

if( !empty( $_GET['customerID'] ) ){
    ....

Upvotes: 1

Related Questions