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.
Why not to call an ajax function on the server side? You could do something like :
$('button').click(function()
{
$.ajax
({
type: "POST",
url: "some.php",
data: "val1:value&lvaln:valn",
success: function(msg)
{
alert( "Data Saved: " + msg );
}
});
return false;
});
Documentation here
Try not to embed php code into html. If you can avoid this practice, the better.
Hope it helps
JavaScript - Client Side.
PHP - Server Side.
You need to issue an AJAX call of some kind in order to communicate with the Server. There's no way for JavaScript to create directories on your Remote Server (this would be a huge security hole otherwise).
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.
Just do an ajax request and then execute the PHP server side:
$('button').click(function(){
$.ajax({url: 'mkdir.php'});
return false;
})
and the php:
<?php mkdir('/test1/test2', 0777, true); ?>
That's all you need.
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); ?>
You can greatly benefit from a framework supporting AJAX.
As author of Agile Toolkit I can recommend you to try it, the code would look like this:
$button=$page->add('Button');
if($button->setLabel('Create Directory')->isClicked()){
if(mkdir('/tmp/123', 0777, true)){
$button->js()->univ()->alert('Directory Created'); // executes JS code
}else{
$button->js()->univ()->alert('Problem'); // executes JS code
}
}
Other frameworks may offer other ways to simplify AJAX and keep it in one file.