CodeIgniter Forums
Access ajax data from the function and use it outside CI3 - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Access ajax data from the function and use it outside CI3 (/showthread.php?tid=87468)



Access ajax data from the function and use it outside CI3 - janeiro - 04-23-2023

I'd like to add selected attribute to subcategory field in my form using ajax.
Code below gets data about the book and the other populates subcategory field in form.

How to access data from function edit_book so I could use it outside?
I'm trying to find the solution for 8 hours now experimenting...

PHP Code:
/*populate subcats field on cat field change*/
$('#book_cat').change(function(){
    var subcat_id = $(this).val();
    $("#book_subcat > option").remove();
    $.ajax({
        type"POST",
        url"<?php echo site_url('book/populate_subcats'); ?>",//controller
        data: {idsubcat_id},
        dataType'json',
        success:function(data){
            $.each(data,function(kv){
                var opt = $('<option />');
                opt.val(k);
                opt.text(v);
                $('#book_subcat').append(opt);
            });
        }
    });
});
//get book data
  function edit_book(id) {
    save_method 'update';
    $('#form')[0].reset(); // reset form on modals
    $.ajax({ //Load data from ajax
      url"<?php echo site_url('book/get_row/') ?>" id,
      type"GET",
      dataType"JSON",
      success: function(data) {
        $('[name="book_cat"]').val(data.book_cat).trigger('change'); //new
        $('[name="book_subcat"]').val(data.book_subcat).trigger('change'); //new
      },
      error: function(jqXHRtextStatuserrorThrown) {
        alert('Error get data from ajax');
      }
    })
  }

//CONTROLLER FILE:
  /*******************************************************************/
  public function get_row$id ) {
    $data $this->model->get_row$id );
    echo json_encode$data );
  }
  /*******************************************************************/
  function populate_subcats() {
    $id $this->input->post'id' );
    echo( json_encode$this->model->get_subcats$id ) ) );
  }

//MODEL FILE:
  public function get_row$id ) {
    $this->db->from$this->table );
    $this->db->where$this->field_id$id );
    $query $this->db->get();
    return $query->row();
  }
  /*******************************************************************/
  function get_cats() {
    $result $this->db->get'book_cats' )->result();
    $id = array( '0' );
    $name = array( '-' );
    for ( $i 0$i count$result ); $i++ ) {
      array_push$id$result$i ]->cat_id );
      array_push$name$result$i ]->cat_name );
    }
    return array_combine$id$name );
  }
  /*******************************************************************/
  function get_subcats$cid NULL ) {
    $result $this->db->where'parent_id'$cid )->get'book_subcats' )->result();
    $id = array( '0' );
    $name = array( '-' );
    for ( $i 0$i count$result ); $i++ ) {
      array_push$id$result$i ]->subcat_id );
      array_push$name$result$i ]->subcat_name );
    }
    return array_combine$id$name );
  }



//Database structure:
TABLE `books` (
`
book_id
`
book_cat` = refers to table book_cats
`book_subcat`  refers to table book_subcats)
 
TABLE `book_cats` (
`
cat_id
`
cat_name`

TABLE `book_subcats` (
`
subcat_id`
`
subcat_name`
`
parent_id` = refers to table book_cats



RE: Access ajax data from the function and use it outside CI3 - SubrataJ - 04-23-2023

What do you mean by "access data from function edit_book", you want to use the response of this function outside, once the Ajax request is complete?


RE: Access ajax data from the function and use it outside CI3 - InsiteFX - 04-23-2023

You need to use 
Code:
jQuery.parseJSON( json )



RE: Access ajax data from the function and use it outside CI3 - SubrataJ - 04-23-2023

(04-23-2023, 10:30 PM)InsiteFX Wrote: You need to use 
Code:
jQuery.parseJSON( json )

pardon me for any mistakes, but he is using dataType: "JSON", is it really required to parse the data again?


RE: Access ajax data from the function and use it outside CI3 - demyr - 04-24-2023

Hi. You can get results from your get_row controller method and display the result in another view file. For example,

Code:
Controller:

public function get_towns_of_a_city(){
        $city_id = $this->request->getVar('city_id');
        $data['towns'] = $this->YourModel->get_towns_of_a_city($city_id);

      echo view('site-view/data-area/towns-result', $data);
    }


Then you can use it after any Ajax call. For example,

Code:
<script type="text/javascript">
    $(document).ready(function(){
        $('#city-select').change(function(){
            let city_id = $(this).val();

            $.ajax({
            url:"<?php echo base_url('SiteController/get_towns_of_a_city');?>",
            method:'POST',
            data:{city_id:city_id},
            success: function(data){
                $('#towns').html(data);
            },
            error: function(data){
            console.log('there is an error somewhere');
          }
   
            });//ajax ends */
               
        });
    });
</script>


You can add another js/ajax in that towns-result view and also anything else.

Hope this was the thing you need.


RE: Access ajax data from the function and use it outside CI3 - janeiro - 04-24-2023

(04-23-2023, 09:07 PM)SubrataJ Wrote: What do you mean by "access data from function edit_book", you want to use the response of this function outside, once the Ajax request is complete?

Yes, that's what I want to do Smile