BOTJr. BOTJr. - 2 months ago 7
Ajax Question

Ajax and jQuery with PHP

I have this code which posts data using jQuery and ajax to itself.

<input type="button" id="butt" value="button11111111111111" >
<script>
$("#butt").on('click',function(e)
{
$.ajax(
{
type:'POST',
url:'test.php',
data:product_type:"cake"
});
});
</script>

<?php
if(isset($_POST['product_type']))
$abc=$_POST['product_type'];

if(isset($abc))
echo $abc;
?>


Now when I try to run this code.I do get the ok status inside the Network Console of Chrome but this code doesn't echo the output.

I simply want to display the result that has been passed by the ajax method.

I am new to ajax and jquery so i don't know much about how they work exactly but is it possible?
If yes, then how could i achieve that without actually refreshing the page?

Answer

Here is what I think you want, i.e. test.php is the source page AND the ajax page!

<?php
    if(isset($_POST['product_type'])) {
        Header("Content-type: text/plain; charset=utf-8");
        $abc=$_POST['product_type'];
        if(isset($abc)) {
            echo $abc;
        }
    }
    else {
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">   </script>
<input type="button" id="butt"  value="button11111111111111" >
<script>
    $("#butt").on('click',function(e) {
        $.ajax({
            type:'POST',
            url:'test.php',
            data: {
                product_type:"cake"
            },
            success: function(data) {
                alert('got ' + data);
            }
        });

    });
</script>
</html>
<?php
    }
?>