Javascript POST not working – Sending Javascript array to PHP

You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:

index.php

<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    //attach to the button a click event
    $('#btn').click(function(){
            //get the value from the textbox
        var txt=$('#txt').val();
            //if txt is blank, alert an error
        if(txt == ''){
            alert("Enter some text");
        } else {
                    //send txt to the server
                    //notice the function at the end. this gets called after the data has been sent
            $.post('catcher.php', {'text':txt}, function(data){
                            //now data is an object, so put the message in the div
                $('#response').text(data.message);
            }, 'json');
        }
    });
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;">&nbsp;</pre>
</body>
</html>

catcher.php:

<?php
//if something was posted
if(!empty($_POST)){
    //start an output var
    $output = array();

    //do any processing here.
    $output['message'] = "Success!";

    //send the output back to the client
    echo json_encode($output);
}

It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.

Leave a Comment