简体   繁体   中英

Trying to send a string to php file using ajax

So i am trying to send a string into a php file using ajax but the http.send is not working, maybe something is wrong with the code? (i am just a beginner)

 mainlink= 'a link';
 id= 'an id';
 $(document).click(function(){
   var http = new XMLHttpRequest();
   var link = mainlink+id;
   http.open("POST", 'test.php', true);
   http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http.onload = function(){
     if(this.status == 200) {
       console.log (link);
     }
   }
   http.send("link="+link);
 });

test.php:

<?php 
if (isset($_POST['link'])){
echo $_POST['link'];
} else{echo "error";}
?>

i tried both GET and POST.

This works. Are you sourcing in jQuery? Paste this tag inside the head tag of your page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

It also seems probable that you want to console log this.responseText instead of link so you actually log what the server is responding rather than what you sent. Here is the exact code I used to get this working:

HTML:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
                var mainlink = 'a link';
                var id = 'an id';
                $(document).click(function(){
                    var http = new XMLHttpRequest();
                    var link = mainlink + id;
                    http.open("POST", 'test.php', true);
                    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    http.onload = function(){
                        if (this.status == 200){
                            console.log(this.responseText);
                        }
                    }
                    http.send("link=" + link);
                });
        </script>
    </head>
</html>

PHP:

<?php 
    if(isset($_POST['link'])){
        echo $_POST['link'];
    }
    else{
        echo "error";
    }
?>

You can see it working live here . Is your pathname correct for test.php ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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