Bijan
Bijan

Reputation: 8586

PHP pass argument in Ajax

In my PHP file I have a variable $file = "abc". How would I create a button in HTML to run a function in PHP passing in $file as an argument? I saw that I need to do this using jQuery/AJAX. For the sake of simplicity, let's just say I want to echo $file.

HTML/JS

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.js"></script>
<input type="submit" class="button" name="Del" value="Del" />
<script type="text/javascript">
$(document).ready(function(){
    $('.button').click(function(){
        var clickBtnValue = $(this).val();
        var ajaxurl = 'ajax.php',
        data =  {'action': clickBtnValue};
        $.post(ajaxurl, data, function (response) {
            console.log(response);
            //alert("action performed successfully");
        });
    });

});
</script>

ajax.php

<?php
if (isset($_POST['action'])) {
    Del();
}

function Del($file) {
    echo $_POST['action'];
    echo $file;
    exit;
}
?>

I am unsure of how to modify this to pass in a php argument ($file) through AJAX.

Upvotes: 0

Views: 704

Answers (2)

Graham S.
Graham S.

Reputation: 163

You could probably pass in the value into a <span id="myFile"></span> that you could put right before the closing </body> tag, and then use jQuery to get the value and then remove it right after. I'm not saying it's the best or safest approach, but it's worked in the past for me with simple things.

HTML

    ...
    <span id="myFile"><?php echo $file; ?></span>
</body>
    ...

JS

$(document).ready(function(){

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

        //Get the text and remove it
        var myFile = $("#myFile").text();
        $("#myFile").remove();

        var clickBtnValue = $(this).val();
        var ajaxurl = 'ajax.php',
        data =  {action: clickBtnValue, file: myFile};
        $.post(ajaxurl, data, function (response) {
            console.log(response);
            //alert("action performed successfully");

            //Append it back in case you need to use it again. Optional
            $("body").append("<span id='myFile'></span>");
        });
    });
});

I took the quotes off of action.

PHP

<?php
    if (isset($_POST['action'])) {
        Del($_POST['file']);
    }

    ...
?>

Upvotes: 0

Eric Ping
Eric Ping

Reputation: 359

In your HTML/JS:

data =  {'action': clickBtnValue, 'file' : '<?php echo $file?>'};

In your ajax.php:

if (isset($_POST['action'])) {
    Del($_POST['file']);
}

This is a very simple example but you can probably adapt it to your needs. Note that there are a ton of potential security implications with this approach, depending on what you're actually doing, so be careful and clean any input in $_POST.

Upvotes: 2

Related Questions