简体   繁体   中英

Can't post variable to PHP using AJAX

I am trying to send a variable to PHP using JavaScript but I don't get any response whatsoever. Any ideas?

PHP/HTML:

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

    <body>
      <?php
        $selection = $_POST['selection'];
        if($selection == 'profile'){
      ?>
      <p> it works
      <?php
        }
      ?>

      <button id="button"> profile </button>
    </body>

JS file (dashmenu.js):

$('#button').click(function() {
    var menuSelection = "profile";

    $.ajax({
        type: 'POST',
        url: 'dashboard.php',
        data: {selection: menuSelection},
        success: function(response) {
            alert('success');
        }
    });
});        

In your html file (let's say index.html) you could have:

$('#button').click(function() {
  var menuSelection = "profile";

  $.ajax({
    type: 'POST',
    dataType: "html",
    url: 'dashboard.php',
    data: {selection: menuSelection},
    success: function(response) {
        alert(response);
    },error: function(jqXHR, textStatus, errorThrown){
        alert('Error: ' + errorThrown);
    }
  });
});

In your dashboard.php, you should ONLY have code that processes requests, and returns (echoes) the desired output:

<?php
    $selection = $_POST['selection'];
    if($selection == 'profile'){
        echo "It works";
    }else{
        echo "It failed";
    }
?>

$('#button').click(function() { var menuSelection = "profile";

$.ajax({
    type: 'POST',
    url: 'dashboard.php',
    data: {selection: menuSelection},
    success: function(response) {
        alert('success');
    }
});

});

Run this in your console in your browser. Right-click > Console tab. If you want to check whether this function has successfully bind to the button. If your browser returns you 'success' alert, meaning you include it wrongly I guess.

If nothing happen when you click, please include .fail() in your $.ajax()

Which will look like this:

 $.ajax({
   type: 'POST',
   url: 'dashboard.php',
   data: {
    selection: menuSelection
    },
   success: function(response) {
    alert(response);
   },
  error: function(jqXHR, textStatus, errorThrown){

  }
 });

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