json_encode not working with a html string as value
ajax, jquery, json, php
Solution
I was having same problem with `json_encode` today. But after testing a lot I found the correct solution:
In PHP to encode the array or string:
json_encode($array, JSON_HEX_QUOT | JSON_HEX_TAG);
In JS to decode the same:
var d = $.parseJSON(content);
Problem
I am debugging this ajax for quite a time now. I have this on my jQUery file: ``` $("#typeForm").ajaxForm({ success : function(html){ alert(html); }).submit(); ``` This calls service.php, and within it I have this: ``` $data = array('upload_data' => $this->upload->data()); $str = "<div style='position:relative'><img src='/assets/ui/success.png' /><span style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>"; echo json_encode(array('file_name' => $data['upload_data']['file_name'], 'prompt' => $str)); ``` This won't work. But by replacing `$str` to `$str = "HELLO WORLD";` the jQuery alerts what should I expected. What seems to be the problem? EDIT: Here is a screenie of the output: It does alerts, but if I modify my jQuery into this: ``` $("#typeForm").ajaxForm({ success : function(html){ var obj = $.parseJSON(html); alert(obj); }).submit(); ``` Then it does nothing at all, even alerting. I did a var_dump on the `json_encode` and here is the dump, it looks like a malformed JSON: ``` string(214) "{"file_name":"cde595988d386529909ce5a8fe3a6d6f.png","prompt":"<div style="position:relative;"><img src="\/assets\/ui\/success.png" \=""><span style="position:relative;top:-15px;">Nachricht empfangen!<\/span><\/div>"}" </span></div> ``` Here is the full content of service.php ``` class Service extends CI_Controller { public function __construct() { parent::__construct(); } public function index() { $filename = 'uploadfile'; $config['upload_path'] = './uploads/temp'; $config['allowed_types'] = 'jpg|png|gif|doc|docx|pdf|ppt|pptx|xls|xlsx|bmp'; $config['max_size'] = '3072'; $config['encrypt_name'] = TRUE; $config['remove_spaces'] = TRUE; $this->load->library('upload', $config); if (!$this->upload->do_upload($filename)) { $error = array('error' => $this->upload->display_errors()); echo json_encode(array('error' => $error['error'])); } else { $data = array('upload_data' => $this->upload->data()); $file_name = $data['upload_data']['file_name']; //print_r($data); //echo json_encode(array('test' => "Hello World")); $str = "<div style='position:relative;'><img src='/assets/ui/success.png' /><span style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>"; $str2 = json_encode(array("file_name" => $file_name, "prompt" => $str)); //var_dump($str2); exit(json_encode(array('file_name' => $data['upload_data']['file_name'], 'prompt' => $str))); } } } ```