Masoud Motallebipour
Masoud Motallebipour

Reputation: 414

How to JSON decode the post in codeigniter

I'm using codeigniter and I have to use json encode using jquery and when I want to give the data and validate them I have problem. My code is:

$this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="nNote nFailure hideit"><p>', '</p></div>');
        $this->form_validation->set_rules('Name', 'Name', 'trim|required|xss_clean');
        $this->form_validation->set_rules('Parent', 'Parent', 'required|xss_clean');
        $this->form_validation->set_rules('Language', 'Language', 'required|xss_clean');
        $this->form_validation->set_rules('Order', 'Order', 'required|xss_clean');
if ($this->form_validation->run())
{
 //do something here
}

How should I handle the post request with JSON?

Upvotes: 0

Views: 3647

Answers (1)

Zarathuztra
Zarathuztra

Reputation: 3251

I'm honestly not sure what you're asking, but if you want to respond with json, it's really quite simple, PHP makes this easy for us.

json_encode(array('jsonKey' => 'jsonValue', 'jsonKey2' => 'jsonValue2'));

Just set the appropriate headers and output that using your favorite mechanism (echo, output buffers, etc)

EDIT: If you want to go in the reverse (you're being presented with JSON data in your script)

Just do the following

$myGreatAssocArray = json_decode($jsonStringData);

Then, you end up with an associate array that you can easily grab data from, as follows:

$firstJsonValue = $myGretAssocArray['jsonKey1'];

It's really very convenient (and way easier than with say, Java :P )

Keep in mind though, json_decode is not only going to return arrays. If the JSON is malformed, NULL is going to be returned, so if you need to do any conditionals make sure to use !== NULL or something to that affect.

Upvotes: 1

Related Questions