I would like to build a web app using json, ajax and php to be more clear, I need a php page with different functions that can be called from ajax method
Eg: phppage.php
addmydetails()
{
logic goes here
}
ajax page
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "phppage.php/addmydetails",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
So my actual question is that any option to call the function like this in ajax post
url: "phppage.php/addmydetails"
No need for URL rewriting. Just get the PATH and use call_user_func. Something like this:
In your phppage.php:
$method = trim($_SERVER["PATH_INFO"], "/");
if(function_exists($method)){
call_user_func($method);
exit();
}
function Your_function_name(){
print "this is my function";
}
Then you can access it using this URL --> phppage.php/Your_function_name
Related
I have the below function in my WordPress functions file, and if I run it as below without the two parameters it works fine, but when I pass the parameters the error handler in the jQuery returns status 500.
If I don't pass the parameters to the PHP function I get status 200 from jQuery, but it's coming from the error handler, and not from the success handler. Why so?
function subscribe_funk(){//$payment_method, $customer_handle){
return "This is a test";
die();
}
It gets called from this ajax:
function subscribe(data) {
jQuery.ajax({
url: PT_Ajax.ajaxurl,
type: "POST",
data: {'action': 'subscribe_funk', 'payment_method': data.payment_method, 'customer_handle': data.customer},
cache: false,
dataType: 'json',
beforeSend: function(){
console.log('Before send subscribe');
},
complete: function(){
},
success: function (response) {
console.log('Message from success handler: ');
console.log(response);
},
error: function(xhr, status, error){
console.log("Message from error handler:")
var errorMessage = xhr.status + ': ' + xhr.statusText
console.log(errorMessage);
}
});
}
Your function expects 2 parameters, however WP/ajax is not passing them directly.
You need to fetch them from $_POST array yourself:
function subscribe_funk(){
$payment_method = $_POST['payment_method'];
$customer_handle = $_POST['customer_handle'];
return "This is a test";
die();
}
Also, you may want to sanitize the post data with sanitize_text_field() or similar function.
Here is a relevant thread in WP StackExchange: how to pass parameters from jQuery ajax to a PHP function
I have looked everywhere, I found, that FUELPHP not handle Ajax requests, native and easily, as does RubyOnRails for example.
There must be done manually through jquery, unless I'm missing something I see is this: you have to use preventDefault () for the submit event of the form to create a post, product or whatever, and use the $ function post () to send the relevant parameters, which I think is ridiculous for a framework that claims to be based on the best ideas from other frameworks.
Please tell me if I'm wrong, I like FUELPHP, and I'm thinking about choosing it as PHP framework, but I want to be clear about this.
why not you can handle ajax in fuelphp like this.
.01. create ajax request in your view or public/assets/ create javascript file,
<script> $('.login').on('click',function(){
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
alert("loading");
}, false);
return xhr;
},
url: "<?php echo \Uri::create('auth/login'); ?>",
type: "POST",
dataType: 'json'
data: {'username':$('#username').val(), 'password':$('#password').val()},
success: function (data) {
alert(data.status);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
});
</script>
.02. after that you can handle post data in classes/controller/ create auth.php and login method like this,
<?php
class Controller_Auth extends \Controller_Template {
function action_login() {
if (\Input::is_ajax()) {
if (\Input::param('username') and \Input::param('password')) {
$username = \Input::param('username');
$password = md5(\Input::param('password'));
//check password and username or anything
$msg = 'fail';
return json_encode(array('status' => $msg));
}
}
...
}
}
?>
you can handle data like this. i think you got something. and this is helpful.
I am using the following code to post form data to a php file..
jQuery("#form-submit").click(function(data){
var url = "save-data.php";
jQuery.ajax({
type: "POST",
data: jQuery('#my-form').serialize(),
url: url,
cache : "false",
success: function(data){
jQuery("#dl-message").html(data);
jQuery("#dl-message").css('background-color', '#0C3');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
},
error: function ( jqXHR, textStatus, errorThrown){
jQuery("#dl-message").html('There was an error saving your form: ' + errorThrown);
jQuery("#dl-message").css('background-color', '#F33');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
}
});
return false;
});
and then in my php file I am simply looking for $_POST['field-name'] to see if the contents of the form were posted. The ajax call returns successful, however no data from the form seems to be posted to the PHP file. When I call...
$name = $_POST['name'];
echo "Your name is: " . $name;
I get nothing.... Does anyone see anything wrong with my ajax call at all?
Thanks so much for your time...
So it seems the post was empty at the first place (btw you can include your last three posts inside the question by editing it). Are you sure your form's id is 'my-form'?
Updated Question to better reflect the communities support
Based on community support I have changed the Ajax function to be as such:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The resulting PHP Class is as such:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET['element_name'])){
$this->_element_name = $_GET['element_name'];
echo $this->_element_name;
}
}
}
The network tab shows that I have some out put from activating the Jquery which I have shown below:
The Console is spitting out no errors, yet not echoing the element name. I have read up on the Jquery Ajax API and everything I have been doing, thus far, seems to be correct. Yet I am not getting the desired out put.
Note: The response tab is empty.... In other words I am not getting a response back.
You're not passing in the event to your click handler.
Use.
$('a').click(function(e){
// Your code
});
$.ajax({
url : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(result) {
console.log(result)
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
Simplify the situation. Just for a moment, change your AJAX processor file (UncheckPackageThemeHelper.php) to read like this:
UncheckPackageThemeHelper.php
<?php
$test = $_POST['element_name'];
$r = 'PHP received: [' .$test. ']';
echo $r;
die();
Also, change your AJAX success function to read like this:
success: function(result) {
alert(result);
},
At least, this will show you that your AJAX is getting through.
Then, start adding things back into your AJAX processor file (one or two at a time) and keep echoing something out so that you can discover where the error is happening.
So I was doing a lot of things wrong. But this is the only way it works, for me - please post your comments if you have better solution.
In the class, I have to do this:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET["element_name"])){
$this->_element_name = $_GET["element_name"];
echo json_encode($this->_element_name);
}
}
}
new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();
The class cannot be instantiated in the .phtml file with the resulting Ajax or the request is never sent back. Also notice the json_encode You cannot pass regular variables back to Ajax - when in a class (I think) - How ever when not in a class it seems to work - clarification is needed.
The Ajax then looks like this:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The Data that comes back is what I expect: "aisis_options[package_RelatedPosts]"
There ar a couple of issues with this answer - One I dont understand why I have to instantiate the class inside the file its written in, and two not sure why I have to encode the response in a class, but not when its just a "script kiddy" file.
I have some jquery/php code which uses ajax to call another page.
var pall_id = $(this).attr('id');
$.ajax({
type: "POST",
url: "do_history.php?pall_id="+pall_id,
success: function (msg) {
alert (msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('Error submitting request.');
}
});
However what do I do to get the value of msg? e.g. if do_history.php is simply:
<?php
$text="text";
return $text;
?>
would 'msg' not be "text" so when I alert(msg); I would get "text" popping up on my screen.
What do I need to do to return a string value? Any ideas?
Thanks,
Use echo $text; and in your $.ajax options add dataType: 'text'.
However, a better solution would be using dataType: 'json' and then echo json_encode($text); - in this case $text could also be an array/object/number and it would be the appropriate type in the JavaScript function
.
You have to echo or print the variable since jquery fetches the output of your script. A simple return doesn't produce any output.
<?php
$text="text";
echo $text;
?>
You need to check jQuery mannual for function $.post,the success param is a function and have several params .The most common used param is msg which is the output by the request url.
you need to know the param msg is the output of request url(do_history.php),if you use return in do_history.php,the content($text) will not output to browser so the msg param will contain nothing.but if you use echo ,print etc, the content($text) will output to browser so the msg param will contain the value!
You need to output text on php side (print 'text'; // echo 'text')