michelle
michelle

Reputation: 653

run php file on button click ajax

Entry level user here. I've seen countless AJAX\PHP examples with data being passed via POST or GET and modified one of their examples. When clicking the button (id="clickMe) I want it to execute advertise.php and nothing more (no variables need to be passed) without refreshing the page and a notification that says success. When I click the button with my current code nothing happens.

<button type="button" id="clickMe">CLICK ME TO RUN PHP</button>

<script type="text/javascript">
$(document).ready(function(){
$('#clickMe').click(function(event){ // capture the event
event.preventDefault(); // handle the event
$.ajax({
    url: 'advertise.php',
    data: {
        'ajax': true
    }, 
    success: function(data) {
        $('#data').text(data);
    }
});
});
});
</script>

Updated, but still isn't executing.

Upvotes: 0

Views: 1312

Answers (2)

hmak
hmak

Reputation: 3968

Here is your editted version code:

$(document).ready(function(){
    $('#clickMe').click(function(){
        $.post("PHP_FILE.php",{ajax: true},function(data, status){
             alert(data);
         });
    });
});

Upvotes: 1

Jay Blanchard
Jay Blanchard

Reputation: 34406

2 things - you need a document ready handler and to prevent the default click action.

$(document).ready(function() {
    $('#clickMe').click(function(event){ // capture the event
         event.preventDefault(); // handle the event
         $.ajax({ // remainder of code...
});

When loading jQuery scripts at the top of the page you need to make sure they do not run until the DOM has loaded, that is what the document ready handler is for. The you capture the click event by including it as an argument for your click's callback function and handle the click with the preventDefault() method.

Since this request is "simple" you may want to consider using one of the shorthand methods, like $.post()

Upvotes: 1

Related Questions