简体   繁体   English

使用AJAX将数据发布到PHP

[英]Post data to PHP with AJAX

Im trying to send data to PHP with AJAX. 我试图用AJAX将数据发送到PHP。 I already tryed sending it with JSON, with $.post and $.ajax, but all it does - it returns Notice: Undefined index: id in C:\\xampp\\htdocs\\PHP Test\\db\\editform.php on line 7 我已经尝试使用$ .post和$ .ajax的JSON发送它,但它所做的全部-它返回注意:未定义的索引:C:\\ xampp \\ htdocs \\ PHP Test \\ db \\ editform.php中的id在第7行

What am I doing wrong? 我究竟做错了什么?

HTML 的HTML

<form action="" method="post" class="usereditform">
  <input type="hidden" name="id" value="'.$db_row['id'].'">
  <input type="hidden" name="key" value="'.$_SESSION['security_key'].'">
</form>

jQuery jQuery的

$(document).on('click', '.edit_user', function (e) {
  e.preventDefault();

  var form = $(this).parent().find('form.usereditform');
  var post_url = 'db/editform.php';
  var post_data = form.serialize();

  $.ajax({
    type: 'post',
    url: post_url,
    data:post_data,
    success: function () {
      $('.edit_user_form_placeholder').load('db/editform.php');
      $('.edit_user_popup').fadeIn();
    }
  });
});

PHP - editform.php PHP-editform.php

$id = $_POST['id'];
echo $id;

HTML 的HTML

<div class="popup edit_user_popup" style="display:none;">
  <div class="popup_container">
    <div class="edit_user_form_placeholder"></div>
  </div>
</div>

You are actually sending two requests: 您实际上正在发送两个请求:

  //first request with proper settings
  $.ajax({
    ...
    success: function () {
      //second request without any posted data
      $('.edit_user_form_placeholder').load('db/editform.php');
      ...
    }
  });

Instead, use the data that you get returned by the request itself. 而是使用请求本身返回的数据。 Using the $.post method this could be done the following way 使用$.post方法可以通过以下方式完成

$.post(post_url, post_data, function(result) {
                                  // ^- this is the data that gets returned by the request
    $('.edit_user_form_placeholder').html(result);
    $('.edit_user_popup').fadeIn();
});

This is the way I'm currently communicating to PHP via ajax. 这是我目前通过ajax与PHP进行通信的方式。 I find it the easiest way, and can be done without forms. 我发现它是最简单的方法,并且无需表格即可完成。

jQuery jQuery的

 var dataString = 'key1='+ value1 + '&key2='+ value2; //values you want to send
    $.ajax({
            type: "POST",
            url: "db/editform.php",
            data: dataString,
            cache: false,
            success: function(result){
            //success text
            }
     });

PHP - editform.php PHP-editform.php

And recieve like so. 并收到这样的消息。

$rowid = $_POST['key1'];
$securitykey = $_POST['key1'];

Have you tried with parsing the data you are posting into a JSON object? 您是否尝试过解析要发布到JSON对象中的数据?

var post_data = JSON.stringify(form.serializeArray());

The data you are passing to your ajax call are not formatted in a JSON object. 您传递给ajax调用的数据未在JSON对象中格式化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM