some Plugins that use Ajax in Wordpress only work when you are logged in as admin or added these hooks:
add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
But I'm really having a hard time with getting everything to work for non-admin users and I'm wondering if there is a easy way (for js/php noobs) to tell wordpress to globally activate all ajax functions for alls users, wether logged in or not.
I know this is probably a very stupid and risky way if that is possible somehow, but please let me know!?!!?
PHP wise, you've hit the nail on the head with your code above. This is required for each AJAX action, as each action will of course call a different function.
Now, I'm making the assumption that you are using the default Wordpress AJAX call -
jQuery.post(ajax_object.ajax_url, data, function(response) {
If that is indeed the case, for front end calls it is likely that ajax_object.ajax_url is not set. To set this, add the following to your functions.php file -
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>
Related
Okay so, I'm a bit stuck... Here's my problem. So, what I'm trying to achieve is I have a JS calendar and what I want it to do is when I click on a date, it fetches the times available for that day and displays it and then changes depending on what day you click on WITHOUT refreshing the page. Now, looking around, the only way I can seem to do this is with AJAX (suggestions welcome) although I have never touched AJAX before so have no idea what I'm doing here.
So I've currently got my .HTACCESS files setup on my webserver to use dynamic subdomains.
It's sort of like a multi-step form, and I'm collecting data in the SESSION as I go. Now what I'm guessing the way to do is here, to send a AJAX query with a JS variable with the date and then that runs an SQL query and gets the times and displays them. Here's what I have so far.
Update Session
<div class="output"><?PHP echo $_SESSION["outputTimes"]; ?></div>
<script>
$("#clickme").click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'data.php',
data: { date: '2020-07-04'},
success:function(response){
alert(response);
}
});
});
</script>
data.php
<?php
//Start Session
session_start();
//Include Database Config
include ("config.php");
//POST
$requestDate = $_POST["date"];
//Define SQL Query
$app_get_sql = "SELECT * FROM cc_av WHERE date=$requestDate";
//Run Query
if($result = mysqli_query($db_connect, $app_get_sql)){
while($row = mysqli_fetch_assoc($result)){
$_SESSION["outputTimes"] = '<li>'.$row["time"].'</li>';
}
}
?>
Currently, when I run this, I get the response in the alert() as the current code of the page I'm on. Hence why I noted about my HTACCESS although I can include() it just fine using the same root. Also, from the results of the data.php, how would I output the code sort of update what would be there at the moment.
Here's what I'm trying to create...
https://drive.google.com/file/d/1bgxSUxN6j2IOZcQBuAOo-PeCsuRgdmZ-/view?usp=sharing
Thanks in advance.
So, I've managed to work out what was going wrong. Because my HTACCESS file is creating SubDomains, it was also redirecting the Paths so in the AJAX code I used a URL to the code instead and then added a header to my PHP code on the file that needed to be requested.
header("Access-Control-Allow-Origin: (URL NEEDING TO BE REQUESTED)");
Final AJAX Code
var scriptString = 'THISISMYSTRING';
$('#clickMe').click(function(){
$.ajax({
method: 'get',
url: '(URL)/data.php',
data: {
'myString': scriptString,
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
I made a two PHP functions for my project, these two functions responsible for fetching different product category for different "online shop".
Now, I am implementing the function that when employee adding a new product, the employee first select which online shop does the new product belongs to (via a select), then depends on the online shop, the second select menu should display the correct options.
so, the first select looks like this
< Select name="Select_CCV_Webshop[]" id="ccv-webshop"
onchange='loadNew_CCV_Category()'>
here I need help on how to execute /call /trigger the php function inside of method "loadNew_CCV_Category".
Inside of function "loadNew_CCV_Category", it will get the select value, and this value will be the parameters for the php function.
Please help :D, Thank you !!!!
You can try this way,
<?php
function square($num)
{
echo $num * $num;
}
?>
<select name="Select_CCV_Webshop[]" id="ccv-webshop"
onchange='loadNew_CCV_Category()'>
<option>Select</option>
<option>Test Php</option>
</select>
<script>
function loadNew_CCV_Category(){
var phpData = "<?php square(4) ?>"
alert(phpData);
}
</script>
The short answer
You can not. PHP is executed server-side and only the PHP-generated page is then delivered to the browser, where JS takes over and can continue reacting to input, but only with information it already has.
The more helpful answer
You can, however, either deliver the information for both cases to the browser and decide which one should be shown, or, which in most cases will be what you would rather do, make another call to the server from within your JS.
That means you would have an additional PHP script, which executes the function and generates the page content you want to insert.
You would then access that script file using JS and insert the generated contents into your page.
As for how to do that, maybe
this answer might help.
EDIT: Also refer to Avi's answer on that.
You cannot execute php inside javascript. because php is server side program and javascript is browser related.
If you want to write php then you can try this.
alert("<?php echo 'hello' ?>")
or
$.ajax({
url: 'yourphpfilepath.php',
success: function(respon) {
$('.result').html(respon);
}
});
your code will be like this.
<Select name="Select_CCV_Webshop[]" id="ccv-webshop" onchange='loadNew_CCV_Category()'>
<div id=wheretoshowresult> </div>
<script>
function loadNew_CCV_Category(){
$.ajax({
url: 'yourphpfilepath.php', //url for your php function or file
success: function(respon) {
$('#wheretoshowresult').html(respon);
}
});
}
</script>
I am currently working on a project including the Facebook SDK. I already made it to Login/Logout myself using the javascript code.
I'm using an AJAX POST request to save the userID and the name from the response in a Session.
The problem here is, that I actually have to reload the page twice, the first time to get the POST parameters and save them into a $_SESSION.
The second refresh is needed to load the Session.
Is there a clean way to avoid that?
javascript: $.post( "login.php", { id:userID, name:response.name } );
login.php:
$_SESSION['name'] = $_POST['name'];
$_SESSION['userID'] = $_POST['id'];
I appreciate every kind of help. Thank you.
edit:
I would like to give the user who logged in with facebook additional oppurtunities on my website. The only way I know how to do this is with a Session in PHP. Whenever he logged in I created a Session who said that a person is logged in.
Now I have to do the same with a facebook login. It worked local with the PHP SDK already, but the webspace does not support that kind of SDK. That is why I have to dodge to the javascript one.
Is there another way to make sure a person is logged?
You are using AJAX,
So you can avoid reloading of Page,
<?php
session_start();
if (isset($_GET['name'])) {$_SESSION['name'] = $_GET['name'];}
if (isset($_GET['userID'])) {$_SESSION['userID'] = $_GET['userID'];}
if(isset ($_POST['name'] ) && isset ($_POST['userID'])){
$_SESSION['name']= $_POST['name'];
$_SESSION['userID']= $_POST['userID'];
}else{
$_SESSION['userID'] = 0;
}
?>
and javascript code is:
$.post( "/login.php", { id:userID, name:response.name } );
I'm building a web application in CodeIgniter and I'm using jQuery and AJAX. I created the whole app locally (using XAMPP) and everything worked fine. After I uploaded the app to my web hosting, one AJAX keeps failing. Here is the part of the code:
// Get all form inputs
var inputs = $('#app-options-existing-form :input[type="text"]');
// Put them in object as name=>value
var data = {};
for(i=0; i<inputs.length; i++) {
data[inputs[i]["name"]] = inputs[i]["value"];
}
// Put loader while AJAX is working
$(".app-content-container").html('<center><img class="loader" src="<?php echo base_url();?>/img/loader.gif" ></center>');
console.log(data);
// Generate POST request
$.post("<?php echo site_url("admin/ajax_app_options"); ?>",
{"add_existing_form_submited" : true, "data" : data2},
function (data) {
alert("test" + data);
});
Here's the console showing error and result of console.log(data)
First, I thought that the key ("d1d1d1") was the problem because I was first using "1-1-1" and after I manually changed it, it was working. But then I changed everything in "d1d1d1" and it doesn't work again. As I said, it works on XAMPP but not on server. Can be a problem in using full URL for AJAX, instead of relative one? But I'm using it in other AJAX requests as well and it works.
Pretty sure you problem is this guy '<center><img class="loader" src="<?php echo base_url();?>/img/loader.gif" ></center>'
Yours source is going to output literally to <?php echo base_url();?>/img/loader.gif which is of course not a real link. Therefore it is a resource that can not be loaded.
You might want to try instead using: '<center><img class="loader" src="/img/loader.gif" ></center>'
The base_url() function is just going to return '/' anyway.
Important! In general you can not write php in javascript. Or this would be a massive security hole that would give every user who visits your site unlimited access to your server.
I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>