P.Davide
P.Davide

Reputation: 379

jquery, json and success function

I have written this code, but I am not able to make it works as it should..:

<script>
$(document).ready(function(){
    $(document).on('click','.a_mod', function(e){
        e.preventDefault();
        var id =  $(this).attr('rel');
        var var_id = '<?php echo $id ?>';
        var data_3 = 'id=' + id + '&var_id=' + var_id;
        $.ajax({
            type: "POST",
            data: data_3,
            cache: false,
            dataType: 'json',
            url: "php/show_tariffa.php",
            success: function(html){
                var obj = jQuery.parseJSON(html);
                $.each(obj,function(index, element){

                var id = element.id;
                var prestazione = element.prestazione;
                var prezzo = element.prezzo;
                var check = element.prezzo_mult;

                $('#id_tariffa').val(id);
                $('#nome_2').val(prestazione);
                $('#prezzo_2').val(prezzo);
                }); // fine .each

                $('#box_2').slideUp();
                $('#box_3').slideDown().css({"border-color": "#F31041"},'fast');
                } // fine success
            }); // fine ajax
    });
});
</script>

Using Firefox and firebug I can see that the event starts and that the php script is executed but, I don't know why, the "success:" part of the ajax doesn't start at all..

Here there is the php script:

<?php

    include("connect.php");

    $id = $_POST['id'];                 // id
    $var_id = $_POST['var_id'];         // id_dentista

    $html = array();

    $query = mysql_query("SELECT
                            tariffe.id,
                            tariffe.prestazione,
                            tariffe.prezzo,
                            tariffe.prezzo_mult
                            FROM tariffe
                            WHERE tariffe.id_dentista = '$var_id' AND tariffe.id = '$id'")
                            or die(mysql_error());

    while( $row = mysql_fetch_array($query)){
        $html[] = $row;
    }

    echo json_encode($html);

?>  

What's wrong? what am I missing?

Thanks Davide,

Upvotes: 2

Views: 607

Answers (1)

Tech Savant
Tech Savant

Reputation: 3766

Update

After hours of troubleshooting in chatroom, I finally just installed this code on my server and set up the database. It works fine, the only issue was a BOM signature at the beginning of every file.

You need to set the encoding of your files to UTF8, not UTF8 BOM and you should be good. My guess is there is a BOM signature at the beginning of the returned data which is making $.parseJSON() mad.

Let me know if that fixes it, if not, it's back to the old drawing board.


If you are sure your query is successful, then add an error callback to your script (or use the delegate script below and its already added).

This should give you the reason why your script is erroring out.

error: function(xhr, status, error) {
    console.log(status);
    console.log(error);
    console.dir(xhr);

}

Also, I'm not sure about FF, but in Chrome, you can go to the Network tab and click on your ajax script. You can then view the data being sent, and the response. You are probably having an issue with datatype/contenttype.

enter image description here

enter image description here

Sidenote:

You should be delegating your AJAX calls to properly handle event bubbling.

You should also be validating your input and not accessing superglobal $_POST directly.

You should also not use PHP inside of JS. Instead create an element in your HTML and replace this ...

var var_id = '<?php echo $id ?>';

with this ...

HTML

<input id="hiddenId" type="hidden" value="<?php echo $id; ?>">

jQuery

var var_id = $("#hiddenId").val();

Delegate Ajax

(function($){
    $(function(){


        //Usage Example

        var inputString = $("#myInput").val();
        var inputNumber = $("#myInteger").val();
        var data = {inputString: inputString, inputNumber : inputNumber};

        $('parent').on('click', 'button', delegateAjax('js/myAjax.php', data, 'POST');

    });

    function delegateAjax(url, data, responseType, dataType, callback) {

        function successHandler() {
            console.log("Ajax Success");
        };

        function failureHandler(xhr, status, error) {
            console.log("Ajax Error");
            console.log(status);
            console.log(error);
            console.dir(xhr);
        };

        function handler404(xhr, status, error) {
            console.log("404 Error");
            console.log(status);
            console.log(error);
            console.dir(xhr);
        };

        function handler500(xhr, status, error) {
            console.log("500 Error");
            console.log(status);
            console.log(error);
            console.dir(xhr); 
        };

        url = typeof url !== 'undefined' ? url : 'js/ajaxDefault.php';
        data = typeof data !== 'undefined' ? data : new Object();
        responseType = typeof responseType !== 'undefined' ? responseType : 'GET';
        dataType = typeof dataType !== 'undefined' ? dataType : 'json';
        callback = typeof callback !== 'undefined' ? callback : 'callback';

        var jqxhr = $.ajax({url: url, type: responseType, cache: true, data: data, dataType: dataType, jsonp: callback, 
                            statusCode: { 404: handler404, 500: handler500 }});
        jqxhr.done(successHandler);
        jqxhr.fail(failureHandler);
    };
})(jQuery); 

Correctly Validate/Sanitize Input

$args = array(
    'inputString' => array(
        'filter' => FILTER_SANITIZE_STRING,
        'flags' => FILTER_REQUIRE_SCALAR
    ),
    'inputNumber' => array(
        'filter' => FILTER_VALIDATE_INT,
        'flags' => FILTER_REQUIRE_SCALAR
    ),
    'inputNumber2' => array(
        'filter' => FILTER_VALIDATE_INT,
        'flags' => FILTER_REQUIRE_SCALAR
    )
);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {


        $response = array('status' => 'success');
        echo json_encode($response); exit;
}

Upvotes: 2

Related Questions