WordPress Button triggered ajax request - javascript

So I have actually read stackoverflow questions about this, but they are somewhat quite old to work with newest version of wordpress.
My end goal is to submit to database some data from my forms but for now ajax response is not working for me. On custom page load in WP all code is loaded so all functions should work. All of this is inside of PHP file for now that why echo is used to create JS scripts. Here's the important part of my code
echo '<button id="ZapisPrace">Save</button>
<script>
jQuery("#ZapisPrace").click(function($){
var data={
action: "addToDB",
info: "nomz"
};
jQuery.post(ajaxurl,data,function(response){
alert("Response was "+ response);
});
});
</script>';
add_action('wp_ajax_addToDB','pridajDoDB');
function pridajDoDB(){
echo '<script>console.log("AAA")</script>';
wp_die();
}
Using current version of WP so variable ajaxurl is pointing to the
/wordpress/wp-admin/admin-ajax.php
No console.log is happening, response is always 0, even when I remove pridajDoDB function or add_action. It's just not triggering the ajax request correctly. Can somebody let me know why?
Also I have not used yet functions like wp_localize_script, wp_register_script or wp_enqueue_script because all of this is in one PHP file that's loaded, and I don't need to import jquery as far as I know its default available in WP. I am just learning how to use WP, PHP AJAX and jQuery, so I have still quite a lot to learn.
PS: I am supposed to use the WP way of using ajax.

Change php code as follows.
add_action('wp_ajax_addToDB','addToDB');
function addToDB(){
echo "AAA";
wp_die();
}

Ok so I didn't figure out how code above works, however I managed to get it working trough different wp structure I found online:
BTW: I used onClick function here but it works even when replaced with jQuery click event.
add_action('wp_ajax_addToDB','pridajDoDB');
echo '<button onClick='triggerAjax()'>Save</button>?>';
<script>
function triggerAjax(){
<?php $nonce = wp_create_nonce( 'subbmitData' );?>//used so ajax response can verify from where is the request coming
jQuery.ajax({
type: "post",url: "admin-ajax.php",data: { action: 'addToDB', _ajax_nonce: '<?php echo $nonce; ?>' },
success: function(html){
console.log(html);//this will console log everything that happens in ajax called php function. Echo works as well.
}
});
}
</script>
<?php
function pridajDoDB(){
check_ajax_referer( "subbmitData" );//this check from where is the request coming from
//here database commands works but if you echo or console log something it will be just passed to success function above
die();
}
?>

Related

Really bizarre bug when using jquery ajax and php

I'm trying to create a like button for different images posted by user. This is my html :
Like
This is my javascript:
<script>
$(function(){
$(".likes").click(function(){
var postid = $(this).attr("id");
alert(postid);
$.ajax({
type:'POST',
url:'likes.php',
data:'id='+postid,
success:function(data){
alert("success");
}
});
});
});
</script>
This is likes.php, for testing purpose it's quite simple:
<?php
require('config.php');
$postid=$_POST['id'];
echo $postid;
?>
When I clicked the like button, a small window will correctly postid, and then "success",which indicates that the ajax is successful, however, when I opened likes.php, I got an error that says: Notice: Undefined index: id in C:\XAMPP\htdocs\likes.php on line 3
I tried adding e.preventDefault(). I tried different syntax,such as data:'id='+postid, data:{id:postid},data:{'id':postid},etc. I experimented with basically all combinations of single quotes and double quotes. I also tried adding datatype:html and datatype:text. Every time I just got a alert that says "success", but when I open likes.php, $_POST['id'] is always undefined.
Can someone help me please this bug took me a lot of time.
Update: I found that even if I entered a completely non-existing url, like url:"aabbll.php", after I clicked the "like" button, I would still see a window that alerts "success", why does the page keep alerting "success" even though clearly the AJAX process wasn't a success?
You are not sending the post variable "id" when you are opening like.php in a new browser window.
The error "Notice: Undefined index" is shown because the $_POST array does not contain the id field.
You can use a chrome extension called postman to test endpoints with post variables.
A tip to improve the code could be to wrap it in an if isset statement
if(isset($_POST['id'])){
// this code will only be executed if the post variable is sent to the page
$postid=$_POST['id'];
// update database
echo "Success";
}else{
echo "ERROR: No id post variable found";
}
Your javascript code is sending the post variable
Try to put var_dump($_POST) to see what you really post.
Couple of suggestions.
Your JS can be simply
<script>
$(function() {
$('.likes').on('click', function() {
var postid = $(this).attr('id');
$.post("likes.php", {id: postid}).done(function( data ) {
alert( 'Data Loaded: ' + data );
});
});
});
For your PHP
<?php
if (!isset($_POST['id'])) {
/// Do what you want to do in this case.
}
$id = $_POST['id'];
// If using PHP7
$id = $_POST['id'] ?? null;
Though $('.likes') works try to avoid that since it is slowest selector in most cases.

Why does my jquery ajax post succeed but the $_POST array is still empty?

This is my first question on here, please bear with me:
My ajax request is:
<script>
$.ajax({
type:"POST",
url:"http://localhost/folder/something.php",
data: { BuildingName:'Jacaranda'},
success: function(data){alert("It worked")},
error: function(data){alert("It failed")},
});
</script>
In my something.php file I have:
$Building= $_POST['BuildingName']; //Error Occurs Here
I get an error on this line stating:
Notice: Undefined index: BuildingName.
When I do VAR_DUMP it returns the $_POST array as empty.
I have checked and rechecked. Looked at different answers here and cannot seem to find the problem. I hope it is not staring me in the face.
I appreciate any help, thank you.
SOLUTION: Instead of simply trying to pass data between pages solely which I do not think is possible(correct me if I'm wrong), there has to be an intermediary. I passed my data into MySQL and had my webpage "listen" to the DB and do something based on the most recent entry.
SOLUTION USING SESSIONS per the advice of Lukas1 (you're right this is more efficient.)
<?php
$_SESSION['Building']= 'something';
$Building= $_SESSION['Building'];
echo "<script> $('#Jacaranda').click(function(){
var id = $(this).attr('id');
$Building= id;
}) </script>";
?>
And my call on the next page is:
<?php echo $Building ?>
Works perfectly without using database as intermediary.
Just change your data attribute to
"BuildingName=Jacaranda"
and it should work all fine.

Call a javascript function from php [duplicate]

How to call a JavaScript function from PHP?
<?php
jsfunction();
// or
echo(jsfunction());
// or
// Anything else?
The following code is from xyz.html (on a button click) it calls a wait() in an external xyz.js. This wait() calls wait.php.
function wait()
{
xmlhttp=GetXmlHttpObject();
var url="wait.php"; \
xmlhttp.onreadystatechange=statechanged;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function statechanged()
{
if(xmlhttp.readyState==4) {
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
and wait.php
<?php echo "<script> loadxml(); </script>";
where loadxml() calls code from another PHP file the same way.
The loadxml() is working fine otherwise, but it is not being called the way I want it.
As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.
All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.
Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.
So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".
There are many ways to do this, but here are a couple.
Using just PHP:
echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;
Escaping from php mode to direct output mode:
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.
Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.
Here's an example of what I think you're doing with jQuery's AJAX
$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;
// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();
// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);
function someOtherFunctionYouWantToCall() {
// stuff
}
Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.
$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);
* Or JSON or XML etc.
I always just use echo "<script> function(); </script>"; or something similar. You're not technically calling the function in PHP, but this is as close as you're going to get.
Per now (February 2012) there's a new feature for this. Check here
Code sample (taken from the web):
<?php
$v8 = new V8Js();
/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;
try {
var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
var_dump($e);
}
?>
You can't. You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.
If you want to echo it out for later execution it's ok
If you want to execute the JS and use the results in PHP use V8JS
V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');
You can refer here for further reference:
What are Extensions in php v8js?
If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution
Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).
<td onClick= loadxml()><i>Click for Details</i></td>
function loadxml()
{
result = loadScriptWithAjax("/script.php?event=button_clicked");
alert(result);
}
// script.php
<?php
if($_GET['event'] == 'button_clicked')
echo "\"You clicked a button\"";
?>
I don't accept the naysayers' answers.
If you find some special package that makes it work, then you can do it yourself! So, I don't buy those answers.
onClick is a kludge that involves the end-user, hence not acceptable.
#umesh came close, but it was not a standalone program. Here is such (adapted from his Answer):
<script type="text/javascript">
function JSFunction() {
alert('In test Function'); // This demonstrates that the function was called
}
</script>
<?php
// Call a JS function "from" php
if (true) { // This if() is to point out that you might
// want to call JSFunction conditionally
// An echo like this is how you implant the 'call' in a way
// that it will be invoked in the client.
echo '<script type="text/javascript">
JSFunction();
</script>';
}
Ordering It is important that the function be declared "before" it is used. (I do not know whether "before" means 'lexically before' or 'temporally before'; in the example code above, it is both.)
try like this
<?php
if(your condition){
echo "<script> window.onload = function() {
yourJavascriptFunction(param1, param2);
}; </script>";
?>
you can try this one also:-
public function PHPFunction()
{
echo '<script type="text/javascript">
test();
</script>';
}
<script type="text/javascript">
public function test()
{
alert('In test Function');
}
</script>
PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.
You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:
<button onclick="xajax_addCity();">Add New City</button>
Our intuitive guess would be that xajax_addCity() is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity(), but what we do have is a PHP function called addCity() that can do whatever PHP does!
<?php function addCity() { echo "Wow!"; } ?>
Think about it for a minute. We are virtually invoking a PHP function from Javascript code!
That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!
For some backend node processing, you can run JS script via shell and return the result to PHP via console.log
function executeNode($script)
{
return shell_exec('node -e \'eval(Buffer.from("'.base64_encode($script).'", "base64").toString())\'');
}
$jsCode = 'var a=1; var b=2; console.log(a+b);';
echo executeNode($jsCode);

WordPress Plugin => How to use JS AJAX to trigger plugin PHP functions

Building my first plugin, I'm having difficulty communicating between scripts. How to use JS AJAX to call the plug-in PHP script handling my functions.
I'm finding that loading the plug-in script NOT in WordPress is (obviously) causing rendering/permission issues.
Here's a boiled down version - the plugin is instantiated via a shortcode:
[short-code]
This kicks off the WP plug-in, carrying out some preliminary tasks.
After the DOM is loaded, I use HTML5 to find the user's geolocation.
Goal: Pass HTML5 geolocation data via AJAX to a php function located in the php file. Eg: Call to undefined function register_activation_hook()
var sf_path = jQuery('#sf_path').val();
var url = '/wp-content/plugin/plugin_name/plugin_name.php?h=true&=lat='+position.coords.latitude+'&lng='+position.coords.longitude;
var jqxhr = jQuery.get( url , function(data) {
console.log( "geolocate", data );
//Response = PHP Error: Call to undefined function register_activation_hook()
});
I think I can rewrite the code to differentiate platforms and run differently based on the request (basically, unwordpressify certain functions) but it would be much handier to NOT have to do that. wp_remote_get is very handy as is.
What am I missing?
The WP ajax calls are handled through the admin-ajax.php script. First, what you need to do is to register actions -
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
Next, you need to define what this my_action_callback would be doing.
function my_action_callback() {
// Handle Geo Location Data
wp_die(); // this is required to terminate immediately and return a proper response
}
Once done, you can send the AJAX call
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'geo': 1234
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
If ajaxurl is undefined, you can define it this way -
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
You can find more about that on the documentation
Ultimately, I was able to solve this with the help of #ToshoTrajanov's help by pointing out how to get the ajaxurl variable into page. It was my stumbling block. For me, though, I kick my mark-up off in PHP and added the following to my php init function:
<?php
print "<script class='gcCleanup'>";
print 'var ajaxurl = "' . admin_url('admin-ajax.php') . '";';
print "</script>";
?>

Using Ajax to require different php page

I want to use jquery ajax to change the content of my div elemnt by requiring different php files.
here is the ajax code :
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num
},
success:function(result){
$("#right_bot").html(result);
}
});
the project_functions.php would be something like :
$result = '<?php require "Panels/Project/Main/main.php" ?>';
echo $result;
I can see the value being outputted , but the html comment out the php part
<!--?php require "Panels/Project/Main/main.php" ?-->
It just comments out the php. Is there a way i load different php files into my div ?
In the main.php file , It has php code , html code , and some style tags. Can I use ajax to load all this into the div element ? or I have to echo all my html code ?
You can't do this like that. What you want is that all PHP is excecuted on the server and only the result has to be returned.
You can't send php-code back to javascript and try to run it there, PHP is a serverside language, it will only work on the server. Javascript is clientside, it will only run in the browser.
If you where to send <?php echo 123; ?> back to Javascript, you'll get exactly that as result, not 123.
The solution in your case is to make project_functions.php really require it. This will include the main.php, all it's functions and output.
require "Panels/Project/Main/main.php";
Some suggested reading:
http://www.codeconquest.com/website/client-side-vs-server-side/
A trick which might help you: Paste the link to your urlbar, and add the variables to it. The result you get in your screen is what Javascript will output. Note: This only works for method=get, not post.
In this case browse to /project/Functions/project_functions.php and do the simple require per my code above. That output will be send to Javascript.
Send a parameter in the ajax request 8for example type):
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num, type: "main"
},
success:function(result){
$("#right_bot").html(result);
}
});
And then in php-file get the type variable:
if($type == "main") {
require "Panels/Project/Main/main.php"
}
else {
require "Panels/Project/Main/sthelse.php"
}
You should also have some sort of same function name or something to output the results of the file;
<?php
function printResult() { }
echo printResult();
Try:
$result = file_get_contents('Panels/Project/Main/main.php');

Categories

Resources