Reputation: 860
I have the following method in my PHP class that processes messages and sends it back to JQuery. It works fine if there is only a single message to send back but if there is more than one, it sends them back as separate json objects. The messages are sent back ok but JQuery gives me an error. The messages look like this:
{"error":true,"msg":"Message 1 here..."}{"error":true,"msg":"Message 2 here"}
My PHP method looks like this:
private function responseMessage($bool, $msg) {
$return['error'] = $bool;
$return['msg'] = $msg;
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
echo json_encode($return);
}
...
}
I don't know how to change this so multiple error messages are put into a single json encoded message but also work if it is just a single message.
Can you help? Thanks
Upvotes: 1
Views: 2576
Reputation: 985
Sounds like a design issue. You need to build up an object like $response = array(); and then every time an error needs to be added just append it. $response[] = $errorData; then when ur finished just json_encode($response);
Upvotes: 0
Reputation: 270607
Looks like you need to be appending onto an array and then when all messages have been added, output the JSON. Currently, your function outputs JSON any time it is called:
// Array property to hold all messages
private $messages = array();
// Call $this->addMessage() to add a new messages
private function addMessage($bool, $msg) {
// Append a new message onto the array
$this->messages[] = array(
'error' => $bool,
'msg' => $msg
);
}
// Finally, output the responseMessage() to dump out the complete JSON.
private function responseMessage() {
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
echo json_encode($this->messages);
}
...
}
The output JSON will be an array of objects resembling:
[{"error":true,"msg":"Message 1 here..."},{"error":true,"msg":"Message 2 here"}]
Upvotes: 2
Reputation: 324630
You can send the errors as an array.
$errors = Array();
// some code
$errors[] = ...; // create an error instead of directly outputting it
// more code
echo json_encode($errors);
This will result in something like:
[{"error":true,"msg":"Message 1 here..."},{"error":true,"msg":"Message 2 here"}]
Upvotes: 0