简体   繁体   中英

AJAX example with JSON Response with object being passed

I'm having a difficult time using AJAX to send an associative array to a php file. There's somethings I'm not understanding clearly. Here's my code to make the array from a form of input tags, but I don't know how to send it and interpret it in php.

<script type="text/javascript">
$(document).ready(function(){
  $(':submit').on('click', function() { // This event fires when a button is clicked
      var theData = {};
      $(":input:not(:button)").each(
        function(index){  
            var input = $(this);
            theData[input.attr('name')] = input.val();
        }
      );
      $.ajax({ // ajax call starts
          url: "http://www.aberlechiropractic.com/meningealrelease/modifydoctors/modifydoctors3.php",
          data: theData,
          dataType: 'json',
          success: function(data)
          {
              $('#wines').html(''); // Clear #wines div
              $('#wines').append('Data Received: ' + data.name+'   '+data.address + '<br/>');
          }
      });
      return false; // keeps the page from not refreshing 
  });
});
</script>

<body>
  <form>
    <input type="text" name="name" id="name" value="Jeff Aberle"/>
    <input type="text" name="address1" id="address1" value="4710 East Broadway"/>
    <button type="submit" name="updatedoctor" id="updatedoctor" value="all">All</button>
  </form>
</body>

Here's my php code:

<?php
$name = $_GET['name'];
$address1 = $_GET['address1'];
$array = array($button, $address1);
print json_encode($array);
?>

Ah now everything works. I edited all the code here to make this work.

<?php
// Get value of clicked button
$name = $_GET['name'];
$address1 = $_GET['address1'];
$array = array(
    "name"    => $name,
    "address"  => $address1,
);
print json_encode($array);
?>

I also have a div with id=wines . It was another thing I forgot to show. That's where the data is being returned to and displayed without the name however.

Your jQuery code to collect the values is correct, although .serialize() will simplify it.

To retrieve the values in PHP, it's the same as if the form were being submitted normally. They're in $_GET['name'] and $_GET['address1'] . theData is just the name of the Javascript variable containing the object, it's not a property name sent to PHP.

Sorry I'm on my phone so its a short answer but use serialize

http://api.jquery.com/serialize/

Example

    $('form').on('submit', function(){
      $data = $(this).serialize();
      //send via ajax
      return false;
    })

To send data: I'm assuming you want to send the results of your form? To do this, first you're going to need to add a submit button to your page. This should be placed in your form to submit the code.

Second, it looks like you're missing the <div id="wine"> which you've referenced in the AJAX success response, so you're going to want to add that.

Try this you have to add button to your form to fire the action:

<script type="text/javascript">

$(document).ready(function(){
  $('#submit').live('click', function() {
      var theData = {};
      $(":input:not(:button)").each(
        function(index){  
            var input = $(this);
            theData[input.attr('name')] = input.val();
        }
      );
      $.ajax({
          url: "http://www.aberlechiropractic.com/modifydoctors3.php",
          data: theData,
          dataType: 'json',
          success: function(data)
          {
              $('#wines').html(''); // Clear #wines div
              $('#wines').append('Data Received: ' + data + '<br/>');
          }
      });
      return false; // keeps the page from not refreshing 
  });
});
</script>

<body>
  <form>
    <input type="text" name="name" id="name" value="Jeff Aberle"/>
    <input type="text" name="address1" id="address1" value="4710 East Broadway"/>
    <input type="button" id="submit" value ="send"/>
  </form>
</body>




<?php
$button = $_GET['theData'];
$array = array($button.name, $button.address1, $button.state);
print json_encode($array);
?>

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