2

I really don't know what i'm missing here. I have this script:

        <script type="text/javascript">
            function ServiceOffer(){
                var service_name  = $('#service_name').val(),
                    dataString = "service="  + service_name;
                    $.ajax({
                        type: "POST",
                        url:  "posted.php",
                        data:dataString,
                        success:function(data){
                            console.log(data);
                        }
                    });
            }

            $(document).ready(function(){   
                ServiceOffer();

                $(document).on('change','#service_name',function(){
                    ServiceOffer();                 
                });     
            });
        </script>

And here is my code for posted.php

    <?php

        $connect = mysql_connect('localhost','root','') or die('Unable to connect'.mysql_error());
        $select = mysql_select_db('hcs',$connect) or die('Unable to select database'.mysql_error());
        $service = $_POST['service'];

        $query = mysql_query("SELECT * FROM serviceoffer WHERE servicename = '$service'");
        $num = mysql_num_rows($query);  

        while($rows = mysql_fetch_array($query)){
            $data[] = $rows;
        }
        echo json_encode($data);

So what i'm missing? I don't think there is a string that is being attached in my code and it gives me string in my console and not json encoded data. Please Help! Thanks!

Edit: Here is the data that is being returned in my console.

enter image description here

leonardeveloper
  • 205
  • 2
  • 4
  • 12
  • What is not working how? What does the result look like? – Pekka Dec 12 '13 at 00:59
  • 2
    In PHP set json header, in JS ajax call set `dataType` to `json`. Other than that, you should learn to debug requests and responses... – Glavić Dec 12 '13 at 01:00
  • 1
    It may just be that `$data` is empty. You should declare it outside of the while loop to ensure it's in scope. Check your error output. The issue is most likely your server-side code. – Brian Poole Dec 12 '13 at 01:02
  • @shirejedi PHP uses function scope, not block scope. – Barmar Dec 12 '13 at 01:06
  • Why oh why are you using the `mysql_*` functions? Unless this is some *really old* legacy code or you've been living under a rock for the last 10 years, you should know that the MySQL extension is unmaintained and now officially deprecated. If you're following some tutorial, please check the published date and think hard about the phrase *current technology*. – Phil Dec 12 '13 at 01:09
  • @Barmar I think they mean so `$data` is defined *after* the loop. – Phil Dec 12 '13 at 01:15
  • It works fine even if i don't initialize the like `$data=array()`. I use `mysql_* functions` because this one is my friends project and I just need to do it the same way. – leonardeveloper Dec 12 '13 at 01:20
  • 1
    @Barmar, as it stands, `$data` would be undefined if the query returned no results. What I was getting at and what Phil clarified for me is `$data` should be defined before (or outside of) the while loop. To me, this was a glaring issue that could have resulted in returning a result that wouldn't be valid JSON as it would contain a PHP notice. Again, this is if the result was empty. – Brian Poole Dec 12 '13 at 02:03
  • That's not a scope issue, it's an uninitialized variable issue. I agree that it's always a good idea to initialize your variables properly. – Barmar Dec 12 '13 at 02:10
  • @leonardeveloper It won't *work fine* if there's no results for the provided service name. Also, tell your friend to get with the times – Phil Dec 12 '13 at 03:03

2 Answers2

3

You have three options:

  1. Add dataType: 'json' to the options in $.ajax.
  2. Add header("Content-type: application/json"); to the PHP code.
  3. Use console.log($.parseJSON(data)) in the success function.

Note that you shouldn't use option 3 if you've also used options 1 or 2. jQuery automatically parses the JSON in the first two cases, and you'll try to parse the result of that, which won't work.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

At a minimum, you should send the appropriate header in PHP, eg

header('Content-type: application/json');
echo json_encode($data);
exit;

You can also set the dataType in jQuery's $.ajax method to specify the expected response type. I also find it easier to send request parameters as object literals (saves having to build URL encoded strings), eg

$.ajax({
    type: 'POST',
    dataType: 'json',
    data: { service: service_name },
    //etc

Update

As shirejedi mentioned, you should initialise $data as an array

$data = array();
while($rows = mysql_fetch_array($query)){
    $data[] = $rows;
}
Community
  • 1
  • 1
Phil
  • 157,677
  • 23
  • 242
  • 245