Button On click call jquery function and acess php - javascript

I am very new to Wordpress and Woocommerce. I have few doubts wrt jquery in Wordpress. Say i have a function
function test(){
alert("test");
<?php
error_log("Test ---------------------------- ", 0);
?>
}
and a button:
<input type="button" id="btnclick" onclick="test();" value="Test" />`
error log is printing on page load but not on click. But i want to execute code inside php block only when user clicks on button.Is there a way to achieve this ? Thanks in advance`

jPO has already explained how to solve this in a good way, but I thought I should explain why this happens.
PHP is executed on the server. Once the page has been sent to the client, the PHP is no more. JavaScript happends on the client, and can be executed as long as the user is viewing the webpage. Since they do not live during the same timeperiod they are not aware of each other and can not be mixed in that way.
When you visit the page in your browser, the browser sends a request to the server. On the server the PHP interpreter goes through the code of the requested page, executing everything between <? and ?>. It does not understand what the other stuff around it is - it could be HTML, JS, plain text, anything, the PHP interpreter does not know and does not care. That is why it writes to the error log on page load.
When the PHP interpreter is done it has produced a document looking like this:
function test(){
alert("test");
}
That is sent to the client, and the JS (without any instruction to write to the error log) is run on the client when the button is pushed.

Not possible like that. If you'd like to do so. You need something like ajax method in php which you can call. Let's say you have a file in the root of your project called ajax.php, there you can define a function named test(), then you have to have a $_REQUEST translator, which calls your function test(), so the ajax.php would look like this
<?php
// checks if you sent a parameter named method and calls the method
// if you provide parameter named params it will send them too
if(isset($_REQUEST)){
if(isset($_REQUEST["params"]))
ajax($_REQUEST["method"],$_REQUEST["params"]);
else
ajax($_REQUEST["method"]);
}
function ajax($function,$data = null){
$function($data);
}
function test(){
error_log("Test ---------------------------- ",0);
}
and your ajax would look like this
function test(){
$.ajax({
url:"ajax.php",
data:{
method:"test"
}
});
}
hope it helps

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

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

I'm having trouble getting JavaScript variables passed to a php script

I'm trying to set up a webpage with Jquery that will receive button clicks from the user, pass those click values to a PHP script, that will then publish them to a MQTT broker. My connection to the broker seems to be working. I'm having problems passing variables from JavaScript to PHP. What am I doing wrong?
Here's my JavaScript:
<script>
$(document).ready(function(){
$("#button01").click(function(){$.post("post.php", {testvalue:test01});});
});
</script>
and here is my PHP:
<?php
require("../phpMQTT.php");
$testvalue = $_POST['testvalue'];
$mqtt = new phpMQTT("192.168.1.20", 8000, "client");
if ($mqtt->connect()) {
$mqtt->publish("hello/world","$testvalue",0);
$mqtt->close();
}
?>
You pass invalid JSON object to $.post() method. It should be:
{testvalue:"test01"}
So your JavaScript code should look like:
$(document).ready(function(){
$("#button01").click(function(){$.post("post.php", {testvalue:"test01"});});
});
Or if test01 is variable, it should be defined first.
Please, next time look at console in your browser and check if there is no errors and if the ajax call is sending correctly.

JavaScript in php file doesn't work when php file is called using Ajax [duplicate]

This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 8 years ago.
Using Ajax, I'm calling a php file that contains javascript, but in this way, the javaScript doesn't work.
The main.html file is given here. It just uses Ajax for calling a php file called test1.php for updating all page at client.
<!DOCTYPE html>
<html>
<body>
<!-- run php file to fill the page -->
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","test1.php",true);
xmlhttp.send();
</script>
</body>
</html>
And the test1.php file is very simple test as follows:
<p id="demo">Hi there</p>
<script>
document.write("Yes! Hi there");
alert('Welcome!');
</script>
Now, just for checking that test1.php is ok, I put in the browser's url line:
localhost/test1.php
and everything works ok, the text of the html and js are displayed and an alert window with the word Welcome! is displayed.
But if I call the main page
localhost/main.html
Then only the html text 'Hi there' is displayed. The JS is ignored.
Anybody knows why is this?
Thanks
Krasimir Tsonev has a great solution that overcome all problems. His method doesn't need using eval, so no performance nor security problems exist. It allows you to set innerHTML string contains html with js and translate it immediately to an DOM element while also executes the js parts exist along the code. short ,simple, and works exactly as you want.
So in this case, the response from ajax is the src string which then translated to a DOM object according to Krasimir Tsonev and then you have it works with js parts that are executed.
var el = str2DomElement(xmlhttp.responseText);
document.body.innerHTML = el.innerHTML;
Enjoy his solution:
http://krasimirtsonev.com/blog/article/Convert-HTML-string-to-DOM-element
Important notes:
You need to wrap the target element with div tag
You need to wrap the src string with div tag.
If you write the src string directly and it includes js parts, please take attention to write the closing script tags correctly (with \ before /) as this is a string.
Here are 3 basic examples of what you can do with ajax & how you should do it:
Main html
js
function ajax(a,b,c){ // Url, Callback, just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function changeHTML(){
document.getElementById('mytext1').innerHTML=this.response;
}
function executeJS(){
(new Function(this.response))()
}
var array=[];
function loadJSON(){
array=JSON.parse(this.response);
updateFields();
}
function updateFields(){
for(var a=0,b;b=array[a];++a){
document.getElementById(b.id).textContent=b.data;
}
}
window.onload=function(){
ajax('getHTML.php',changeHTML);
ajax('getJS.php',executeJS);
ajax('getJSON.php',loadJSON);
// even if this works you should execute ajax sequentially
}
html
<div id="mytext1"></div>
<div id="mytext2"></div>
getHTML.php
<?php
echo "<div>i'm html</div>";
?>
getJS.php
<?php
echo "var a='hello';alert(a);";
?>
getJSON.php
<?php
$arr=array(array('id'=>'mytext2','data'=>'data'));
echo json_encode($arr);//json_decode
?>
if you want to execute a javascript function use the executeJS function and pass a valid javascript string.
There is no need for EVAL!
TIP:using json you can pass a function as data but as the parsing does not like the string function at the beginning a nice trick is to convert the javascript to base64 and back into a normal string with javascript with atob(base64) and have something like this:
function updateFields(){
for(var a=0,b;b=array[a];++a){
if(b.func){
(new Function(atob(b.func)))()
}else{
document.getElementById(b.id).textContent=b.data;
}
}
}
php
<?php
$arr=array(
array('id'=>'mytext2','data'=>'data'),
array('func'=>base64_encode("alert('jsonfunc')"))
);
echo json_encode($arr);//json_decode
?>
maybe there are some little errors ... i wrote that now. and can't check ajax atm.
if you have any questions just ask !!
I want to give you one advice that insted use of javascript you can use jquery ajax it will be easy and latest thing for ajax.
You can use $.ajax function. You can use json easily with this function
When you make an AJAX call you contact to a server url. If your url is, as in this case, a php page, it will execute on the server and return to your AJAX call the HTML that it produces... now you can play with that HTML and manage it or publish into your current's page DOM.
-AJAX is a server call that executes server code.
-A script tag embeded on a php page is HTML that will execute the code it contains on client when parsed and executed by a browser.
So... your code isn't executing because it's never being called... the response to your AJAX call will be exactly
<p id="demo">Hi there</p>
<script>
document.write("Yes! Hi there");
alert('Welcome!');
</script>
The php page executes and return that to your current page as text/html.
If you want to execute client code from your javascript you should have it on the same .js file or in another one included, but if you include it on a server page you'll need to redirect your browser to that page, if you call it with AJAX the code won't execute as the client browser won't parse it.

JS/jQuery passing array/variable/data to PHP in same page?

Im hoping you can point me in the right direction.
I have a php page, that includes some HTML markup and some JS/jQuery routines to build an array of 'user choices' based on the 'user input' (checkboxes..etc).
my question is, how can I pass off this (multidimensional) array to PHP, that is in the same page? (ultimately I want to save this data/array to my PHP session)
While looking around, I read about using another (external) .php script to do,, which is NOT what Im after, I'm hoping to do this to the SAME PAGE I'm in... WITHOUT A REFRESH.
will $.post() do this for me? without a page refresh (if we suppress the event or whatever)...
and -not- using an external .php script?
I understand PHP runs/executes FIRST... then everything else..
I'm not really trying to get PHP to do anything with the data being sent from JS/AJAX.. outside of save it to the SESSION array..
Ajax seems like it will be needed?
To summarize:
1.) PHP and JS are in/on same page (file)
2.) No page refresh
3.) No external PHP script to do 'anything'.
4.) Trying to get (multidimensional) array to PHP session in same page.
5.) I am trying to 'update' the PHP SESSION array each time a user 'clicks' on a checkbox.
I have read a little on using AJAX to post to the same page with the URL var left empty/blank?
edit:
to show the data, I want to pass...heres a snippet of the code.
its an array of objects.. where 1 of the poperties of each object is another array
example:
var somePicks = [];
somePicks.push({casename:caseName, fullname:fullName, trialdate:trialDate, citystate:cityState, plaintiff:plaintiff, itemsordered:itemsOrdered=[{name:itemOrdered, price:itemPrice}]});
when from all the checkboxes.. I update the 'sub-array' (push or splice..etc)
somePicks[i].itemsordered.push({name:itemOrdered, price:itemPrice});
'this' is the array/data I want to get into my PHP session from JS using whatever I can AJAX most likely.
You can sort of do that, but in essence it won't be any different than using an external PHP file. The PHP code gets executed on the server before ever being sent to the browser. You won't be able to update the PHP SESSION array without reconnecting with the server.
If you really want to use post to call the current page (I don't think you can just leave the url blank, but you can provide the current file name), you can just have the PHP handler code at the top of the page. However, this would be the exact same as just putting that handler code in an external file and calling it.
Either way, the page will not refresh and will look exactly the same to the user.
You can use $.ajax function with $(#formid).serializearray (). And use url as ur form action in $.ajax function.
I hope it will work for you
<form id="formId" action="post.php" methor="post">
<input type="checkbox" name="test1" value="testvalue1">TestValue1
<input type="checkbox" name="test2" value="testvalue2">TestValue2
<input type="button" id="buttonSubmit" value="click here" />
</form>
<script>
$("document").ready(function ()
{
$("#buttonSubmit").click(function () }
{
var serializedata=$("#formId").serializeArray();
$.ajax(
{
type:"post",
url:$("#formId").attr("action"),
data:{"data":serializedata},
success:function()
{
alert("yes");
}
});
});
});
</script>
<?php
if(isset($_POST))
{
session_start();
$_SESSION["data"]=$_POST["data"];
}
?>
I suggest to use the .post method of Jquery, to call a PHP file, sending the array and processing in the PHP called.
Can find the jquery documentation about .post() here: http://api.jquery.com/jquery.post/
Edited:
I used this case some time ago:
document.getElementById("promotion_heart_big").onclick = function(e){
$.post("' . URL_SITE . 'admin/querys/front.make_love.php",
{
id_element: ' . $business["promotion"]["id"] . ',
type: \'promotion\',
value: $("#field_heart").val()
},
function(data) {
if (data.result) {
//some long code....
}
}
},
"json"
);
from some preliminary testing..
this does NOT seem to be working, (will do more test tomorrow)
$.ajax({
type : 'POST',
//url : 'sessionSetter.php',
data: {
userPicks : userPicks,
},
success : function(data){
//console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
});
It was mentioned that posting to external .php script -or- posting the same page would produce the same results..
no page refresh
$_SESSION would update for future pages
Does anyone have an y example for that?

Categories

Resources