CodeIgniter autoloaded models' variables are lost after an AJAX call

与世无争的帅哥 提交于 2020-01-06 13:57:49

问题


I've been creating an application that requires buttons to make an ajax call to a controller that uses autoloaded models. I was under the impression that variables in an autoloaded model would retain their values after an Ajax call, but for some reason the entire model (including their variables) have lost their new values.

Am I misunderstanding the way the autoload function works, or does it have something to do with me using Ajax?

Code for reference below.

Autoload:

$autoload['model'] = array('choice_model');

Ajax calls in JQuery:

$( document ).ready(function() {
    var encounter = 1;

    $.ajax({
        type: "POST",
        url: baseURL+"Encounter/startEncounter",
        dataType: "json",
        data: "encounter_id=" + encounter,
        success: function(data) {
            $("#message-box").html(data);
            SetChoices();
        }
    });
});

function SetChoices() {

    $.ajax({
        type: "POST",
        url:  baseURL+"Choice/getChoices",
        dataType: "json",
        data: "",
        success: function(data){
            alert (data);
        }
    });
}

The first ajax call sets the following variable in Choice_model to "TestTrue":

public $test = 'TestFalse';

The second ajax call returns the previous variable, but it's value is now "TestFalse" once again.

Thank you for your time, I hope someone can help me out.


回答1:


Am I misunderstanding the way the autoload function works?

Well... yes.

Autoloading means the object is loaded (instantiated) automatically when the application starts. So we won't need to load them couple of times if needed.

Note: Only necessary/essential models should be loaded automatically.

Or does it have something to do with me using Ajax

In this case, a XHR request acts as a normal HTTP request. When you send a request to a Controller/method the whole application runs and stops after serving the result.

So the model would lost all values stored in its properties.

Looking for a solution?

I'm not sure about this, but you could store the variables in Session (by using $this->session->set_userdata() in CI) and retrieve the stored values later.




回答2:


Every ajax request is a new page load, so, when you call it first, you load the model and set you variable, but when you call the second request you load a new instance of the model, with new values for your variables... I think the best way to manage this is using SESSIONS or COOKIES...



来源:https://stackoverflow.com/questions/21162136/codeigniter-autoloaded-models-variables-are-lost-after-an-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!