WordPress post request in my plugin - php

I am trying to make a post request in my plugin, but I am not sure if it is reaching the desired function or not. I try to echo, return value but nothing seems to work. Here is my jquery
$.post({
url: "http://localhost/tutorials/wordpress/wp-admin/admin-post.php",
type: "POST",
cache: false,
data: {
action: "add_order"
// parameters:parameters,
//orderAddress : orderAddress,
//order : order
},
success: function(response) {
console.log(response);
secondStep.hide();
pricing.hide();
$('.thirdStep').show();
}
});
My function on the WordPress server end is this
function prefix_admin_add_order() {
echo 2; // or return 2;
}
Just trying to return anything from the function and trying to console log it in the response. But it doesn't work. Any pointers?

Your Php file must be as a page template and you must address it like this :
http://yourdomain.com/ajax
and in your jquery you must put this url

Related

How can I set a jquery var to be another jquery ajax functions callback

Sorry for my terms incase they are incorrect, but I have a php function that I am going to interop with ajax so I can use a php function to get a value for a jquery variable.
So now I am just at the point where I have received the ajax callback and would like to set the jquery variable to the response value I got back. Here is my code as an example:
$(document).ready(function() {
$('body').videoBG({
position:"fixed",
zIndex:0,
mp4:'', //This is where I want to use the ajax response value
opacity:1,
});
})
jQuery.ajax({
type : "POST",
url : "index.php",
data : {
request : "getvideo_Action"
},
success : function(response) {
alert(response);
//Do my response stuff
}
});
So basically what I want to do is set the 'Mp4' var(or is it property?) with the value that I get from the response. Can anyone help me out with this? Thanks.
You can put the entire thing inside the success function, like this:
jQuery.ajax({
type: "POST",
url: "index.php",
data: {
request: "getvideo_Action"
},
success: function (response) {
$('body').videoBG({
position: "fixed",
zIndex: 0,
mp4: response,
opacity: 1
});
}
});

Jquery Javascript Variable

Hello i have searched the whole website for a soltution found something but didnt get it to work.
-I have the main function on the head area of the page. (This will return Data from a PHP)
-This Data i need as a variable but dont know how to handle.
function note(content,usern){
note = Function("");
$.ajax({
type: "POST",
url: "note.php",
data: {'token': content, 'user': usern }, success: function(data){ var myneededvar = data; }, }); }
Ok thats works and also data is given out
Now im calling the function in the script like this
note(token,notename);
and i need the result myneededvar
but cant get it to work.
Firstly, your variable myneededvar is local to the success handler function and will not be available outside.
Secondly, your AJAX call is asynchronous and you cannot expect to immediately get the AJAX return data in a variable right after the AJAX call statement.
i.e., you cannot do:
note(...); // call your method
alert(myneededvar); // this won't work as the AJAX call wouldn't have completed
Thirdly, not sure why you have that note = Function(""); statement there. You should remove that.
Something like this should work:
var myneededvar;
function note(content, usern){
$.ajax({
type: "POST",
url: "note.php",
data: {'token': content, 'user': usern },
success: function(data){
myneededvar = data;
// use it here or call a method that uses myneededvar
}
});
}

Javascript executes before getting result from a ajax call

I have the following code which displays session data.The problem am facing is even if the session has value and the ajax get that data the alert that I have put below the function call getValFromSession(qes) always shows null data.I think this is due to the asynchronous execution of ajax with in the javascript.So I put some extra code as shown in the function
getValFromSession(qid).How can I overcome this asynchronous issue?
var qes=$('#qsid_'+q).val();
var res=getValFromSession(qes);
alert(res);//always shows null value
$('#select_'+).val(parseInt(res));
function getValFromSession(qid)
{
return $.ajax({
url : site_url_js+"controller/getValFromSession",
type : "POST",
data : "qid="+qid,
cache: false,
async: false
}).responseText;
}
/*controller*/
function getValFromSession()
{
echo $_SESSION['time'][$_REQUEST['qid']];
}
Try this:
var qes=$('#qsid_'+q).val();
var res=getValFromSession(qes);
function getValFromSession(qid)
{
$.ajax({
url : site_url_js+"controller/getValFromSession",
type : "POST",
data : "qid="+qid,
cache: false,
async: false,
success: function(data) {
alert(data); // alert here in successHandler
$('#select_'+).val(parseInt(data));
}
})
}
/*controller*/
function getValFromSession()
{
echo $_SESSION['time'][$_REQUEST['qid']];
}
Hope this helps.
$.ajax provides you with a success, error and complete callback handlers. Populate your response text in those handlers because the way you have implemented is synchronous and would execute immediately instead of after the request completes.
Docs
You can put your code into a function and call that function on success event of AJAX as below
---
---
return $.ajax({
url : site_url_js+"controller/getValFromSession",
type : "POST",
data : "qid="+qid,
false,
async: false,
success: finalfunction
---
---
function finalfunction(res)
{
alert(res);//always shows null value
$('#select_'+).val(parseInt(res));
}

Wordpress - fetch user info using jQuery ajax POST request

I am working in Wordpress trying to use an ajax request to fetch user data by passing the user id.
I can see that the user id sends correctly via AJAX POST but I am getting an internal error message and I don't know why.
At first I thought it was because I was trying to fetch some custom fields that I had added to the user profile but even when I simplified my script I am still getting the error message.
Any help is much appreciated!
Front End
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: 'wp-content/themes/twentyeleven/author_info.php',
data: {id: id},
dataType: 'html',
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
author_info.php
$user_id = $_POST['id'];
$forename = get_the_author_meta('user_firstname', $user_id);
$output = $user_id;
echo $output;
Error Message
500 (Internal Server Error) jquery.min.js:4
Mathieu added a hackable approach to intercepting a request and redirecting it, which is fine. I prefer to build out AJAX responses that return json_encoded arrays.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
url: 'http://absolute.path/wp-admin/admin-ajax.php',
data: {'action' : 'ajax_request', 'fn': 'getAuthorMeta', 'id': id},
dataType: 'json',
success: function(data) {
//We expect a JSON encoded array here, not an HTML template.
}
});
return false;
});
Now we build out the function to handle our ajax requests.
First, we need to define our ajax add_action method ->
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');
We need to use both add_action lines here. I won't get into why. You'll notice the _ajax_request here. This is the 'action' that we sent over in our AJAX function data: {'action' : 'ajax_request'}. We use this hook to validate our AJAX request, it can be anything you'd like.
Next, we'll need to build out or function ajax_handle_request.
function ajax_handle_request(){
switch($_REQUEST['fn']){
case 'getAuthorMeta':
$output = ajax_get_author_meta($_REQUEST['id']);
break;
default:
$output = 'That is not a valid FN parameter. Please check your string and try again';
break;
}
$output = json_encode($output);
if(is_array($output)){
return $output;
}else{
echo $output;
}
}
Now let's build our function to actually get the author meta.
function ajax_get_author_meta($id){
$theMeta = get_the_author_meta([meta_option], $id);
return $theMeta;
}
Where [meta_option] is a field provided by WP's native get_the_author_meta function.
At this point, we'll now go back to our success:function(data) and (data) is a reference to the json_encoded array we've returned. We can now iterate over the object to get our fields and output them into the page as you'd like.
You are not in a POST at that moment because you are calling a specific page of your template that probably doesn't correspond to any article in your blog.
Instead, create a pluggin that will do this:
add_action('template_redirect', 'my_author_meta_intercept');
function my_author_meta_intercept(){
if(isset($_POST['getAuthorMeta'])){
echo get_the_author_meta('user_firstname', $_POST['getAuthorMeta']);
exit();
}
}
This will short circuit the request to the same page as before when you call it using:
http://mysite/mycurrenturl?getAuthorMeta=testMetaKey
So calling that post normally will return the article as usual, but if you pass in ?getAuthorMeta, it will stop the template from being selected and simply return the exact content you want it to return.
In your page, you just have to change your javascript to:
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: window.location.href,
data: {getAuthorMeta: id},
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
Just make sure you adapt the concept to what you need!
I would rather recommend you to use WP AJAX action method.
As in your case, add the following to your functions.php file.
add_action('wp_ajax_get_user_info', 'ajax_get_user_info');
add_action('wp_ajax_nopriv_get_user_info', 'ajax_get_user_info');
function ajax_get_user_info() {
//Handle request then generate response using WP_Ajax_Response or your html.
}
then in javascript tag.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
jQuery.post(
ajaxurl, /* if you get error of undefined ajaxurl. set it to "http://example.com/wordpress/wp-admin/admin-ajax.php"*/
{
'action':'get_user_info',
'user_id':id
},
function(response){
alert('The server responded: ' + response);
}
);
});
I would recommend you to read the 5 tips for using AJAX in WordPress.
p.s; Code above is not tested, it may have errors. but you get the idea.

How to get the url for a ajax page?

I'm pretty new to ajax and I applied it succesfully to a Drupal site. But I was wondering, how do I get an URL to a page where part of the content is loaded through ajax. Is this even possible? The JSON object is retrieved on click, so how do I make it work when retrieving a certain URL?
I realize this is a very broad questionany, any help would be greatly appreciated.
Thanks in advance!
My JS looks like this:
Drupal.behaviors.ajax_pages = function (context) {
$('a.categoryLink:not(.categoryLink-processed)', context).click(function () {
var updateProducts = function(data) {
// The data parameter is a JSON object. The films property is the list of films items that was returned from the server response to the ajax request.
if (data.films != undefined) {
$('.region-sidebar-second .section').hide().html(data.films).fadeIn();
}
if (data.more != undefined) {
$('#content .section').hide().html(data.more).fadeIn();
}
}
$.ajax({
type: 'POST',
url: this.href, // Which url should be handle the ajax request. This is the url defined in the <a> html tag
success: updateProducts, // The js function that will be called upon success request
dataType: 'json', //define the type of data that is going to get back from the server
data: 'js=1' //Pass a key/value pair
});
return false; // return false so the navigation stops here and not continue to the page in the link
}).addClass('categoryLink-processed');
}
On the begining of the page load ajax based on hash part of the url page#id,
$(document).ready(function() {
$.ajax({
type: 'POST',
url: "/path/to/page",
success: updateProducts,
dataType: 'json',
data: 'id=' + window.location.replace(/.*#/, '')
});
$('a.categoryLink:not(.categoryLink-processed)', context).click(function () {
$.ajax({
type: 'POST',
url: "/path/to/page",
success: updateProducts,
dataType: 'json',
data: 'id=' + this.href.replace(/.*#/, '')
});
});
Or you can use jquery-history but I didn't test it.
I don't know what exactly you are trying to do. But unless you have a module that creates the JSON data you need to do it yourself.
You would need to create a menu callback with hook_menu. In the callback function you can return json data by using drupal_json.
If you create the menu callback etc yourself, the URL will be whatever you make it to. Else you just have to use the URL defined by the module you want to use.

Categories