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

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.

Related

Wordpress get post id with a php file

I have been stuck on this for weeks. I have an HTML slide presentation using Reveal.js. I want to run a php script on the very last slide.
This is an HTML button on the last slide within a Wordpress post:
<button onclick="myFunction()">Open php file</button>
<script>
function myFunction() {
window.open("../../testing/test.php", "_self");
}
</script>
This is the code inside the test.php file that I am trying to run but it returns null:
define('WP_USE_THEMES', false);
require_once('../wp-load.php');
echo "Post ID: ".get_the_ID(); // Returns nulls but I want this to return 86.
The post id is 86. I can hard code it into the html (if I have to) but I don't want to hard code it into the php file. Also, I would prefer not to use jquery. How can I get the post id into the php file? Thanks.
Have you tried using global $post variable??
global $post;
And after that, you can get the id,
echo "Post ID: ".$post->
Another approach is using $wpdb global variable to make database queries.
You can also use JavaScript to send your post id to another php file using javaScript forms, Ajax or jQuery. jQuery Post.
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Button On click call jquery function and acess php

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

Capture onClick event in serverside php file using Ajax

I am very new to Ajax. My application uses ajax (and a server side php page called Req.php) to fetch records from a database, create table using those fetched records and display it. Now I want a column to be added having Delete option to it. May be something like this:
echo '<td>Delete</td>';
This deleteIt() method lies inside Req.php (server side) file like this:
<script type = "text/javascript">
function deleteIt(rowID)
{
//Some Code
}
</script>
Now considering the fact that it is a server side file, and delete event happens at client side, what should be the procedure to capture this delete event so that it takes $rowID from the table made by server side php file and deletes the correponding record.
Any help would be highly appreciated. And please let me know if there's insufficient information so that I can give more details.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
jQuery.ajax({
url:'YOUR PHP url which contains DELETE code',
type:'POST',
data:'SEND YOUR DATA',
success:function(results){
jQuery("#oresponsecontainer").html(results);
}
});
In your PHP
$id = $_POST["id"];
An Ajax request would be then be sent from your javascript with the id and action (deleting) of the column your accepping php file would then search for the row and delete it.
please specify what has been done in php for deleting.
You should create another php script that handles POST request (or GET, i've used post ajax)
so function should execute something like this
$.post("/trackDeletion.php",{rowID:rowID},function(successResponse){
//client handler
})
and PHP will be
rowID = $POST['rowID']
//do you code on backend

Passing data from PHP to JS and JS to PHP

Hi I'm trying to learn PHP and javascript, therefore I tried to do an exercise about passing data but I didn't understand the js function and currently unable to do anything.
Here is the code
php-code.php
$v1=$_GET['v1'];
$v2=$_GET['v2'];
$v3=$_GET['v3'];
//Some operations about them
echo $output;
my-js.js
var v1 = $('#v1 option:selected').val();
var v2 = $('#v2 option:selected').val();
var v3 = $('#v3 option:selected').val();
//This is where I want to pass these variables to my php file and get the output
//But i don't know how
js-execute.php
//this is where my js gets the variables at first
PHP is a server-side language while JavaScript is a client-side one. This means that PHP will be executed when someone requests a page, but the browser will only get the result of the PHP code. On the other hand, JavaScript is sent to the browser and the browser will execute it at the appropriate time (when the page loads or when an event happens). That's why if you look at the source code of a page, you will be able to see the JavaScript code, but never the PHP code.
If you want to pass values from JavaScript to PHP, you will need to make a remote call to a PHP file. PHP isn't like JavaScript – once it's done running its code, it won't be able to respond to anything without a reload of the page.
The easiest way to send something to a PHP file and fetching the result with JavaScript can probably be achieved with JQuery. It has a function $.get which will fetch a given URL. Just be sure to properly validate the input on the server side – never trust user input.
JavaScript (using JQuery to send v1, v2 and v3 to page.php)
function requestPage(v1, v2, v3) {
$.get('page.php', {'v1':v1, 'v2':v2, 'v3':v3}, function(data) {
alert(data);
});
}
PHP (a trivial example)
// Be sure to properly validate input!
if(isset($_GET['v1']) && is_scalar($_GET['v1'])) {
echo strrev($_GET['v1']);
}

How to assig a PHP variable a value inside a JavaScript block?

if ($page_title->exists()) {
//the rest of the code is in php.here i insert a javascript for the confirm box.
echo'<script type= "text/javascript" >
var b=confirm("This page already exists.would you want to edit");
if(b == true)
//here i want to assign a php variable , say for eg. $a to 1 so that i can use that value of $a in an if clause outside this javascript code.
</script>';
}
if($a==1)
..some code..
How do I do it?
The PHP code is executed on the server side and is all done at the point where your javascript is executed on the client side.
To communicate the value from the client to the server you typically either use AJAX (tutorial on how to do it here: http://www.w3schools.com/ajax/ajax_httprequest.asp) or store the value in a form and submit it together with data you are going to send down later anyway.
Good luck
Javascript runs on the client (browser) and PHP on your server. So you have to transport the variable to the server.
Most easy way to do this is to use the URL to send this information, for example: http://example.com/myscript.php?a=1. Then you can grab a using $_REQUEST['a'] and use it.
A more sophisticated (and complex) method is to use AJAX to send the variable to your PHP script, so it can return some data which you can use to modify your page.
What you need depends on your application, so you should provide some more details if you do not know what method is best to you in your situation.
you can send the result back to php using an ajax call, e.g.:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript">
x = confirm('Page exists, would you like to edit it?)
$.post('script.php', {x: x}, function(data) {
if (data == '1') {
alert('ok');
} else {
alert('not ok');
}
});
</script>

Categories

Resources