How to get the url for a ajax page? - php

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.

Related

jQuery send a query strings value as POST instead of GET

One of my php pages was changed to handle POST data (in order to accommodate a few form text fields), instead of GET (which was previously used).
So now, instead of if($_GET) { } it uses if($_POST) { }. They (team) wont allow both methods using ||.
I need to send a querystring to that same page using jQuery, but because of if($_POST) { }, it will not get through.
The querystring is formed from this : <i class="icon-hand remove" data-handle="se25p37x"></i>
I used to send it using jQuery ajax before, but that will not work now. Any idea how I can send it as POST?
$('.remove').live('click', function() {
var self = $(this);
var handle = $(this).data("handle");
if(handle) {
$.ajax({
type:"POST", // this used to be GET, before the change
url:"/user/actions/"+handle,
dataType:'json',
beforeSend:function(html) {
},
Just change type: "GET" to type: "POST" and add data parameter:
...
type: "POST",
data: $('form').serialize(), // OR data: {handle: $(this).data("handle")}
dataType: 'json',
...

jQuery Ajax(post), data not being received by PHP

The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}

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

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.

Can I access the href of my ajax request in the javascript of my request?

Here a sample use case:
I request a simple form via an ajax request. I want to submit the result to the same page that I requested. Is there a way to access the URL of that request in the resulting request's javascript?
Below is some code that accomplishes what I want via javascript AND PHP. The downside to this is that I have to include my javascript in the same file as myajaxform.php. I'd rather separate it, so I can minify, have it cached etc.
I can't use location.href, b/c it refers to the window's location not the latest request.
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : '<?= $_SERVER['PHP_SELF'] ?>',
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});
If there's not a way to access it via javascript directly, how would you solve this problem so that the javascript can go in it's own file? I guess that I could in the original ajax request's success handler, create some sort of reference to the URL. Thoughts? Maybe something using the jQuery data method?
You can store the url to submit to in the action attribute of the form, and then set the url to frm.action:
jQuery.ajax({
url : frm.action,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
Forgive me if I totally misinterpret your question, as I find it somewhat confusing. What about
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : window.location.href,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});

Categories