Ionut Apostu Ionut Apostu - 22 days ago 6
Javascript Question

AJAX call returns undefined in Header / form-data

I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:

$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});

});

});


The PHP is a simple echo. Please advise.

Answer

Suppose you have a div

<div id="send_me">
    <div class="sub-item">Hello, please send me via ajax</div>
    <span class="sub-item">Hello, please send me also via ajax</span>
</div>

Make AJAX request like

$.ajax({
    url: 'get_sorted_content.php',
    type: 'POST', // GET is default
    data: {
        yourData: $('#send_me').html()
        // in PHP, use $_POST['yourData']
    },
    success: function(msg) {
        alert('Data returned from PHP: ' + msg);
    },
    error: function(msg) {
        alert('AJAX request failed!' + msg);
    }
});

Now in PHP, you can access this data passed in the following manner

<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
    echo 'data received!';
else
    echo 'no data received!';
?>
Comments