Call PHP function from jQuery?
AJAX does the magic:
$(document).ready(function(
$.ajax({ url: 'script.php?argument=value&foo=bar' });
));
calling php function from jquery?
From jQuery you can only call php script with this function. Like that:
$.ajax({
url: 'hello.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert(response);
}
});
hello.php
<?php
echo "bye bye"
?>
using jquery $.ajax to call a PHP function
Use $.ajax
to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
On the server side, the action
POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}
I believe that's a simple incarnation of the Command pattern.
call php function with arguments using Jquery
You can't call a PHP function directly from an AJAX call, but you can do this:
PHP:
<? php
function func1($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo func1($_POST['callFunc1']);
}
?>
JS:
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { alert(response); }
});
How to call PHP function using jquery?
Change the type of the jquery Ajax code from post to get since you want to use the response, else I can't see something wrong there
How to call a PHP function from jQuery?
To anyone who might need some help with a similar issue, I'm sharing how I solved this one...
HTML
<form id="frm-addcart" method="post">
<input id="txt-quantity" class="text-center" type="number" value="1" required>
<input id="btn-submit" class="submitted btn-resize" type="submit" value="Agregar +">
<input type="hidden" id="checker-login" name="checker-login" value="isValid">
</form>
jQuery
$("#btn-submit").on("click", function (event) {
// DEFAULT ACTION OF THE EVENT WILL NOT BE TRIGGERED
event.preventDefault();
// GET THE VALUES FROM THE FORM
var clickBtnValue = "btn-addcart";
var checkerLogin = $("#checker-login").val();
var quantity = $("#txt-quantity").val();
// USE AJAX TO CALL THE PHP FUNCTION
$.ajax({
type : 'POST',
url : 'php/functions.php',
data : {
"action" : clickBtnValue,
"checkerLogin" : checkerLogin,
"quantityAdded" : quantity
},
success : function (data) {
// data IS THE VALUE THAT THE PHP FUNCTION RETURNS THROUGH echo
if (data == "valid") {
window.location.href = "home.html";
} else {
alert("Something went wrong.");
}
},
error : function() {
alert("An error has ocurred.");
}
});
});
php
if (isset($_POST["action"]) == true) {
switch ($_POST["action"]) {
case "btn-addcart":
insertData();
break;
}
}
function insertData() {
// GET DATA FROM AJAX PARAMETERS
$checkLogin = $_POST["checkerLogin"];
&quantity = $_POST["quantityAdded"];
// VALIDATE AND EXECUTE REST OF FUNCTION
// AND IF EVERYTHING GOES OK
echo "valid";
exit();
}
And that's it! I'm calling a PHP function from jQuery.
Enjoy!
How to call a php function from ajax?
For AJAX request
Include jQuery Library in your web page.
For e.g.<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Call a function on button click
<button type="button" onclick="create()">Click Me</button>
While click on button, call create function in JavaScript.
<script>
function create () {
$.ajax({
url:"test.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "abc@gmail.com"},
success:function(result){
console.log(result.abc);
}
});
}
</script>
On the server side test.php file, the action POST parameter should be read and the corresponding value and do the action in PHP and return in JSON format e.g.
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
// some action goes here under php
echo json_encode(array("abc"=>'successfuly registered'));
}
Run php function inside jQuery click
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); ?>
Trying to call PHP function using jQuery.post()
Your $.post()
is an AJAX request to index.php
. Whenever you make an AJAX request, or any HTTP request at all, the browser sends out a HTTP request to the server (the one hosting index.php
), and gets some data back in return. In the special case of HTTP AJAX requests, the browser sends HTTP request asynchronously without refreshing the page, and the response is received behind the scenes from server.
A typical AJAX POST call in jQuery should look like this:
$.post("index.php", {action: 'typer'}, function( data ) {
// do something with data, e.g.
console.log(data);
});
Your server file (index.php
) should then return some data to the AJAX request. Because you have used index.php
to serve AJAX data as well as normal HTML, it should look something like this:
<?php
function type_my_text() { ... }
// Either serve data to AJAX call, or serve HTML of index page.
if ($_POST['action'] == "typer"){
// serve AJAX call
type_my_text();
}
else {
// serve HTML
?>
<html>
...
</html>
<?php
}
But this is messy.
It would be preferable to apply some separation of concerns - use HTML files purely for serving HTML, and PHP purely for serving AJAX content. In other words, take your HTML and put it into index.html
, then create ajax.php
(or whatever name you want), and put your PHP code in it. You then wouldn't need to do ugly things like the above - mixing HTML code inside your PHP file. And of course, remember to change the URL in your JS.
Additional:
In your JS making the AJAX request, make sure you prevent the default browser action of submitting the form - which is a fresh page request. Otherwise, you aren't doing AJAX at all.
The cleanest way to do this in jQuery:
$('#my-form').on('submit', function(e) {
e.preventDefault(); // important - to prevent page refresh
$.post(...); // the AJAX call here
});
Then in your HTML:
<form id="my-form">
<input type="text" name="textfield">
<input type="submit">
</form>
Main things to note:
Give your form an ID so you can find it in jQuery efficiently. No action/anything else required.
I presume you'd do something with your
textfield
input after AJAX.Avoid using inline JS.
How can I call PHP functions by JavaScript?
Yes, you can do ajax request to server with your data in request parameters, like this (very simple):
Note that the following code uses jQuery
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
and your_functions_address.php like this:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
Related Topics
Get Order Increment Id in Magento
Check How Many Times Specific Value in Array PHP
Do I Have to Use MySQL_Real_Escape_String If I Bind Parameters
PHP - How to Get Shell Errors Echoed Out to Screen
Unserialize PHP Data in Python
Mysql: Group by Two Columns and Sum
Detect How Long It Takes for a File to Upload (Php)
PHP Readfile() Adding Extra Bytes to Downloaded File
Switching to Prepared Statements
Adding Additional Persist Calls to Preupdate Call in Symfony 2.1
How to Get Month from Date in MySQL
Easiest Way to Grab Filesize of Remote File in PHP
How to Convert a Huge Integer to Hex in PHP
Do I Need to Escape My Variables If I Use MySQLi Prepared Statements
PHP "Header (Location)" Inside Iframe, to Load in _Top Location