开发者

Retrieving multiple post variables in a controller function in Codeingiter

开发者 https://www.devze.com 2023-01-24 07:56 出处:网络
I am posting data to controller like this: var postVars = new Arr开发者_如何学Cay(); postVars[0] = key;

I am posting data to controller like this:

var postVars = new Arr开发者_如何学Cay();
postVars[0] = key;
postVars[1] = haveCredits;
postVars[2] = creditsNeeded;
postVars[3] = creditsLeft;
//alert(postVars.join("&"));
xhr.open('POST', 'ajax');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(postVars.join("&"));

How can i retrieve this values in my controller function?

Controller code:

$variableValues= explode('&',$this->input->post('postVars'));

It is returning an empty array.

Thanks in advance.


Change last row like this:

xhr.send("postVars="+encodeURIComponent(postVars.join("&")));

Now $variableValues= explode('&',$this->input->post('postVars')); should work.

Btw, i would like to introduce you to jQuery. It's one of the most popular JavaScript libraries and has very powerfull AJAX API.


What you're sending isn't really application/x-www-form-urlencoded format. You're just joining together string values, rather than named, URL-escaped parameters.

I suggest sending separate parameters in standard URL-encoded format:

function encodeParameters(o) {
    for (var k in o)
        pars.push(encodeURIComponent(k)+'='+encodeURIComponent(o[k]))
    return pars.join('&');
}

var pars= {key: key, have: haveCredits, needed: creditsNeeded, left: creditsLeft};
xhr.open('POST', '/ajax');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(encodeParameters(pars));

then on the PHP side you can retrieve them using the normal request arrays:

$key= $_POST['key'];
$creditsNeeded= intval($_POST['needed']);
// ...
0

精彩评论

暂无评论...
验证码 换一张
取 消