0

How do I send an array from PHP to jQuery?

I have many <input type = "text" id = "search_term" />. How can I send this data to jQuery?

<head>
  <script>
    $(document).ready(function(){
      $('#button1').click(function(){
        var search_val=$("#search_term").val(); 

        $.post("ajax.php",
          { search_term : search_val },
          function(data) {
            $("#search_results").html(data);
          }
        );
      });
    });
  </script>
</head>
<body>
  <input type = "text" id = "search_term" />
  <input type = "text" id = "search_term" />
  <input type = "text" id = "search_term" />
  ...
  <input type = "button" id = "button1" value = "test" />
</body>

2 Answers 2

2

You must use JSON.

PHP SCRIPT

echo json_encode($array);

JQuery

$.post("ajax.php", {search_term : search_val},
            function(data){
                var data=$.parseJSON(data); //Now "data" contains the php array
            });
        });
Sign up to request clarification or add additional context in comments.

Comments

1

The easiest way is to use JSON. From your php, you do json_encode($output) where $output is your array, and in jQuery you use either getJSON() method, or use $.ajax with the option dataType: 'json'.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.