简体   繁体   中英

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.

Thanks in advanced.

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);
});
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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM