Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Ajax with jQuery - Execute PHP File

Tags:

jquery

ajax

php

For some reason I can't get this to work. All I want to do is that when a button is clicked, (via ajax) a php file is executed. Aka, if I weren't using ajax, we'd be looking at:

<a href="file.php">dfgdfg</a>

I want the file to be executed without leaving the page.

This is what I've got atm:

$(".vote-up").live('click', function(e) {
$.ajax("file.php", function(){
       alert("Executed file");
   });
});

That doesn't seem to be working. I'm just really confused how the jQuery ajax function functions in general, without dealing with anything remotely complicated.

Added question:

.ajax({
       url: 'includes/login-check-jquery.php',
       success: function (data) {
            if(data == 1){
                alert("Logged in!!!");
            }else{
                window.location = data;
            }
        error: function (xhr, status, error) {
        // executed if something went wrong during call
        if (xhr.status > 0) alert('Error: ' + status); // status 0 - when load is interrupted
        }
    });
});

In the above code, if the data returned equals "logged in" than a message box appears. Otherwise it'll redirect to the location (that is sent in data). For some reason this if statement isn't working, but the data is being returned as expected.

My PHP code is:

<?php  
if (!$user->logged_in){
    echo "../login/index.php";
}else{
    echo "1";
}

?>

Any ideas?

like image 616
Andrew Avatar asked Jul 15 '26 07:07

Andrew


1 Answers

If you don't want to leave the page, do

$(".vote-up").live('click', function(e) {
    e.preventDefault();
    ...

And ajax could be updated, if desired to

$.ajax({
    url: 'file.php',
    success: function (data) {
        // this is executed when ajax call finished well
        alert('content of the executed page: ' + data);
    },
    error: function (xhr, status, error) {
        // executed if something went wrong during call
        if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
    }
});

error callback part could be removed, if you go for simplicity and not usability and some more options could be added by referencing jquery ajax doc.

like image 52
i-- Avatar answered Jul 17 '26 20:07

i--