How to call a php function from ajax? - php

I am familiar of how to get ajax to go to a php page an execute a series of things and then return json data. However is it possible to call a specific function which resides in a given page?
Basically what I want is to reduce the number of files in a project. So I can put a lot of common functions in one page and then just call whatever the function that I want at the moment.

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'));
}

You cannot call a PHP function directly from an AJAX request, but you can do this instead:
<? php
function test($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo test($_POST['callFunc1']);
}
?>
<script>
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { console.log(response); }
});
</script>

As a structure for this kind of purposes, I suggest this:
PHP
<?php
if(isset($_POST['action'])){
if ($_POST['action'] == "function1") { func1(); }
if ($_POST['action'] == "function2") { func2(); }
if ($_POST['action'] == "function3") { func3(); }
if ($_POST['action'] == "function4") { func4(); }
}
function func1(){
//Do something here
echo 'test';
}
?>
jQuery
var data = { action: 'function1' };
$.post(ajaxUrl, data, function(response) {
if(response != "") {
$('#SomeElement').html(response);
}else{
alert('Error, Please try again.');
}
});
As mentioned, you can't call a PHP function directly from an AJAX call.

If I understand correctly, yes you can.
Put all your functions in one php file and have the ajax pass as a parameter which one you want to call. Then with a switch or if structure, execute the one you want.

jquery:
$(document).ready(function(){
$('#tfa_1117700').change(function(){
var inputValue = $(this).val();
var v_token = "{{csrf_token()}}";
$.post(
"{{url('/each-child')}}",
{ dropdownValue: inputValue,_token:v_token },
function(data){
console.log(data);
$('#each-child-html').html(data);
}
);
});
});
php:
public function EachChild(Request $request)
{
$html ="";
for ($i=1; $i <= $request->dropdownValue; $i++)
{
$html = $i;
}
echo $html;
}

Related

PHP Not catching ajax request

I am having request like this:
$(function(){
$("#novaProfaktura").click(function(){
$.ajax({
type: "POST",
url: "../Pages/Program.php",
data: { action: "testing" },
success: function()
{
alert("Ajax done"); //Testing purpose
}
});
location.reload();
});
});
And then in my body I have php like this:
<div id="Content">
<?php
echo("Php running <br>");
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo("Post running <br>");
if($_POST['action'] = "testing")
{
echo("Action running <br>");
}
}
?>
</div>
What I am getting from this is alert message so I assume ajax is set up properly and getting Php running but it doesn't pass if($_SERVER['REQUEST_METHOD'] == 'POST'
As you can see jQuery code is running on div click.
What am I doing wrong?
EDIT: I have used function(data) and it seems to work BUT it doesn't return only echoed data but WHOLE page with echo. I used document.write() and it rewrite whole page but how to get particular echo value?
Answer for this was to instead of this:
success: function()
{
alert("Ajax done"); //Testing purpose
}
use this:
success: function(data)
{
alert("Ajax done"); //Testing purpose
document.getDocumentById('emptyDiv').innerHTML = data;
}
Now as data you are getting all HTML text from document you are running function from so instead of url: "../Pages/Program.php" I used separated file url: "../Php/Testing.php" and inside that file I have
only this code:
<?php
echo("Testing");
?>
$_POST['action'] = "testing"
This is variable assignment
$_POST['action'] == "testing"
This is comparison. You want this.
$_POST['action'] === "testing"
This is better because it's type matching too, it must be a string.

Execute php using jquery post

I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard

Ajax function issue on return true and false in wordpress

I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.

Not able to retrieve $_POST values through ajax call

I am having little problem with ajax. Here is my code what I have done so far:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
getLocation();
});
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
latitude =position.coords.latitude;
longitude= position.coords.longitude;
$.post({ url: 'test.php',
data : ({lat :latitude,long:longitude}),
success: function(data){
alert('done');
}});
}
What I am trying to do is call the function on document ready and trying to retrieve the value of ajax call on the same file where I did call this script. Whenever I reload the page, I don't get any value of :
print_r($_POST['lat']);
I don't know what is the actual problem,I already checked in console and didn't get any error. Please help.
To get the value you need to print it in success callback
$.post({ url: 'test.php',
data : ({lat :latitude,long:longitude}),
success: function(data){
alert(data);
}
});
and if you put
if (isset($_POST['lat']) {
print_r($_POST['lat']);
}
you will get the value in alert box.
EDIT: You can check in php if the reqest came from Ajax using this:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
if (isset($_POST['lat']) {
print_r($_POST['lat']);
}
exit();
}
if you put this at the begining you will see only that print_r from ajax call.
The value you are printing is not an array. So you have to print it like,
print $_POST['lat'];
(OR)
echo $_POST['lat'];
AND NOT
print_r($_POST['lat']);
If you want to print all post values mean then you can print it as,
print_r($_POST);
I have solved my problem by own. Here what I have done. I made one more file called test2.php and put my php script over there and call that file in my ajax call. Here the code.
Test.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
getLocation();
});
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
latitude =position.coords.latitude;
longitude= position.coords.longitude;
$.ajax({ url: 'test2.php',
data : ({lat :latitude,long:longitude}),
type: 'post',
success: function(data){
if(data=='true'){
window.location = "http://example.com";
}
}
});
}
</script>
Test2.php
//just for example
<?php
echo 'true';
?>
Hope this will help someone in future.

Kohana - how to create form without refresh?

How to create jQuery + ajax form without refresh?
This is my controller and views:
http://pastebin.com/GL5xVXFZ
In "clear" PHP I create something like this:
$(document).ready(function(){
$("form#submit").submit(function() {
var note = $('#note').attr('value');
$.ajax({
type: "POST",
url: "add.php",
data: "note="+ note,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
in add.php file is INSERT to Database.
There are more complicated ways of doing this for example detecting an ajax request in your action and then if detected print out a javascript response. The way you would do this is
JAVASCRIPT
function postForm(note){
$.ajax({
url : '/controller/action',
type : 'POST',
data : 'note='+note,
success : function(jsn){
var json = $.parseJSON(jsn);
if(json.status == 200)
alert('Completed Successfully');
else
alert('Not Completed Successfully');
},
error : function(xhr){
//Debugging
console.log(xhr);
}
});
}
PHP
<?php
Class Controller_ControllerName extends Controller_Template{
public $template = 'template';
public function action_index(){}
public function action_form(){
$this->auto_render = false; // <-EDITED
$array = array();
//PROCESSING FORM CODE HERE
if($success){
$array['status'] = 200;
}else{
$array['status'] = 500;
}
print json_encode($array);
}
}
?>
this is an example i have done without testing but this surely should be enough for you to work on

Categories