Paul
Paul

Reputation: 1047

AJAX load PHP file and passing data and function?

I'm trying to pull in a PHP file via ajax and having a few issues.

This is my html/js:

<script>
function viewdata(){
    $.ajax({
        type: "GET",
        url: "getinfo.php",
        dataType: "html",
        success: function(data){
            $('.target').html(data);
        }
        error: function(data){
        }
    }).done(function(data){

    });
}

</script>

<div class="target"></div>

My issue is a 500 error and I've worked out it's not using a function I've delcared earlier on the page or passing a variable called "$urls" into the included file. The ajax call is in a foreach loop so the $urls is different each time.

My function (not used in the loop, it's declared before the loop)

function isSiteAvailible($urls){
    // some php code
}

How do I get the function and the variable into the "getinfo.php" file?

Thanks for your help!

Upvotes: 1

Views: 820

Answers (1)

Rik Lewis
Rik Lewis

Reputation: 749

If you want to get data into the file you're calling, the best way is with query parameters. Try something like...

function viewdata(){
  $.ajax({
    type: "GET",
    url: "getinfo.php?urls="+urls,
    dataType: "html",
    success: function(data){
        $('.target').html(data);
    }
    error: function(data){
    }
  }).done(function(data){
});
}

You can that access the parameter inside "getinfo.php" like this...

$urls = $_GET["urls"];

Obviously you should have some URL encoding in there, and validation on the server side to avoid security issues, but hopefully that helps get you started.

Upvotes: 1

Related Questions