I need help on how to call an external PHP script from within JavaScript.
See below for my example
INDEX.PHP
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myName = 'John';
phpResult = /* Need help calling script.php passing is myName and assigning result to phpResult */;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
</script>
</body>
</html>
SCRIPT.PHP
<?php
//script.php
//Need help adding last name to John (i.e. Smith) and returning John Smith to calling javascript
?>
First things first: What are you asking is cannot be done in the way you think. When a page is requested, the server runs the php file, and after that it will send you the javascript/html/css page to you. So when you see the page the php script has already done. Javascript is running on your machine, so that's why you can handle with it user interactions.
But, if you send a post request to the script.php, sending the information you want, then you will be able to interact with a php file. To do this, you need jquery. Here is the script how you can do it in jquery:
$.ajax({
type: "POST",
url: "yoursite/script.php",
data: "name="+myName,
success: function(data){
phpResult = data;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
}
});
You can download jquery from here: http://jquery.com/download/
After you have downloaded, you have to link it to your index.php the jquery.js file, as a normal javascript file.
In your php file, you can access the name with $_POST["name"], and the information you want to send back, you have to actually print it.
Something like this:
if(isset($_POST["name"])){
$result = "";
//Do something with the name, and fill accordingly the $result variable
// Something like:
$result = $_POST["name"]." Smith";
echo $result;
}
You can simply write
phpResult = '<?php echo $sometext; ?>';
But,
the js script needs to be in a php file. you cannot use this in .js file obviously.
this will not evaluate any runtime variables on the client side. because the page will already contain vars rendered by the php script from the server.
I use this method all the time specially for rendering php arrays and objects as js objects/arrays.
Related
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
I have been reading so many posts and none of them seem to work for me I have no idea what I am doing wrong. I want to call a PHP integer in JavaScript and set it to a JavaScript variable so I am then able to use that variable in my calculations.
average = '<?php echo $average; ?>';
console.log("value" + " " + average);
This is the code I have been using and it prints to the console:
value <?php echo $average; ?>
This is clearly not the resulted I wanted, I wanted it to print the integer.
My $average PHP integer is also located in a different file so I used:
<?php include 'DBObject.php';?>
I want to be able to do a calculation like:
drone1percentage = 1000 / average * 100;
but since the average variable isn't taking the php integer $average from my other file it doesn't work.
You could add this to your .htaccess, so PHP will interpret js files too.
<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Or rename that .js to .php and add this header in front of the file:
header('Content-Type: application/javascript');
You "cannot" execute php inside a javascript file.
However there are some tricks to get to your variables from php.
One of them is creating a javascript variable with php and use this variable inside your javascript file.
Example:
// Inside your php file
<script>
var average = <?php echo $average; ?>
</script>
<script src="yourjavascriptfile.js"></script>
// Inside your javascript file
console.log(average);
use jQuery.ajax - http://api.jquery.com/jquery.ajax/
var average;
$(function(){
$.get("path/to/script", function(data, status){
average = data;
});
});
For me the most reliable way to get information from PHP into javaScript is using jQuerys ajax functionality.
So if you have something like
yourPHPFile.php
<?php
if($_POST['action'] == 'getAverage') {
echo returnAverage();
die;
}
function returnAverage() {
//your average calculation here
return $average
}
You could do something like
yourJavaScriptFile.js
var average = null;
$.ajax({
method: 'POST',
url: '/path/to/yourPHPFile.php',
data: {action: 'getAverage'},
success: function(response) {
average = response;
}
});
Just put this inside a function that is triggered whenever you need it.
For this to work you need to have jQuery included. For further information about the jQuery.ajax() functionality see The Documentation.
Please also note that some ajax parameters might differ depending on the version of jQuery you use.
Your js file has to end in .php for example example.js.php in order for the php code to be parsed.
While you cannot put php code into a .js file, you can create a js file from php
You could also setup the web server to parse all .js files as php code, but that would be a bit too much perhaps.
Try this:
average = parseInt('<?php echo $average; ?>');
I got stuck when using ajax as primary request sender to php.
I was trying to send data to php file and then take that data to view in another file, but the problem is I don't know how to do it .
I tried
var ajax = ajaxObj("POST", "function.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
window.location = "view.php";
}
}
ajax.send("a="+a+"&b="+b);
it locate view.php and I want to take contents that sent
function.php and view it's contents in view.php.
That is where my problem occurs.
So, my question is HOW TO TAKE THOSE CONTENTS
I think you don't understand the use of ajax... here you don't need ajax at all. Ajax is used to update/send content without refreshing the page. So if you want to pass data to a new php file, just pass the variables directly to view.php in your case.
For instance:
go to view.php?a=[your value]&b=[your value]
in view.php you can get the values:
$a = $_GET['a'];
$b = $_GET['b'];
and pass it to your function.php
Use Jquery to avoid dealing with browsers specifications and also jquery is pretty popular and simple to use library
Assuming you are familiar with php and JavaScript
first you have to do all this work in you www or htdocs folder depending on the stack you are using whether it is XAMPP,WAMP or LAMP
let's say as an example we want to send post request to function.php file and that file should verify the existance of $_POST['username'] and return the length of username otherwise it returns 0
so the function.php file should be something like this :
if(isset($_POST['username'])){
echo strlen($_POST['username']);
}else{
echo 0;
}
and the view.php file is the file used to send post request and get the response and displays it in a #display div
so here is the content of view.php
// first you should include jquery
// here is a cdn link
// https://code.jquery.com/jquery-2.1.3.min.js
// or you can use a local jquery file it is up to you
<div id="display">
</div>
// here is the simple js code to send and get the data from function.php file
<script>
$(document).ready(function(){
// waiting for the document until it is ready to use
$.post('function.php',{username:'myusername'},function(data){
// data here is the returned data from the function.php file
$('#display').text('username length is : '+data);
});
});
</script>
I have a file like "my_js_stuff.js" which is looking like this :
function my_js_function()
{
jQuery.ajax({
url: my_ajax_script.ajaxurl,
data: ({action : 'get_my_comments'}),
success: function() {
//Do stuff here
}
});
This file is included in my
<header>like this: <script type="text/javascript" src="my_js_stuff.js"></script>
I want to call the function from "my_js_stuff.js" inside my php page, and I'm thinking to call it like this:
<?php
<script type="text/javascript>
$('.some-class').on('click', my_js_function()); // this is the function from the js file.
</script>
?>
Is this the correct way to call the function from the js file ?
Thank you !
Is this the correct way to call the function from the js file ?
my_js_function() is certainly the correct way to call it.
But, to pass the function so the event can call it later, you'll want to skip the calling parenthesis:
$('.some-class').on('click', my_js_function);
With them, it'll be called immediately and its return value will instead be passed to the event binding.
Also note that the <script> shouldn't be inside a <?php ... ?> block unless it's in a string being echoed.
<?php
# ...
?>
<script>
$('.some-class').on('click', my_js_function);
</script>
<?php
# ...
?>
You could do that, but I'm not sure that's what you actually want to do. Javascript is executed on the client-side, whereas PHP is executed on the server. Your Ajax function makes a request (client-to-server) and fetches content from the server, such as dynamic content generated from a PHP file.
If what you're describing is really what you want to do, you need to echo your script snippet and enclose it in quotes.
<?php
echo '<script type="text/javascript">/*js content*/</script>';
?>
You're confusing the technologies. Your JS is for the client side (browser) and the PHP is for the server side (business logic).
You cannot call a JS function from inside PHP.
However, assuming you want to communicate JS > PHP, you need to include the JS on your page.
<script type="text/javascript?>
$('.some-class').on('click', my_js_function()); // this is the function from the js file.
</script>
and your URL needs to match the PHP endpoint:
url: my_ajax_script.ajaxurl, // This should be the path of your PHP file
Inside the php file you can get all the info as if it were a normal request:
<?php
echo $_GET['action'];
?>
This will return the $_GET['action'] var to your JS success function:
success: function(data) {
alert('Received: ' + data);
}
Hopefully you can use this information to build what you need.
I have this JS function and I'm looking for the simplest way to send a variable to php and have php return an array to my JS. I have the second part down I just need help sending the variable. Here's my function:
function myEvent(){
//console.log(uploaded);
var length = uploaded.length;
var content = document.getElementById("Profile");
if(length == 0){
content.innerHTML = '<p style="text-align:center"><b> You uploaded no events. </b></p>';
}
else {
content.innerHTML = " ";
for(var i=0; i<length;i++){
var entry = document.createElement('li');
var EID = uploaded[i][0];
entry.innerHTML= ''+uploaded[i][1]+'';
content.appendChild(entry);
}
return false;
}
}
I want to be able to send EID which is a unique ID to a PHP script every time I click the link.
Any help? I'm using Jquery but I'm not too familiar with it. If there's an option using JS alone I would really appreciate it.
You can do that using Ajax. There's also another really simple way to send data to a php script on any server (same domain or not) while making that php script interact with your page
first you create a script tag:
var tag = document.createElement('script');
the src of that tag will be the url of the php script that will receive the variable:
var myVar = 'foo';
tag.src = '/path/to/my/script.php?variable='+myVar;
you add the script tag to the dom to request it
document.getElementsByTagName('head')[0].appendChild(tag);
on the server side the php script receives the variable and does whatever it should do with it, and optionally it can echo any javascript that will run on the page afterwards:
<?php
echo "alert('".$_GET['variable']."')";
that's pretty much it, WARNING, be aware that this is just a simple example, to implement something like this on a production site you need to make sure that doing so won't open your site to XSS attacks, code injection etc... how to do that is beyond what is being discussed here but be aware
Make sure you view this using firebug, or anything similar in order to see the returned results, in the jquery done function you can then do data[0], etc for the arrays
html
<!DOCTYPE html>
<html>
<head>
<title>JQuery Test</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="myjs.js"></script>
</head>
<body>
<button id="sendData">Send Data</button>
</body>
</html>
JS
$(document).ready (function (){
$("#sendData").on ("click", function (){
jQuery.ajax ({
url: "index.php",
type: "POST",
data: {returnArray: 1}
}).fail (function (){
console.log ("failed");
}).done (function (data){
console.log (data);
});
});
});
PHP
if (isSet ($_POST ['returnArray']))
{
$a = array ("a", "b", "c", "d");
header('Content-type: application/json');
echo json_encode ($a);
exit;
}
I am sure you can figure this out... show some effort.. and don't be afraid to ask if you still don't understand.. just as long as you try.
Use JavaScript's XMLHttpRequest to send a message to the server running PHP. When the PHP script responds, the XMLHttpRequest object will let you know and you'll be able to grab the XMLHttpRequest.responseText.
It would be a good idea to have PHP respond with JSON, which it can do easily. Then you can parse the responseText with JavaScript's JSON.parse function and just use it.
The following two articles will show you how to use the standard objects.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
http://www.php.net/manual/en/function.json-encode.php
You'll just have to be sure you don't try talking to a different website than the one your page is loaded from, unless you want to learn all about cross domain requests.