简体   繁体   English

在PHP中从Ajax获取数据

[英]Get data from ajax in php

I'm new to ajax and I'm stuck in a problem. 我是ajax的新手,我陷入了一个问题。 I want to post the id of the clicked element in a result list to another page (in localhost). 我想将结果列表中单击的元素的ID发布到另一个页面(在localhost中)。 When I want to get the posted id from the ajax data I get undefined index id (which is $id = $_POST['id']). 当我想从ajax数据中获取发布的ID时,我得到了未定义的索引ID(即$ id = $ _POST ['id'])。 how can I solve this ? 我该如何解决?

I appreciate any help or advice. 感谢您的帮助或建议。

index.php index.php

<section id= "searchbar">
        <form method="get" action="index.php" name="myForm" id="myForm">
            <h3>Search</h3>
        <table>
            <tr>
                <td><input id="wilaya" type="text" name="wilaya" class="resizedTextbox" placeholder="Choose your Wilaya"></td>
                <td><input id="surface" type="text" name="surface" class="resizedTextbox" placeholder="Choose the surface"></td>
                <td><input id="search" type="submit" class="resizedTextbox" value="Search"></td>
            </tr>

        </table>
    </form>
    </section>




     <section id="resultlist">
            <table width="100%" height="90%" id="table1">
                <thead>
                    <tr>
                    </tr>
                </thead>

                <?php
                $array[] = null;
                $i = 1;
                while ($results = mysql_fetch_assoc($result)) {
                    ?>
                    <tr>

                    <div class="round-button">
                        <!--echo '<img name= "house" class= "imagehouse" src="images/' . $results['photo'] . '" id=' . $results['id'] . ''-->   
                        <?php echo "<img src= images/" . $results['photo'] . " width='50' id=" . $results['id'] . " />"; ?>
                        <td id="nametable" width="10%"> <?php echo $results['name']; ?></td>
                        <td id="wilayatable"width="10%"><?php echo $results['wilaya']; ?></td>
                        <td width="10%"><?php echo $results['surface'] . " m²"; ?></td> 
                        </tr>
                        <?php
                        $i++;
                    }
                }
                ?>
        </table>
    </section>

    <?php
//extract data from the post
//set POST variables
        $url = 'http://localhost/testcurl.php';

        $fields = array(
            'wilaya' => urlencode($_POST['wilaya']),
            'id' => urlencode($_POST['id']),
        );

//url-ify the data for the POST
        foreach ($fields as $key => $value) {
            $fields_string .= $key . '=' . $value . '&';
        }
        rtrim($fields_string, '&');

//open connection
        $ch = curl_init();

//set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

//execute post
        $result = curl_exec($ch);

//close connection
        curl_close($ch);
        ?>
    <?php
    var_dump($_POST['id']);
    ?>

and that's the function that get the id of the clicked image 这就是获取点击图片ID的函数

        $('img').click(function () {
            alert(this.id);
            var id = this.id;
            $.ajax({
                url: 'index.php',
                type: 'post',
                data: {
                    'id': id
                },
                success: function (msg) {
                    alert('Success!');
                }
            });
            $.get("http://localhost/testcurl.php");
            window.location = 'http://localhost/testcurl.php';
        }); 

testcurl.php testcurl.php

here I send a post the id to the server 在这里,我将帖子ID发送到服务器

<?php

$url = "http://localhost/testcurlserver.php";// where you want to post data

$wilaya = isset($_POST['wilaya']);
$id = isset($_POST['id']);
$fields = array(
    'wilaya' => urlencode($_POST['wilaya']),
    'id' => urlencode($_POST['id']),

);

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

var_dump($output); // show output

?>

testcurlserver.php here is the server code testcurlserver.php这是服务器代码

<?php

if (isset($_POST['id'])) {

    $jj =$_POST['id'];
    var_dump($jj);

    echo "it worked";

    $wilaya = $_POST['wilaya'];
    // connect to database 
    $db = mysql_connect('localhost', 'root', 'test123') or die('error because:' . mysql_error());
    $mydb = mysql_select_db("top360");
    $sql = "SELECT id,photo,name, wilaya, surface FROM HOUSE WHERE wilaya= '" . $wilaya . "'";
    //-run the query against the mysql query function
    $result = mysql_query($sql);

    while ($row = mysql_fetch_array($result)) {
        echo $row['name'];
    }


    if ($result === FALSE) {
        die(mysql_error());
    }
    $results = mysql_fetch_assoc($result);


    echo $results['name'];
}

here is what I get: 这是我得到的:

Notice: Undefined index: id in C:\xampp\htdocs\index.php on line 122 
Notice: Undefined variable: fields_string in C:\xampp\htdocs\index.php on line 127 
  Notice: Undefined variable: fields_string in
  C:\xampp\htdocs\testcurl.php on line 14 string(0) "" it worked Notice:
  Undefined variable: output in C:\xampp\htdocs\testcurl.php on line 31
  NULL  
Notice: Undefined index: id in C:\xampp\htdocs\index.php on line
  147 NULL

please type at top of the your code 请在您的代码顶部输入

if (! is_array($_POST)) {
   $_POST = json_decode(file_get_contents('php://input'), true);
}

After trying I've found a solution now that's why I want to share it here. 经过尝试之后,我现在找到了解决方案,这就是为什么我要在这里共享它。 I post the id with an ajax post like ($.post) and get the response in a div with the id = 'content'. 我用一个像($ .post)这样的ajax发布该ID,并在一个ID为'content'的div中获得响应。

<div id="content" style ="border: 1px solid red;">

</div>

<script type="text/javascript">

    $('img').click(function () {
        alert(this.id);
        var id = this.id;

        $.post('testcurlserver.php', {'id': id}, function (data) {
                $('#content').html(data);
            });
        });

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

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