S
S
sunnyrio2018-05-01 16:19:10
PHP
sunnyrio, 2018-05-01 16:19:10

What's wrong with using ajax?

When accessing the server, the following message is displayed in the console:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
What could be the reason?

The server that processes this request:

<?php

/*
* Получение страницы
*/
function add_comment(){
  global $connection;
  $comment_author = trim(mysqli_real_escape_string($connection, $_POST['commentAuthor']));
  $comment_text = trim(mysqli_real_escape_string($connection, $_POST['commentText']));
  $parent = (int)$_POST['parent'];
  $comment_product = (int)$_POST['productId'];
  
  // если нет ID товара
  if(!$comment_product){
    $res = array('answer' => 'Неизвестный продукт!');
    return json_encode($res);
  }
  // если не заполнены поля
  if(empty($comment_author) OR empty($comment_text)){
    $res = array('answer' => 'Все поля обязательны к запалнению');
    return json_encode($res);
  }
}

?>


ajax request:
$.ajax({
  url: '<?=PATH?>add_comment',
  type: 'POST',
  data: {commentAuthor: commentAuthor, commentText: commentText, parent: parent, productId: productId},
  success: function(res){
    var result = JSON.parse(res);
    console.log(result);
  },
  error: function(){
    alert('Ошибка JQ user');
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2018-05-01
@GavriKos

if(!$comment_product){
    $res = array('answer' => 'Неизвестный продукт!');
    return json_encode($res);
  }
  // если не заполнены поля
  if(empty($comment_author) OR empty($comment_text)){
    $res = array('answer' => 'Все поля обязательны к запалнению');
    return json_encode($res);
  }

And where is the result sending if everything is correct? Not a single if fired - what to return to the server? An empty string, by the way, is not a valid json.
And to simplify - output to the console on the client res BEFORE trying to parse it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question