javascriptphpjqueryajax

How to assign values to js variable from ajax function(PHP)


I have the following ajax

function loadCalender() {
  $.ajax({
    url: '<?php echo base_url()."catering"."/"."loadStoreCalender"; ?>',
    method: 'POST',
    data: {
      val: $(this).val()
    },
    context : this,
    success: function(result) {
      // I have to Assign value to Array in the following format
      //events[0] = { Title: "Booking Not Available", Date: new Date("05/13/2014") };
      //events[1] = { Title: "Booking Not Available", Date: new Date("04/21/2014") };
      //events[2] = { Title: "Booking Not Available", Date: new Date("04/22/2014") };
      //events[3] = { Title: "Booking Not Available", Date: new Date("04/23/2014") };
    }
  });
  return false;
}

My Question is how could I pass the array value from PHP Controller to Ajax to achieve an array in the desire format (I mean

    //events[0] = { Title: "Booking Not Available", Date: new Date("05/13/2014") };

).

Below is my PHP Controller

public function loadStoreCalender()
{
  $this->load->model('catering_model');
  $result=array();//???
  $storeId = $_POST['val'];
  $result = array("Title" => "Booking Not Available","Date" => new Date("04/21/2014")); // For Example
  die(json_encode($result));
}

I'm creating a function for Booking System with PHP CI and Ajax. I'm noob in working with array and ajax things. Please help me.


Solution

  • Try this:

    function loadCalender(callback) {
        $.ajax({
            url: '<?php echo base_url()."catering"."/"."loadStoreCalender"; ?>',
            method: 'POST',
            data: {
                val: $(this).val()
            },
            dataType: 'json',
            context : this,
            success: function(results) {
                callback(results);
            }
        });
        return false;
    }
    
    // Test
    loadCalender(function(eventsJsonObjArray)
    {
        console.log(eventsJsonObjArray);
    });