Request ajax with unexpected return

2

I have an ajax code that makes a request in a php file, and in this php file has only one

  

echo json_encode ('test')

In return, the string "teste"NULL , always with this NULL is returned, after any return.

$.ajax({
        url: BASE_URL+'produto/only_df',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
           alert(data);
        }
      });
    
asked by anonymous 12.05.2018 / 15:59

1 answer

4

The json_encode function converts objects and arrays to a JSON string, but there is no sense in converting a normal string to JSON, ie:

$foo = array(
     'bar' => 'Olá',
     'baz' => 'Mundo!'
);

echo json_encode($foo);

It will turn this (which is a valid json):

{"bar":"Ol\u00e1","baz":"Mundo!"}

And this:

$foo = array( 'Olá', 'Mundo!' );

echo json_encode($foo);

It will turn this (which is a json of the indexed / iteravel type valid):

["Ol\u00e1","Mundo!"]

Now this:

echo json_encode('Olá mundo!');

Or this:

echo json_encode("Olá mundo!");

You will only escape the string where you have accents and apply the quotation marks:

"Ol\u00e1 mundo!"

In other words, this is not a JSON, it's just a string that can be used with JSON, or other JavaScript functions

  

Read about the unicode escape at: Writing PHP code without special characters

     

Note: If the document is not saved in a unicode format, as utf8, json_encode will not work, it will return the value NULL

     

read more about using utf-8 in your PHP pages: Doubt with charset = iso-8859-1 and utf8

The use of json_encode with strings is allowed because the same escape that is used for JSON is used for JavaScript, since JSON is an accepted and widely used format with JS. Even the use of HTML attributes called data-* can make use of this escape.

An example of using json_encode with strings would be to create a function generated via PHP that will be executed in JS, for example if you create a file like this:

foo.php

<?php

echo 'foo(' . json_encode('teste') . ')';

And call it like this on another HTML page:

<script src="foo.php"></script>

The script (and function) would be processed and downloaded like this in the browser:

foo("teste");

Of course you could do this directly / manually, without needing json_encode , but imagine that the string has broken lines or quotation marks, if you do this:

$arg = '
  olá mundo

  "isso é um teste"
';

echo 'foo("' . $arg . '")';

It will generate this:

foo("
  olá mundo

  "isso é um teste"
");

What will give syntax error when running in JavaScript, due to line breaks and "quotation marks" within quotes, but using json_encode

$arg = '
  olá mundo

  "isso é um teste"
';

echo 'foo(' . json_encode($arg) . ')';

It will escape the accents, breaks of lines and quotation marks, thus:

foo("\n      ol\u00e1 mundo\n\n      \"isso \u00e9 um teste\"\n    ")

What will run correctly in JavaScript.

    
12.05.2018 / 18:00