0

I need help for my code as i have been browsing the internet looking for the answer for my problem but still can get the answer that can solve my problem. I am kind of new using AJAX. I want to display data from json_encode in php file to my AJAX so that the AJAX can pass it to the textbox in the HTML.

My problem is Json_encode in php file have data from the query in json format but when i pass it to ajax success, function(users) is empty. Console.log also empty array. I have tried use JSON.parse but still i got something wrong in my code as the users itself is empty. Please any help would be much appreciated. Thank you.

car_detail.js

    $(document).ready(function() {


        function $_GET(q,s) {
            s = (s) ? s : window.location.search;
            var re = new RegExp('&'+q+'=([^&]*)','i');
            return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
        }
            var car_rent_id1 = $_GET('car_rent_id');
            car_rent_id.value = car_rent_id1;

                    $.ajax({  
        type: 'POST',
        url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
        dataType: "json",
        cache: false, 
        data: { car_rent_id: this.car_rent_id1 },
        success:  function(users) {

        console.log(users);
        $('#car_name').val(users.car_name); 

        }
    });
    });

car_detail.php

    $car_rent_id = $_GET['car_rent_id'];   
    $query = mysql_query("SELECT c.car_name, c.car_type, c.car_colour, 
    c.plate_no, c.rate_car_hour, c.rate_car_day, c.car_status, 
    r.pickup_location
    FROM car_rent c
    JOIN rental r ON c.car_rent_id=r.car_rent_id
    WHERE c.car_rent_id = $car_rent_id");

    $users = array();
      while($r = mysql_fetch_array($query)){
    $user = array(
        "car_name" => $r['car_name'], 
        "car_type" => $r['car_type'], 
        "car_colour" => $r['car_colour'], 
        "plate_no" => $r['plate_no'], 
        "rate_car_hour" => $r['rate_car_hour'], 
        "rate_car_day" => $r['rate_car_day'], 
        "car_status" => $r['car_status'], 
        "pickup_location" => $r['pickup_location']
        );
         $users[] = $user;
    // print_r($r);die;
    }
    print_r(json_encode($users)); //[{"car_name":"Saga","car_type":"Proton","car_colour":"Merah","plate_no":"WA2920C","rate_car_hour":"8","rate_car_day":"0","car_status":"","pickup_location":""}]

car_detail.html

  <label>ID:</label>
                <input type="text" name="car_rent_id" id="car_rent_id"><br>

                <label>Car Name:</label>
                <div class = "input-group input-group-sm">
                    <span class = "input-group-addon" id="sizing-addon3"></span>
                    <input type = "text" name="car_name" id="car_name" class = "form-control" placeholder = "Car Name" aria-describedby = "sizing-addon3">
                </div></br>

                <label>Car Type:</label>
                <div class = "input-group input-group-sm">
                    <span class = "input-group-addon" id="sizing-addon3"></span>
                    <input type = "text" name="car_type" id="car_type" class = "form-control" placeholder = "Car Type" aria-describedby = "sizing-addon3">
                </div></br>
17
  • Duplicating this line data: { car_rent_id: this.car_rent_id1 }, wont help! Commented May 16, 2017 at 16:16
  • 2
    Also, you've got ); after your success() method that doesn't look like it should be there. Commented May 16, 2017 at 16:19
  • You forgot to close the $.ajax(), your code is full of syntax errors Commented May 16, 2017 at 16:22
  • @RiggsFolly. Thank you for the reply. Actually i have use that line to get an id from the url, pass to the php to make a query. I am using GET method for that purpose. Then the query value will pass back to the json to be display in the textbox in html. Is my way wrong? Commented May 16, 2017 at 16:24
  • 1
    @Luqman305 learn to accept answers, I have seen your passed questions you don't accept answers, when you feel that an answer has solved your problem, accept it as it will help other people in the future. Commented May 16, 2017 at 17:29

3 Answers 3

2

Remove this in this.car_rent_id1 and cache: false this works with HEAD and GET, in your AJAX you are using POST but in your PHP you use $_GET. And car_rent_id is not defined, your function $_GET(q,s) requires two parameters and only one is passed.

$(document).ready(function() {
    function $_GET(q,s) {
        s = (s) ? s : window.location.search;
        var re = new RegExp('&amp;'+q+'=([^&amp;]*)','i');
        return (s=s.replace(/^\?/,'&amp;').match(re)) ?s=s[1] :s='';
    }
    var car_rent_id1 = $_GET('car_rent_id'); // missing parameter
    car_rent_id.value = car_rent_id1; // where was this declared?

    $.ajax({
        type: 'POST',
        url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
        dataType: "json",
        data: { car_rent_id: car_rent_id1 },
        success:  function(users) {
            console.log(users);
            $('#car_name').val(users.car_name);
        }
    });
});

You can also use $.post(), post is just a shorthand for $.ajax()

$(document).ready(function() {
    function $_GET(q,s) {
        s = (s) ? s : window.location.search;
        var re = new RegExp('&amp;'+q+'=([^&amp;]*)','i');
        return (s=s.replace(/^\?/,'&amp;').match(re)) ?s=s[1] :s='';
    }
    var car_rent_id1 = $_GET('car_rent_id');
    car_rent_id.value = car_rent_id1;

    $.post('http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php', { car_rent_id: car_rent_id1 }, function (users) {
        console.log(users);
        $('#car_name').val(users.car_name);
    });
});

and in your PHP change

$car_rent_id = $_GET['car_rent_id']; 

to

$car_rent_id = $_POST['car_rent_id'];
Sign up to request clarification or add additional context in comments.

1 Comment

thankssss!!! I have change according to your suggestion and it works now.
0

Here is a code skeleton using .done/.fail/.always

<script
  src="https://code.jquery.com/jquery-1.12.4.min.js"
  integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
  crossorigin="anonymous"></script>

<script>
$(function(){
  $.ajax({
    url: 'theurl',
    dataType: 'json',
    cache: false
  }).done(function(data){
    console.log(data);
  }).fail(function(data){
    console.log(data);
  }).always(function(data){
    console.log(data);
  });
});
</script>

I've adapted your code, so you can see the error, replace the ajax call with this one

<script>
    $.ajax({
      url: "theurl",
      dataType: "json",
      data: { car_rent_id: car_rent_id1 },
      success: function(users) {
        console.log(users);
        $('#car_name').val(users.car_name);
      },
      error: function(data) {
        console.log(data);
        alert("I failed, even though the server is giving a 200 response header, I can't read your json.");
      }
    });
</script>

3 Comments

There's difference between $.ajax({}).success(function(){...}); and $.ajax({success: fun...})
Thank you. I'm aware of that. I'm giving him the non-deprecated code skeleton to build from.
I just googled this and you're correct. Thank you. stackoverflow.com/questions/15821141/…
0

A couple of recommendations on this, I would follow jQuery API to try an see where the request is failing http://api.jquery.com/jquery.ajax/. Also, I would access the ids for the input fileds with jQuery. e.g.: $("#theID").val().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.