Vitaly2017-09-20 12:26:16
Vitaly, 2017-09-20 12:26:16

Ajax gives error and status 200?

Good afternoon. Help me to understand.
There is a form

<form  id="feedback">
  <div class="form-group">
    <input type="text" class="form-control" id="name">
  <div class="form-group">
    <input type="email" class="form-control" id="email" >
  <div class="form-group">
    <input type="text" class="form-control" id="theme" >
  <div class="form-check">
    <textarea id="message" class="form-control"></textarea>

  <button type="submit" class="btn btn-primary">Submit</button>

there is an ajax request
    $('button').on('click', function(e){

    function sendMessage()
      var user_name = $('#name').val(),
        user_email = $('#email').val(),
        user_theme = $('#theme').val(),
        user_message = $('#message').val();
        url: 'action.php',
        type: 'POST',
        dataType: 'JSON',
        data: {
          name: user_name,
          email: user_email,
          theme: user_theme,
          message: user_message
        success: function(data){
        error: function(request, status, error){
          var statusCode = request.status; // вот он код ответа

and there is an action.php file that handles ajax and should write to the database
$name = $_POST['name'];
$email = $_POST['email'];
$theme = $_POST['theme'];
$message = $_POST['message'];

$db_host = "*****"; 
$db_user = "*****"; 
$db_password = "******"; 
$db_table = "feedback";     

$db = mysql_connect($db_host,$db_user,$db_password) OR DIE("Не могу создать соединение ");
// Выборка базы
mysql_query ("INSERT INTO feedback (name, email, theme, message,) VALUES ('$name', '$email', '$theme', '$message')");

during execution, ajax fulfills error: and displays status 200 in the console and nothing is written to the database

Answer the question

In order to leave comments, you need to log in

2 answer(s)
grisha2217, 2017-09-20

Let's start with how the form handler should look like:
1. The event should be hung on the form, not on the button - $('#feedback').on('submit', ...)
2. Leave the preventDefault line
3. Have set the name attribute of each input
4. In the data parameter, write $(this).serializeArray() - all inputs with a name will be serialized into an array and sent to the server, where they will be visible via $_POST
Next, via var_dump in php, see the values ​​of the variables, the cheekbone will display error if something goes wrong.

Vladimir Skibin, 2017-09-20

dataType: 'JSON',
What do you get in response from php? Make an answer of this type and we will be successful for you
and to all this recommendations from grisha2217

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question