简体   繁体   English

使用jQuery通过Ajax将数据从javascript发送到php。 如何查看回来的数据?

[英]Sending data from javascript to php using via Ajax using jQuery. How to view the data back?

I know this question has been asked a lot as I have been googling since morning but I just can't think what's going on in my code. 我知道这个问题从早上开始就一直被问到很多,但是我只是想不到代码中发生了什么。

I have a index.php (which is my website) that uses forms to receive information from user, then invokes a javascript file separately which in turn invokes another backend php file (this backend php file queries a database using mysql and does some stuff). 我有一个index.php(这是我的网站),该网站使用表单从用户那里接收信息,然后分别调用一个javascript文件,然后依次调用另一个后端php文件(该后端php文件使用mysql查询数据库并执行某些操作) 。

The problem is I am not sure what information is getting passed to the backend php from my js. 问题是我不确定什么信息会从我的js传递到后端php。 I have just learnt jQuery and Ajax so I really don't know what is that small mistake I am making. 我刚刚学习了jQuery和Ajax,所以我真的不知道我犯的那个小错误是什么。

From my understanding, the backend php does its stuff and passes the value to javascript to be displayed on the web page. 根据我的理解,后端php会执行其工作,并将该值传递给javascript以在网页上显示。 But my data is not getting sent / displayed. 但是我的数据没有被发送/显示。 I am getting a error 500 internal server error. 我收到错误500内部服务器错误。

Here are the pieces of code that are currently is question: 以下是当前存在问题的代码段:

Javascript: Javascript:

var data1 = {week:week, group:grp_name};

$.ajax({
    dataType: "json",
    type: "POST",
    url : "php/remindUsers.php",
    success : function(response){
                alert ("success !");
            },
    error : function(response){
           console.log(response);
           alert("fail!");
     }

   })
});

PHP backend (remindUsers.php): PHP后端(remindUsers.php):

<?php

if (isset($_POST['week'])) {
   $week = $_POST['week'];
}

if (isset($_POST['group'])) {
  $group_name = $_POST['group'];
}

  echo $week;
?>

I am ommiting out the sql code pieces because they work fine. 我省略了sql代码段,因为它们可以正常工作。

Edit: Now my status code is 200, response text is also ok . 编辑:现在我的状态码是200,响应文本也可以。 My response text shows a weird "enter' sign next to the actual response text expected. Is this normal ? And it is still going into the error block , not the success block of code. 我的响应文本在预期的实际响应文本旁边显示一个奇怪的“输入”符号。这正常吗?并且它仍然进入错误块,而不是代码成功块。

You can't have these tags <body>,... in your PHP response over json. 通过json的PHP响应中不能包含这些标签<body>,...

It must be only: 它只能是:

<?php
 $week = $_POST("data");
 $json =  json_decode($week);
 echo json_encode($json);
?>

Remove the comment on 删除评论

//data : {week :week} //数据:{week:week}

And set a variable week with a valid value: 并设置具有有效值的可变周:

data : {week :week} 数据:{week:week}

and so: 所以:

$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
data : {week :week} ,
success : function(response){
            console.log(response);
        },

In order to see what is the shape of response. 为了看看响应的形状是什么。

I can not fully answer your question because I need more debug information about whats going on but theres 2-3 things about your code bugging me a little that might fix your bug. 我无法完全回答您的问题,因为我需要更多有关运行情况的调试信息,但是关于您的代码有2-3件事使我感到有些困惑,这可能会解决您的错误。

First, use isset in your backend like this: 首先,在您的后端中使用isset,如下所示:

if (isset($_GET['your_input_name'])) {
    $someData = $_GET['your_input_name'];
}

The isset part is very important here. isset部分在这里非常重要。 Set it up and try it again. 进行设置,然后重试。 If you stop having a 500 error. 如果您不再遇到500错误。 Its probably because your data was never send to your backend or because your not checking the good input name. 这可能是因为您的数据从未发送到您的后端,或者是因为您没有检查良好的输入名称。

Second, About input name. 其次,关于输入名称。 I can see in your code that you send: 我可以在您发送的代码中看到:

var data1 = {week:week, group:grp_name};

So in your backend you should use the name of the value like this to retrieve your data: 因此,在您的后端中,应使用像这样的值的名称来检索数据:

$week = $_POST("week");

Third, I am not a json pro but maybe your json is not valid. 第三,我不是json专业人士,但也许您的json无效。 Even if he is ok I suggest you build a "cleaner" one like this: 即使他没事,我还是建议您像这样建造一个“清洁工”:

var data = [
        { 'name' : 'week', 'value' : week}
    ]; 

And finally, if you are using forms to send data to php then you can use something like that : 最后,如果您使用表单将数据发送到php,则可以使用类似的方法:

 var myForm = $("#myForm").serializeArray();

 $.ajax({
  url: 'yourUrl',
  type: "GET",
  data: myForm,
  dataType: 'json', 
  success: function(res){
      //your success code

  },
  error: function(){
    //your error code
  }
});

I hope this helps. 我希望这有帮助。

USE THIS 用这个

PHP 的PHP

   $week = $_POST['data'];
    $json = json_encode($week);
    echo $json;

JS JS

 $.ajax({
        dataType: "json",
        type: "POST",
       url : "php/remindUsers.php"
        //data : {week :week} ,
        data:  {data:{week:'week', group:'grp_name'}} ,
        success : function(response){
            alert ("success !");
        },
        error : function(response){
            alert("fail!");
        }

    })

You are doing a couple things wrong. 您做错了几件事。 First, you don't want to stringify your data before sending it to the server. 首先,您不想在将数据发送到服务器之前对数据进行字符串化处理。 You want to send JSON, so your commented line is the correct one. 您要发送JSON,因此您的注释行是正确的行。 There is also a problem with the PHP. PHP也有问题。 The data going to the server will look like: 发送到服务器的数据如下所示:

{week: "Something"}

So in your PHP, you want to access the data like: 因此,在您的PHP中,您想访问如下数据:

$_POST["week"];

I would say wrap the php in a function and echo the json. 我会说将php包装在一个函数中并回显json。 Also its good to check if there was POSTed data, and if not return an error message. 检查是否有POST数据,如果没有返回错误消息,这也很好。 This is not tested, but will hopefully point you in the right direction. 这没有经过测试,但是希望会指出正确的方向。

 <?php

 function getJSON() {

     if (isset($_POST["data"] && !empty($_POST['data'])  ) {
         $week = $_POST["data"];
         $json =  json_decode($week);
         echo $json;
     } else {
         echo "There was a problem returning your data";
     }
 } 

 getJSON();

 ?>

Actually as I write this, I realized you could try these headers in your AJAX POST: 实际上,在撰写本文时,我意识到您可以在AJAX POST中尝试这些标头:

accepts: 'application/json',
contentType: 'application/json',
dataType: 'json'

Hope that helps. 希望能有所帮助。

It worked. 有效。 I figured out the answer thanks to another SO post. 由于有了另一个SO帖子,我找到了答案。

TIL : Even if server response is ok, the error condition will be triggered because the data returned to javascript from php is not json,since i had explicitly mentioned dataType: "json" in the ajax request. TIL:即使服务器响应正常,也会触发错误情况,因为从php返回到javascript的数据不是json,因为我在ajax请求中明确提到了dataType:“ json”

Link here: 链接在这里:

Ajax request returns 200 OK, but an error event is fired instead of success Ajax请求返回200 OK,但是会引发错误事件而不是成功

Thanks folks for helping me and steering me in the right direction. 感谢大家的帮助和指导我正确的方向。 Cheers! 干杯!

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

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