Skip to content
Advertisement

How do I just run a php script with Ajax (no returns)

I’m trying to run a php script with ajax. All I want for it to do is just run the script, I don’t want any echos or anything. Is there a way to do this. Here is what I’ve tried:

        $('button')[1].click(function () {
          $.ajax({
            method: 'get',
            url: 'like.php',
            data: {
              id: $('button')[1].id
            },
            success: function(data) {
              console.log(data);
            }
          });

I thought that this would just run like.php with the get data I sent it but it is not working. I know that the php script works because when I type in the url with the id parameter manually it works.

Advertisement

Answer

This will clean up and work better for your “fire n forget” like buttons. Add a special class to only the buttons you want to do this:

<button class="like-it">I Likes!</button>

Then the jquery handler can be this:

$(document).ready(function() {
    $('body').on('click','.like-it',function(e){

        e.preventDefault(); // stops the button from doing something else
        $.get(  'like.php',
                { id : $(this).attr('id') },
                function(response) { console.log(response); }
             );

    });
});

You can test if your PHP is doing something, by simply returning something and inspecting the result in your console tab of the browser devtools. Since you are ignoring the result, you can echo anything for debugging in devtools. Then comment out the echo when you go to live.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement