Home » Php » php – json_encode not working with a html string as value

php – json_encode not working with a html string as value

Posted by: admin April 23, 2020 Leave a comment

Questions:

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:

enter image description here

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!&lt;\/span&gt;&lt;\/div&gt;"}"
</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)));
        }
    }
}
How to&Answers:

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);

Answer:

Some stuff to try:

ajaxForm supports dataType argument, if you expect a JSON coming from the server, use dataType: json like so

$("#typeForm").ajaxForm({
    success : function(html){
       // html here is already automatically a json object
       alert(html.prompt);
    },
    dataType: 'json'
}).submit();

Could you post the full service.php? OR try the following:

exit(json_encode(array(‘file_name’ =>
$data[‘upload_data’][‘file_name’], ‘prompt’ => $str)));

— EDIT —

Not sure why json_encode returns such weird string :s, is the json_encode a standard php library or an external library? I’m asking this because some servers don’t have json_encode in their php installation… I tested on my local and using php internal json_encode and it works fine:

<?php
$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('prompt' => $str));

// output
//{"prompt":"<div style='position:relative'><img src='\/assets\/ui\/success.png' \/><span style='position:relative;top:-15px;'>Nachricht empfangen!<\/span><\/div>"}

Answer:

How about convert all the potential problem characters instead of just what fixes the problem in this circumstance:

die(json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE));

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/json.constants.php

Answer:

If you cannot find a better solution for this you can encode the value to base64 encoding:

$data = array('upload_data' => $this->upload->data());
$str = base64_encode("<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));

and in the client decode it, IMO this is more safer this is also more applicable if you’re processing characters from different languages.

ALSO:

to sure that no other characters will be added on the json string call exit; writer after you print it.

Answer:

You should call only prompt object of your array not all! like below:

$("#typeForm").ajaxForm({
    success : function(html){
        var obj = $.parseJSON(html);
        alert(obj.prompt);
}).submit(); 

Answer:

It looks like you need to escape your quotes server-side. Since they are in there, it seems to be creating an invalid JSON string.

Answer:

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!&lt;\/span&gt;&lt;\/div&gt;"}"
</span></div>

This seems to be broken because there’s no quote escaping. When an unescaped ” is found, it breaks the JSON structure you expect.
Escaped ” should be \”, single quotes with \’ and so on.

Answer:

JSON doesn’t play well with string output that comes out of magic method __toString() – it nearly impossible to json_encode() anything that even remotely touched something like this.

<?php
/**
 * DEBUGGING NIGHTMARE
 * SO MUCH FUN, 10/10,
 */
class Nightmare {
  protected $str;
  public function __construct($str) {
    $this->str = $str;
  }
  public function __toString() {
    return $this->str;
  }
}

$test = new Nightmare('Hello Friends.');
echo $test;
> Hello Friends.

// cooool, so let's JSON the hell out of it, EASY

echo json_encode(['our_hello' => $test]);
// This what you expect to get, right?
> {"our_hello":"Hello Friends."}

// HAHA NO!!!
// THIS IS WHAT YOU GET:
> {"our_hello":{}}


// and this is why is that:

var_dump($test);
object(Nightmare)#1 (1) {
  ["str":protected]=>
  string(14) "Hello Friends."
}

print_r($test);
Nightmare Object
(
    [str:protected] => Hello Friends.
)