I need to find a way to use a js variable in wordpress query string. I know it involves ajax but i don't know how to go about it. Please help!
<script>
$(document).ready(function(e) {
var x=$(this).find('.resp-tabs-list li').attr('id');
//alert(x);
});
$('.resp-tabs-list').on('click',function(e){
var x = $(this).find('.resp-tab-active').attr('id');
//alert(x);
});
</script>
In the code above, i fetch 'x', which is the category id, based on which i want to fetch posts in a loop.
You are correct that it does involve ajax. You'll need to do something like the following (I haven't tested it, but it should put you on the right track):
Javascript (assuming you have jQuery loaded, and that you've used PHP to output the admin url as a javascript variable ajaxurl):
$(document).ready(function() {
bindCategoryFilter();
}
function bindCategoryFilter() {
$('.resp-tabs-list').on('click',function(e){
var x = $(this).find('.resp-tab-active').attr('id');
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
//this is the name of our Wordpress action we'll perform
'action' : 'get_ajax_posts',
//this is the important line--send 'x' to the server as category
'category' : x
},
success: function(data) {
//do whatever with the data you're getting back
//with the PHP below, it's an array of the post objects
}
});
});
This will POST data to our server, with the variable 'category' set to x in the $_POST variable. To access this, in your functions.php you would want to add something like the following:
//add our action hooks--wp_ajax_XXXXX is defined in the ajax query as 'action'
//the second argument is the name of the PHP function we're calling
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
function get_ajax_posts() {
if(isset($_POST['category'])) {
//get all the posts in the category, add more arguments as needed
$posts = get_posts(array('category' => $_POST['category']));
//data is returned to javascript by echoing it back out
//for example, to return all of the post objects (which you probably don't wnat to do)
echo json_encode($posts);
//we're done
die();
}
}
See the wordpress codex for more information about AJAX and Wordpress.
Related
I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.
I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):
$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";
//this is the file that contains the above query variable
require('custom/Connection.php');
$owner_arr = array();
//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}
This generates a list of name records pulled from the database in a Alias(first name) Last Name format.
Here's where I'm having trouble
Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.
I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:
$.ajax({
type: 'POST',
data: 'listRefresh();',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function() {
alert("this succeeded?");
}
});
The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?
Your ajax call is wrong. The 'data' value is what you send to the server.
Try this:
$.ajax({
type: 'POST',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function(data) {
listRefresh(data);
alert("this succeeded?");
}
});
The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.
In alternative, you could just reload the page putting location.reload(); into success function
I have php function that checks if an entry exists in my database that I call with class::checkThis($my_entry);
In my script javascript is used to determined the name of the folder I am selecting, so $my_entry is supposed to look like this :
(in normal is determined by php and the part in bold is what is determined by javascript)
C:/library/user/apatik/folder1
As you guess I can't find a working way to mix up thoses languages, and I don't really have any experience in javascript yet to figure out this.
The php code that returns the first part of the path is simply $_SESSION['cwd'].'/' and the javascript variable that returns the selected folder's name is data_name and is determined by var data_name = $(this).attr('data-name');
Is there a way to get something like if (class::checkThis($_SESSION['cwd'].'/'.data_name) == true) ?
None of what I tried so far worked and I'm having troubles finding an alternative.
Thanks for the help
You'll need to make an AJAX request to accomplish this. You'll load the page as normal, except for the dynamic part. Then you can populate the dynamic part (I've illustrated it as #content here) based on the result of the AJAX call:
var data_name = $(this).attr('data-name');
...
$.ajax('http://example.com/my_php_script.php?data_name=' + data_name)
.done(function(data){
// "data" is the resulting output of the PHP script
$('#content').append(data);
});
NOTE: The solution above uses jQuery.
Then, in your my_php_script.php, you can do something like this:
if (class::checkThis($_SESSION['cwd'] . '/' . $_GET['data_name']) == true) {
...
}
Ajax jQuery is your best solution.
This one using post method with event, just for reference...
Am I exist?
Am I exist too?
$('.anchor').click(function(){
var data_name = "name=" + $(this).attr('data-name');
$.ajax({
type: "POST",
url: "is_exist.php",
data: data_name,
success: function (data) {
alert(data.response);
}
});
};
is_exist.php
if(isset($_POST['name'])){
$data['response'] = class::checkThis($_SESSION['cwd'].'/'.$_POST['name']) == true ? "exist" : "buried";
echo json_encode($data);
}
I have a php file with a lot of checkboxes on the left hand side. I extract the values via javscript and pass them into an array. Which works just fine. I would like to pass then this array via Ajax to PHP in order to mess around with the values and create SQL-statements out of them.
$(document).ready(function(e) {
$('#getSelectedValues').click(function() {
var chkBoxArray = [];
$('.graphselectors:checked').each(function() {
chkBoxArray.push($(this).val());
});
for (var i = 0; i < chkBoxArray.length; i++) {
console.log(i + " = " + chkBoxArray[i]);
}
$.ajax({
url: 'index.php', // (1)
type: 'POST',
dataType:'json',
data: chkBoxArray, //(2)
success: function(data){
console.log(data.length);
console.log(data);
}
});
});
});
Several questions:
(1) what file name do I need to add here? The origion or the target?
(2) I have numerous ways of this: serialization, with these brackets {}, and so on. How to get it done right?
An error that I get is the following:
Notice: Undefined index: data in graph.php
That makes me wondering a bit, because it clearly shows no data is being send.
var_dumps on $_POST and $_SERVER offer these results:
array(0) { }
array(0) { }
which is somewhat unsatisfying.
Where am I doing things wrong? The only puzzling aspect is the ajax, all other stuff is not much of an issue.
The site is supposed to work in the following way:
Page -> Checkbox(clicked) -> Button -> result (ajax) -> PHP fetches result -> SQL DB -> PHP gets DB result -> fetch result (ajax) -> jslibrary uses result for something.
1- You need to point your ajax to the script that will use the data you are sending. I would not recommend to point to index.php, since you'll need to add a if statement checking if there is data on $_POST that is exactly what your're expecting, otherwise it will return the same page that you're in (considering that you are in index.php and is making a request to index.php). A point to consider. Since it is a whole request and it's not a method call to actually return something to your page you need to echo things. That said, consider also to set header('Content-Type: application/json') then, since you're expecting dataType: 'json', echo json_encode($objectorarray);
2- Since you're sending a Javascript array to PHP, it can't interpret correctly the structure, that is why you should use JSON.stringify(chkBoxArray) before sending it. But just setting it on data attribute would send the number of checkboxes you selected as values to POST, so consider to data: {myCheckboxValues: JSON.stringify(chkBoxArray)}
In your PHP script, considering all the security measures to take, you can $foo = json_decode($_POST['myCheckboxValues']);
Well, of course you need to pass the target page as url in your ajax call. It can't guess which file should process the data.
As for the data property. You need to give your data a name.
data: {
something: "something"
}
Becomes: $_POST['something']. (value: something)
$.ajax({
url: 'target.php', // (1)
type: 'POST',
dataType:'json',
data: { data: chkBoxArray }, //(2) Now $_POST['data'] will work
success: function(data){
console.log(data.length);
console.log(data);
}
});
I am trying to pass a variable from my javascript code over to the server side PHP code. I know this must be done via an ajax call which i believe i have done correctly, however accessing the variable i pass from my ajax into my php is when i run into trouble as i am new to php. Here is my code i have thus far:
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data: "userID=" + userID,
success: function(data)
{
alert("success!");
}
});
});
});
<?php //logtime.php
$uid = isset($_POST['userID']);
//rest of code that uses $uid
?>
I'm trying to pass my javascript variable "userID" to php ($userID), however i've gone wrong somewhere along the road. Thanks for the help!
Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):
data: { userID : userID }
And in your PHP do this:
if(isset($_POST['userID']))
{
$uid = $_POST['userID'];
// Do whatever you want with the $uid
}
isset() function's purpose is to check wheter the given variable exists, not to get its value.
Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset is a function to check if something exists and has a value, not to get access to the value.
Change your PHP to be:
$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;
The above line will check to see if the post variable exists. If it does exist it will set $uid to equal the posted value. If it does not exist then it will set $uid equal to 0.
Later in your code you can check the value of $uid and react accordingly
if($uid==0) {
echo 'User ID not found';
}
This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.
To test if the POST variable has an element called 'userID' you would be better off using array_key_exists .. which actually tests for the existence of the array key not whether its value has been set .. a subtle and probably only semantic difference, but it does improve readability.
and right now your $uid is being set to a boolean value depending whether $__POST['userID'] is set or not ... If I recall from memory you might want to try ...
$uid = (array_key_exists('userID', $_POST)?$_POST['userID']:'guest';
Then you can use an identifiable 'guest' user and render your code that much more readable :)
Another point re isset() even though it is unlikely to apply in this scenario, it's worth remembering if you don't want to get caught out later ... an array element can be legitimately set to NULL ... i.e. it can exist, but be as yet unpopulated, and this could be a valid, acceptable, and testable condition. but :
a = array('one'=>1, 'two'=>null, 'three'=>3);
isset(a['one']) == true
isset(a['two']) == false
array_key_exists(a['one']) == true
array_key_exists(a['two']) == true
Bw sure you know which function you want to use for which purpose.
Alternatively, try removing "data" and making the URL "logtime.php?userID="+userId
I like Brian's answer better, this answer is just because you're trying to use URL parameter syntax in "data" and I wanted to demonstrate where you can use that syntax correctly.
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id'); // you can add here your personal ID
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data : {
action : 'my_action',
userID : userID
},
success: function(data)
{
alert("success!");
console.log(data);
}
});
});
});
$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 'ID not found';
echo $uid;
$uid add in your functions
note: if $ is not supperted than add jQuery where $ defined
I'm using the JQuery AJAX function to deliver data to a PHP doc.
Currently, the AJAX success function returns HTML which gets added to the html page.
My goal is for the success function to return a second/different piece of data that can be used as a JavaScript variable.
How can this be done?
Update
The question was answered correctly. Here is an example of the resulting script.
PHP Document
<?php
$some_html = 'foo';
$some_value_for_js_variable = 'bar';
// create json content
echo "{";
echo "\"some_html_outupt\":\"$some_html\",";
echo "\"some_value_for_js_varialbe_output\":\"$some_vale_for_js_variable\"";
echo "}";
?>
JS Document
// Jquery ajax function
$.ajax({
dataType: 'json',
type: "POST",
url: "some_file.php", // the location of the above mentioned php script
cache: false,
success: function(json) {
$(el).html(json['some_html_output']); // add html output to page
var a = json['some_value_for_js_varialbe_output']; // assign value to js varialbe
}
}
}); // ajax
The way that I would implement this is to return the data in a JSON string with 2 items in it The first part would hold the HTML and the 2nd part holding the data for the variable that you want.
{"html":{html},
"2nd variable":"{data}"}
and then you can do a $.getJSON call to your web server like
$.getJSON('path','querystring=if_needed',function(data){
var html = data['html'];
var 2ndVariable = data['2nd Variable']
//do other things that you want
});
I hope that helps