Kim
Kim

Reputation: 1156

Post with AJAX and PHP - How is this really working

1.) To post the content (i.e. text) from an ID and then get the variables in PHP in the post.php file?

2.) Call the PHP, like "if ($_POST['Promotion'])". How do you define the _POST in the ajax and in the PHP?

Basically I want the PHP to make a post.

HTML:

<input type="text" id="promo_headline">
<button id="BtnPostPromotion">Post promotion</button>

Jquery:

$(document).ready(function(){
$('#BtnPostPromotion').click(function() {
    $.ajax({
        type : 'POST',
        url : 'post.php',
        dataType : 'json',
        data: $('#promo_headline').val(),
        success : function(data){                   
            if (data.error === true)
            $('#errorModal').modal("show");
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            $('#errorModal').modal("show");
        }
    });

    return false;
});
});

PHP:

if ($_POST['Promotion']) {  
    $promo_headline = $_POST['promo_headline'];
}

Upvotes: 0

Views: 61

Answers (2)

David Barker
David Barker

Reputation: 14620

If you want $_POST['Promotion'] available in your PHP, send an object with a key of Promotion.

$.ajax({
    url : '...',
    type : 'POST',
    data : { Promotion : $('#promo_headline').val() },
    ...
});

As another note it kinda makes me sad seeing jQuery.val() being used when it is so much more efficient (and just as cross browser friendly) to:

document.getElementById('promo_headline').value;

Upvotes: 1

Ayush
Ayush

Reputation: 42450

In your jQuery, data needs to be in key value pairs:

data: {
    'Promotion' : $('#promo_headline').val()
},

Upvotes: 0

Related Questions