About json_encode and ajax dataType: "json"

In my ajax code:

$.ajax({ url: CI_ROOT + "isUserExist", type: "GET", data: {recepient: recepient}, success: function(r) { console.log(r) } }) 

Gives me the exit [{"records": "1"}] [{"records": "1"}] So I parsed it json by adding dataType: "json" in my ajax code. But when I disassembled it, it does not give me a way out, but an error in try-catch-block.

How do I display it as objects? In my PHP code, I do this:

  for ($i = 0; $i < count($matches[0]); $i++) { echo json_encode($this->searchmodel->doesUsersExists($matches[0][$i])); } //gets the user id of the user from a given string. 
0
source share
2 answers

Add each entry to the array, and then json encode that array, not json, encoding each separately. If you have only one json_encode call, you will get valid JSON:

 $result = array(); for ($i = 0; $i < count($matches[0]); $i++) { $result[] = $this->searchmodel->doesUsersExists($matches[0][$i]); } //gets the user id of the user from a given string. echo json_encode($result); 
+5
source

This is invalid JSON. Make an array of your existing results and code it.

+2
source

Source: https://habr.com/ru/post/948549/


All Articles