0

I have 2 ajax calls the first one that executes on change of #recipeName works but the second one(#resourceName) does not work. It seems it's not even going to my controller.

Javascript

<script type="text/javascript"> 
    $(document).ready(function (){
        $('#recipeName').change(function (){
            var recId = $(this).val(); 
            console.log(recId);

            $.ajax({
                url: "<?php echo base_url(); ?>" + "index.php/MainController/recipeDetails",
                async: false,
                type: "POST",
                data: "name="+recId,
                dataType: "json",

                success:(function(data) {
                    $('#makes').val(data[0]);
                    $('#type').val(data[1]);
                    console.log(data);
                })
            })
        });

        $('#resourceName').change(function (){
            var resId = $(this).val(); 
            console.log(resId);
            $.ajax({
                url: "<?php echo base_url(); ?>" + "index.php/MainController/resourceDetails",
                async: false,
                type: "POST",
                data: "resource="+resId,
                dataType: "json",

                success:(function(data) {
                    $('#rate').val(data[0]);
                    $('#per').val(data[1]);
                    console.log(data);})
                })
            });
        });
</script>

HTML

<select name="resourceName" id="resourceName" required>
    <option>Choose a resource</option>
    <?php if($resources != null){
        foreach($resources as $res){ ?>
        <option><?php echo $res->resource;?></option>
    <?php }}?>
</select>

My controller code is below. I even try to echo something out to see if the value gets passed to the controller but it doesn't echo anything.

public function resourceDetails() {
    $resource = $_POST['resource'];
    echo $resource . ' soe';
    $result = $this->MainModel->resourceDetails(trim($resource));
    if(isset($result)) {
        $rate = $result->rate;
        $per = $result->per;
        $values = array();
        $values[0] = $rate;
        $values[1] = $per;
        echo json_encode($values);
    }
}
JGallardo
  • 11,074
  • 10
  • 82
  • 96
geek2be
  • 29
  • 6
  • "does not work" isn't an error message or problem statement. We need debugging info. To start with, have you checked your browser's console and/or network tab to see what happens to the ajax request? What HTTP status is returned? Any messages in the console? – ADyson Sep 08 '17 at 15:04
  • @ADyson you are righ! – bjesua Sep 08 '17 at 15:06
  • Just as a side note, try changing the event to this `$('#resourceName').on('change', function() {...});`. Can you please also check the Network tab of Chrome DevTools and see if the request is at least going out? – Mithc Sep 08 '17 at 15:06
  • @Mithc that syntax change is functionally equivalent to the OP's. It's very unlikely to make any difference. the .change() method is just a shorthand for what you wrote. – ADyson Sep 08 '17 at 15:07
  • You have to get used to properly formatting your code for readability, it makes troubleshooting so much faster. – JGallardo Sep 08 '17 at 15:13
  • Also please stop using `async:false`. It serves no useful purpose in your code (because you're using callbacks properly) and provides bad user experience (it locks up the browser making it seem like it has crashed, if the request lasts longer than normal). It's also deprecated in several browsers so you can expect it to stop working in future. – ADyson Sep 08 '17 at 15:14
  • jQuery is only aware of the elements in the page at the time it runs, so new elements added to the DOM are unrecognized by jQuery. To combat the problem use [event delegation](http://learn.jquery.com/events/event-delegation/), bubbling events from newly added items up to a point in the DOM which was there when jQuery ran on page load. Many people use `document` as the place to catch the bubbled event, but it isn't necessary to go all the way up the DOM tree. Ideally [you should delegate to the nearest parent existing at the time of page load.](http://stackoverflow.com/a/12824698/1011527) – Jay Blanchard Sep 08 '17 at 15:17
  • @ADyson I have checked all that. There are no error messages on the console or any HTTP status returned. It seems like the second ajax request is not executed at all. – geek2be Sep 09 '17 at 09:02
  • If you put a console.log inside the "change" event, does it log anything when you choose an option? If not then it might well be the delegated event thing I described in my last comment. If it's not executing then potentially the event handler is declared before the element exists on the page. – ADyson Sep 10 '17 at 19:22

3 Answers3

0

You are making it hard on yourself, and not doing some things correctly. From the way you create your urls to the way you implement the success function, and also the way you post your data, your working too hard. You are also not trying to catch errors, and assume teh data will always be there. Consider this instead:

$(document).ready(function(){

    $(document).on('change', '#recipeName', function (){
        var recId = $(this).val(); 
        $.ajax({
            url: "<?php echo site_url('MainController/recipeDetails'); ?>",
            type: "POST",
            data: {
                'name': recId
            },
            dataType: "json",
            success: function(data) {
                if( data.makes && data.type ){
                    $('#makes').val(data.makes);
                    $('#type').val(data.type);
                }else{
                    alert('No makes or type');
                }
            },
            error: function(){
                alert('Problem with ajax 1');
            }
        })
    });

    $(document).on('change', '#resourceName', function (){
        var resId = $(this).val(); 
        $.ajax({
            url: "<?php echo site_url('MainController/resourceDetails'); ?>",
            type: "POST",
            data: {
                'resource': resId
            },
            dataType: "json",
            success: function(data) {
                if( data.rate && data.per ){
                    $('#rate').val(data.rate);
                    $('#per').val(data.per);
                }else{
                    alert('No rate or per');
                }
            },
            error: function(){
                alert('Problem with ajax 2');
            }
        });
    });

});

In MainController/recipeDetails you can and should pass back named elements:

echo json_encode(array(
    'makes' => '123',
    'type'  => '567'
));

In MainController/resourceDetails you can and should pass back named elements:

echo json_encode(array(
    'rate' => '987',
    'per'  => '654'
));

Also, in your controller, it seems like you will always have $result set. It might be better to check if it is empty, but it depends on the resourceDetails method in your MainModel.

I couldn't actually test this code, because I don't have your database or data. Let me know if it helps, or if you need some other help.

Brian Gottier
  • 4,522
  • 3
  • 21
  • 37
  • Brian I've tried this but it alerts me with the error message "problem with ajax 2" – geek2be Sep 09 '17 at 09:00
  • You might have a PHP error corrupting the response. Look in your web browser's developer console, on the net tab, and you will be able to see the raw response. It will give you a clue as to what is going on. – Brian Gottier Sep 09 '17 at 15:40
0

Try This and track

Script

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
  $(document).ready(function () {
    $('#recipeName').change(function () {
      var recId = $(this).val();
      console.log(recId);

      $.ajax({
        url: "<?php echo base_url(); ?>" + "index.php/MainController/recipeDetails",
        type: "POST",
        data: "name=" + recId,
        dataType: "json",

        success: (function (data) {
          $('#makes').html(data[0]);
          $('#type').html(data[1]);
          console.log(data);
        })
      })
    });

    $('#resourceName').change(function () {
      var resId = $(this).val();
      console.log(resId);
      $.ajax({
        url: "<?php echo base_url(); ?>" + "index.php/MainController/resourceDetails",
        type: "POST",
        data: "resource=" + resId,
        dataType: "json",

        success: (function (data) {
          $('#rate').html(data[0]);
          $('#per').html(data[1]);
          console.log(data);
        })
      })
    });
  });
</script>

HTML

recipeName:<select name="recipeName" id="recipeName" required>
      <option>Choose a resource</option>
      <option value="1">test 1</option>
      <option value="1">test 2</option>
      <option value="1">test 3</option>
    </select>
    <br>
   resourceName: <select name="resourceName" id="resourceName" required>
      <option>Choose a resource</option>
      <option value="1">test 1</option>
      <option value="1">test 2</option>
      <option value="1">test 3</option>
    </select>
  <br>
  <label id="makes">make : 1</label>
  <label id="type">2</label>
  <label id="rate">3</label>
  <label id="per">4</label>

Controller

public function recipeDetails() {
    echo json_encode(array(array("vijay"), array("sharma")));
    exit(0);
  }

  public function resourceDetails() {
    echo json_encode(array(array("ram"),array("sita")));
    exit(0);
  }

Change functions according your requirement

Vijay Sharma
  • 833
  • 8
  • 15
0

I tried out all the suggestions and code that were posted but they didn't work. I checked my code and realised I was echoing some statements in my controller and model just to test that the functions were being executed. Those echos were interfering with my echo json_encode($values); so my success function was not returning any values. Once I removed the other test echos my function was working as expected.

geek2be
  • 29
  • 6