Basic PHP and Ajax Tutorial

Very Basic PHP and Ajax Tutorial

This tutorial will show a very simple setup to use Ajax with PHP. I will give a brief overview of the process. When the submit button with the 'contacted' class is clicked, the function goes to work. The myurl variable has the 'myurl' class and takes its value. It is the sibling of the submit button. If you look at the html, you can see the input elements are indeed siblings. 

After that, the Ajax call begins. A post request takes place and the value of the 'myurl' variable is transfered to the my_ajax.php file. At this point, the my_ajax.php file has a new post variable called my_variable. So, when you open up the my_ajax.php file, you can write code to do whatever you want with the variable $_POST['my_variable'].

Jquery / Ajax

<script type="text/javascript">

    $('.contacted').click(function () {

        var myurl = $(this).siblings('#myurl').val();

        $.ajax({
            type: "POST",
            cache: false,
            url: "my_ajax.php",
            data: { my_variable: myurl },

            success: function (msg) {
//  alert("Success!");
            }
        });
    });
</script>


HTML

<form method="POST" action="">
            <input id="myurl" type="hidden" name="contacted_url" value="yahoo.com"/>
            <input id="contacted" class = "contacted" type="submit" name="contacted" value="Submit"/>
</form>


Post URL

$source_url = $_POST['my_variable'];