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.
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 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
After hours of playing with this, it hit me that my JQuery simply isn't executing.
I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.
Here is my main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('submitpicks').on('submit','#submitpicks',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
</script>
</head>
<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
var userPick = confirm("You picked " + thepick + ". Accept this pick?");
//var theid = "finalpick" + v;
var removebtn = "btn" + removepick;
//alert(theid);
if(userPick==1){
document.getElementById("finalpick").value=removepick;
document.getElementById(removebtn).disabled = true;
document.getElementById("submitpicks").submit();
v=v+1;
}
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
while($setrow = mysqli_fetch_array($setresult)){
//shuffle($setrow);
echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
$u=$u+1;
}
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results"> </div>
</body>
</html>
Here is my PHP:
<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>
you can use e.preventDefault(); or return false;
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault();
$.post('submitpick.php', $(this).serialize(), function(data) {
$('#results').html(data);
});
// return false;
});
});
</script>
Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php
<?php
echo 'File connected';
?>
and then alert(data) in js .. if everything works fine .. go to next step
Explain each Step..
before everything you should check you install jquery if you use
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then
1st to submit form with js and prevent reloading.. and you used <script> in your main page
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
<script>
output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step
2nd add $.post to your code
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
$.post('submitpick.php', $(this).serialize(), function(data){
alert(data);
});
});
});
<script>
and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory
<?php
echo 'File connected';
?>
output: alert with File connected
Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.
Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.
Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
And here's an example of how you can set it up with Jquery:
$(document).ready(function() {
$.ajax({
method: "POST",
url: "/something.php"
dataType: "JSON",
data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
success: function(data){
if (data["somevalue"]) == something {
dosomething;
} else {
dosomethingelse
},
error: function() {
alert("Error message");
}
});
});
This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:
Method
POST
POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.
GET
GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.
There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.
Url
The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:
<?php
$form_data = $_POST['data'];
$array = json_decode(form_data, true);
do something with your data;
$jsonToSendBack = "{status: 1}";
$response = json_encode($jsonToSendBack);
echo $response;
?>
So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.
DataType
Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.
Success and Error
Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.
Anyway, I hope my explanation is sufficient, and that you can take it from here.
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.
This question already has answers here:
Passing Javascript Variable to PHP using Ajax
(2 answers)
Closed 8 years ago.
I am thinking to use Speedof.me api to find out the user download speed accurately.I will use the value of the download speed to determine which video quality will be used to stream video to the user.
<html>
<head>
<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
</head>
<body>
<h2>SpeedOf.Me API Consumer - Sample Page</h2>
<script type="text/javascript">
SomApi.account = "SOM5380125e96067"; //your API Key here
SomApi.domainName = "domain.com"; //your domain or sub-domain here
SomApi.config.sustainTime = 2;
SomApi.onTestCompleted = onTestCompleted;
SomApi.onError = onError;
SomApi.startTest();
function onTestCompleted(testResult) {
var speed = testResult.download;
}
</script>
<?php
//how can i use the speed variable here
}
?>
</body>
</html>
I am a begineer with javascript and i would like to use the javascript variable in the php as shown above without reloading the page.I know that javascript is executed client-side and php is server-side but from what i read online is that ajax is the way to go.Also is there a way in which i can store the result of speedof.me so that i don't need to run the test every time the same user view a video
Thanks for helping me out guys
you can make an ajax call to server to use the javascript variable in php
function onTestCompleted(testResult) {
var speed = testResult.download;
$.ajax({
url:"link to php script" // e.g test/index.php
type:"POST", //method to send data
dataType:"json", //expected data from server
data:{speed:speed}, //data to send server
success:function(data){
alert(data); //alert response data after ajax call success
}
});
}
on php script you can use that javascript variable speed after checking $_POST[]
echo $_POST['speed'];
passing PHP values to javascript can just be echoed. But javascript to PHP is a bit complicated.
Server scripts like PHP are executed first before Browser scripts (i.e. javascript) do their job. this means, after the page has loaded, your php won't do any good anymore, EXCEPT, you use Ajax requests.
what I use is jquery function .post() (if you're wondering why i use post, you can do your own reading about this functions including .ajax() and .get() )
PHP code somewhere found in /project/execute.php
$speed = $_POST["speed"];
echo $speed * 5;
and in your javascript...
<script type="text/javascript">
SomApi.account = "SOM5380125e96067"; //your API Key here
SomApi.domainName = "domain.com"; //your domain or sub-domain here
SomApi.config.sustainTime = 2;
SomApi.onTestCompleted = onTestCompleted;
SomApi.onError = onError;
SomApi.startTest();
function onTestCompleted(testResult) {
var speedresult = testResult.download;
// here's the magic
$.post("/project/execute.php", {speed:speedresult}, function(result) {
alert(result);
} )
}
PS. DON'T FORGET TO IMPORT JQUERY IN YOUR SECTION OR THE BOTTOM MOST PART OF THE BODY
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
You do not seem to understand the fundamental differences between Clientside and Serverside Code.
The PHP Code will be executed serverside; only the output is sent to the browser. Then the browser executes the Javascript.
One solution to your problem would be to load the video dynamically with Javascript (either per Ajax or a simple video link naming convention). To store the speed test results, use a Cookie.
It doesn't work that way. As you said, JavaScript is client side. Your PHP page is processed by the server first--meaning, all PHP code gets executed first before any of your HTML, CSS, and JS. It doesn't matter if your JS is positioned first before PHP since PHP will get evaluated first. After that, it's sent back to the client for the browser to process HTML, CSS, and JS.
For your case, after running the speed test, send the value back to a PHP script via AJAX. You can use jQuery to make AJAX calls easier. Store a cookie using JS to indicate that the test has been executed once. You'll need to modify your JS so that it will check if this cookie is present and skip the speed test.
try this :-
<?php
echo "<script>alert(speed)</script>";
?>