Call PHP Function from Jquery

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"
?>

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 a php function from ajax?

For AJAX request

  1. 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>
  2. Call a function on button click

    <button type="button" onclick="create()">Click Me</button>
  3. 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'));
}

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:

  1. Give your form an ID so you can find it in jQuery efficiently. No action/anything else required.

  2. I presume you'd do something with your textfield input after AJAX.

  3. Avoid using inline JS.

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 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

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.



Related Topics



Leave a reply



Submit