G
G
galynsky2014-08-21 08:06:12
PHP
galynsky, 2014-08-21 08:06:12

How to use JSON PHP?

Help with JSON. Does not work. Thanks in advance.
HTML:

<form class="form-horizontal" id="callback_form" role="form" action="javascript:void(0);">
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-3 control-label">Меня зовут:</label>
    <div class="col-sm-9">
      <input name="callback_name" type="text" class="form-control" placeholder="Введите имя">
    </div>
  </div>
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-3 control-label">Мой телефон:</label>
    <div class="col-sm-9">
      <input type="text" class="form-control" name="callback_phone" placeholder="Введите телефон">
    </div>
  </div>
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-3 control-label">Удобное время:</label>
    <div class="col-sm-9">
      <select name="callback_time" class="form-control">
        <option value="9.00 - 12.00">9.00 - 12.00</option>
        <option value="12.00 - 14.00">12.00 - 14.00</option>
        <option value="14.00 - 16.00">14.00 - 16.00</option>
        <option value="16.00 - 18.00">16.00 - 18.00</option>
      </select>
    </div>
  </div>
  <button type="submit" class="btn btn-primary btn-block">Отправить</button>
</form>

JS:
$('#callback_form').on('submit',function()
    {
      var form_data = $(this).serialize();

      $.ajax({
        url: 'ajax/modal/send_phone.php',
        type: 'POST',
        data: form_data,
        dataType: 'json',
        success: function()
        {
          $('.call_add').hide();
          $('#modal_call .alert-success').show();
        }
      });
    });

PHP:
<?php
$test = json_decode($_POST);
echo $test['callback_name'];
?>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
_
_ _, 2014-08-21
@galynsky

dataType: 'json' in $.ajax tells jQuery to treat the response from the server as json instead of using headers to determine the content type.
As I understand it, you thought that this parameter is sending your form_data as json to the server.
In fact, you do not need to do any json_decode($_POST), you already have an associative array with form data in $_POST. Just do $_POST['callback_name'] and that's it.

1
1Michael1, 2014-08-21
@1Michael1

but in my opinion json_decode is not needed here ... in $_POST there will be a serialized form anyway ...
for greater certainty, you can simply in php:
print_r($_POST);

V
Vitaly Zheltyakov, 2014-08-21
@VitaZheltyakov

if ((!empty($_POST))&&(isset($_SERVER['HTTP_X_REQUESTED_WITH']))&&($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
$test = isset($_GET['form_data']) ? json_decode($_GET['form_data']) : '';
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question