user2170838
user2170838

Reputation: 47

I don't understand AJAX callbacks

I have a javascript function which executes on the change of a dropdown:

    <script type="text/javascript">
        $(function()
        {
            // Executes when the status dropdown changes value
            $('select[name="status_dropdown"]').change(function(event)
            {
                var $this = $(event.target);
                var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table

                var result = null;
                var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;

                $.ajax(
                {
                    url: scriptUrl,
                    type: 'get',
                    dataType: 'html',
                    async: false,
                    success: function(data)
                    {
                       result = data;
                       alert(result);
                   }
                });
            });
        })
    </script>

I am trying to get the alert call to show the return value of the following php code (which is true):

    <?php
        .
        .
        .

        return true;
    ?>

The alert doesn't pop up. Anyone know why ???

Upvotes: 0

Views: 151

Answers (3)

S&#233;bastien
S&#233;bastien

Reputation: 1053

I tried your code with another URL and it's working well. There are three cases:

  • scriptUrl is not calculated properly and doesn't point to your PHP script
  • your server is down
  • you are accessing an URL not served under the same domain as the one of your script (same-origin policy)

You can see detail of your error if you add an error handler to ajax parameters :

error : function(jqXHR, textStatus, errorThrown) {
    alert(errorThrown);
}

Upvotes: 2

iJade
iJade

Reputation: 23811

Try this

$(document).ready(function(){
    $('select[name="status_dropdown"]').change(function(event)
        {
            var $this = $(event.target);
            var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table

            var result = null;
            var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;

            $.ajax(
            {
                url: scriptUrl,
                type: 'get',
                dataType: 'html',
                async: false,
                success: function(data)
                {
                   result = data;
                   alert(result);
               }
            });
        });
});

Upvotes: -1

Kevin Pei
Kevin Pei

Reputation: 5872

Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");

Upvotes: 1

Related Questions