Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run php function inside jQuery click

How do i run a PHP function inside jQuery click event. I have the following which is not correct. when the user clicks on a button, i want a new directly created.

$('button').click(function(){
  <?php mkdir('/test1/test2', 0777, true); ?>
  return false;
})
like image 702
Pinkie Avatar asked May 24 '11 21:05

Pinkie


3 Answers

You cannot run PHP code inside a jquery function. PHP runs on the server-side whereas jquery/javascript runs on the client-side. However, you can request a PHP page using jquery and with the PHP code on that page will run the mkdir that you want.

JS:

$.ajax({
  url: 'test.php',
  success: function(data) {
    alert('Directory created');
  }
});

test.php FILE:

 <?php mkdir('/test1/test2', 0777, true); ?>
like image 164
Cargowire Avatar answered Oct 11 '22 02:10

Cargowire


First of all you should understand how php works (no offense but this is essential). Why PHP script is not workig in a web browser? To accomplish what you need you have to use ajax (to request a script on the server using javascript)

PHP File (createdir.php):

<?php 
    mkdir('/test1/test2', 0777, true); 
?>

JavaScript Code:

$('button').click(function() {
    $.ajax({
        url: 'createdir.php',
        success: function(){
             alert('dir created');
        }
    });

    return false;
});

I have not validated if the code acually works. If you encounter any problems you should have a look at the jquery documentation (it's awsome :-) ) http://api.jquery.com/jQuery.ajax/

like image 42
Flatlin3 Avatar answered Oct 11 '22 04:10

Flatlin3


You are mixing up client side and server side code here. The PHP code is already executed on the server when the user clicks the button and therefore nothing will happen. You can use the xmlhttprequest (or ajax) for this.

like image 3
Bas Slagter Avatar answered Oct 11 '22 02:10

Bas Slagter