I have a mini-project to finish and I am facing a problem. I created a button to delete data from database and it works. But I want to add a prompt which asks for a password. I read that JavaScript is required.
So I used this code:
echo
"
<script>
var password=prompt('Please enter the password');
$.ajax(
{
type: 'POST',
url: '/test.php',
data: password,
success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
</script>
";
if($_POST['data'] == "admin")
{
The rest of the code doesn't matter. But it throws me this error:
Uncaught ReferenceError: $ is not defined
Any solutions? I am new in PHP and I've never used JavaScript before :)
You will need to add a reference to jQuery before you use the $ operator.
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
You need to include jquery in your code. Just add this before your scripts.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
You're trying to use the jQuery library, but haven't included the jQuery script necessary to run it. However, I would not recommend including an entire library to perform a single task.
Presumebly, your browser supports the Fetch API, which does the same as jQuery' $.ajax function, but natively. I would suggest that you learn how to use JavaScript without any libraries.
The example below shows how you should do this with the Fetch API. It sends a POST request with the password in an object. That object is transformed to JSON before being sent. JSON is a intermediate language that both JavaScript and PHP can understand, so it's a perfect way of communicating between two languages.
The request expects a response that is text based. Whenever a response is received it will print the received string to the console.
var password = prompt('Please enter the password');
fetch('/test.php', {
method: 'POST',
body: JSON.stringify({ // Send the object as JSON
password: password
})
})
.then(response => response.text()) // Decode the response as text.
.then(text => {
console.log(text); // Log the received text.
});
On the PHP side, try to keep this logic in a seperate file. Your Fetch request will call the PHP file and the PHP file should send back a response.
The example below checks if the password key in the $_POST array exists. Because we converted our JavaScript object into JSON earlier, PHP is able to convert it into an assosiative array. So JS is effectively turned into PHP at this point.
Then check if the $password equals the admin string and return a string. This returned string will be sent back to client and processed as the response.
$password = $_POST['password'] ?? ''; // If the password key does not exist, use an empty string.
if ($password === 'admin') {
return 'Password is admin';
} else {
return 'Password is NOT admin';
}
die(); // Stop this file from running any further.
Related
I have this php file graph.php
$host = $_POST['hostname'];
echo $type=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type.'.inc.php');
and I trying to send data to this file using this ajax code
var type_char='fortigate_cpu';//$('#graph').val();
var hostname='10.10.0.144';//$(this).attr('id');
//$('#device_host').val(id);
$.ajax({
type: 'POST',
url: 'SNMP/graph.php',
data: { hostname:hostname,type_char:type_char },
success: function(data) {
alert(data);
// show the response
$("#grph").attr("src", 'SNMP/graph.php');
console.log(data);
}
});
the result when I send data to that file is
fortigate_cpu as a value of type_char variable
when I opened error.log file in apache logs
I have this message
include(): Failed opening 'graphs/.inc.php' for inclusion (include_path='.:/usr/share/php')
as you see the value of fortigate not included in include function even if the char_type variable is send by ajax and printed in page
include file must be as this
include( 'graphs/fortigate_cpu.inc.php')
why type not included in the include session even if the variable is received from ajax
As was mentioned by other users in the comments, maybe your issue is that you are setting type to a different value after including rrdtools.inc.php .
Try randomizing ( changing the name), of the type variable:
$host = $_POST['hostname'];
echo $type123456=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type123456.'.inc.php');
It's the only thing I can think of, since both I (and others) have tested your code.
(both front-end and back-end).
PS: Include using post param is a bad practice.
Does anyone know how pass form values into PHP and still return the data to JavaScript? (For use in Google Charts if anyone is wondering.)
I have an HTML form with 4 radio boxes. I'd like to pass the value of the form so that my PHP request will be modified based on the user's selection.
The results from the PHP request need to be passed to JavaScript for processing.
In the radio button on click event place a javascript function that will perform an XMLHttpRequest to the php page and have the PHP page echo some JSON content that can be decoded in the return of the XHR in Javascript.
Example of such
May this can help you.
I think that you must do an Ajax request
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( data) {
alert( "Data Saved: " + data);
});
You send data to server form your form (here sent are name and location). You read this data with javascript with OnSelect and transfert it to your PHP code and,
You get back data from server into your JavaScript code and you can do what you want with it.
Sorry if my solution use JQuery, it is better for cross-browser with less code writing !
You could use this line to parse an array into json and use it later in javascript:
json_encode($rows); //format array named $rows into json data
More info: http://php.net/manual/en/function.json-encode.php
I use this simple javascript code to call a php function from javascript.
var a = new XMLHttpRequest();
a.open("GET","save.php");
a.onreadystatechange = function() {
if( a.readyState == 4) {
if( a.status == 200) {
alert("Worked");
}
else alert("HTTP error "+a.status+" "+a.statusText);
}
}
a.send();
In this example I have a php function save() contained into save.php file.
I have some questions:
1) How can I call a php function that it is located into the same file where there is the javascript function? (I would to call a php method declared into the same file where there is the javascript caller)
2) Is possible to pass also an php array as parameter?
First: You are not "calling a function". You are making a request to a server. The request is "interpreted" in php, and php has a function defined that is called. Js never calls php directly (one is front side, one is back).
To answer your questions:
You need to make the request to the same page you are displaying, but your js will also be executed.
Yes, but I suggest a post not a get for this (use var_name[] for array, where var_name is the name of the array).
As side notes:
Having both php and js in the same file is usually a bad idea. Try to isolate the front-end from the back-end as much as possible (it may be hard at first, but it will save you from huuuge headaches).
The script you are using is fine for simple things, but lacks lots of things (what if destination was moved and you get a redirect state, what if is unreachable, what if you need a callback, etc.). You are also limited at GET, and for some thing you may prefer POST method. I suggest using js lib for your requests (like jQuery ajax, prototype ajax, etc.) that take care of this things. Or you can extend your script of course.
You have to use ajax call as described manner--
On javascript side on save.php page-
$.ajax({
type:"POST",
data:'demodata',
url:"save.php?action=php_function", // place your php function name here
dataType: "html",
success:function(response){
alert(response); // It will alert value returned by php function
},
failure:function(response){
alert("there is an error.");
},
});
On PHP side on save.php page-
<?php
if(function_exists($_GET['action']))
{
$_GET['action']();
}
else
{
echo 'There is some error.';
}
function php_function()
{
// some code
echo "result";
}
?>
In general, passing an array between PHP and Javascript is better done using a JSON document as interchange format.
You would have to detect the request was made via ajax so that you can run the save() function, or if not then output the page normally, with the JavaScript caller included.
There are a number of ways to detect ajax, one would be to set the X-Requested-With header, which you can check on the PHP side.
save.php
function save(){
// some PHP code here
}
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
// request was made via ajax, call the function
save();
exit(); // exit so no page content is sent via ajax
}
// output the page content including JavaScript caller
JavaScript:
var a = new XMLHttpRequest();
a.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // set the header
// continue with your XHR code
The best way to send an array would be to JSON encode it before sending via POST, then JSON decode on the PHP side.
JavaScript:
a.open("POST","save.php");
a.send('json=' + encodeURIComponent(JSON.encode(myArray)));
PHP
function save(){
$myArray = json_decode($_POST['json']);
}
Having a spot of problem with a very simple example using PHP and jQuery.
PHP File
<?php
// This is where we return all of our initial widget markup
header('Content-Type: application/json');
$markup = array('markup' => 'No markup here');
echo json_encode($markup);
JS Function
jQuery(document).ready(function($) {
var widgetURL = "http://samedomain.com/vip/php/markup.php?callback=?";
$.getJSON(widgetURL, {
format: "json"
}).done(function( data ) {
console.log('Success!')
}).fail(function (data) {
console.log('Failed!');
});
});
However every time it fails. Even though checking the JSON shows it to be valid in the response. e.g. The headers say 200OK and list my valid JSON.
Valid JSON Returned with 200 OK response {"markup":"No markup here"}
Why then does the function fail?
Looks like it was a cause of the same domain! Finicky Javascript. ;)
Here's the total explanation. Thanks to all for your help.
See getJSON fails, JSON validates
I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).