B
B
barakuda12022-03-07 19:47:18
AJAX
barakuda1, 2022-03-07 19:47:18

Where did I make a mistake in json?

$("#form-phone").submit(function(e) {
                e.preventDefault();

                var phone= $("#phone").val();

                $.ajax({
                    type: "POST",
                    url: "json.php",
                    data: $(this).serialize(),
                    cache: false,
                    success: function(response) {
                        var jsonData = JSON.parse(response);

                        if (jsonData.ok == "1") {
                            alert("ok");
                        }else{
                            alert("error");
                        }
                    }
                });
            });


if(isset($_POST['phone'])) {
  $phone= $_POST['phone'];
        echo json_encode(array('ok' => 1));
}else{
  echo json_encode(array('ok' => 0));
}


VM1632:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
ThunderCat, 2022-03-07
@ThunderCat

Open the developer tools, network, and see what your Ajax request returns, most likely you have some kind of warning there, or an error.
In addition, parsing the string is not necessary at all, it is enough to specify the type of the returned value in Ajax.

A
Andrey Elsukov, 2022-03-09
@Dropsen

There may be some character at the beginning of the line that is not related to json. Try first to remove the first character from the string, then JSON.parse later. Before that, it's better to check what returns. Because if an error, then the first character has nothing to do with

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question