Forgive the simplistic question. I'd like to pass a variable from javascript to php and I understand this can be done with an xmlhttprequest object. So I built a test script to figure out how to do this.
I'm using XAMPP and I placed the following files, main.php and test.php into their proper location in the htdocs folder.
main.php tries to pass a variable to test.php using an xmlhttprequest. test.php simply echos the variable. I then try and display the echoed result in main.php.
When I load main.php in a browser and view source, I expect to see the variable echoed. Instead I see an error message that the variable that was supposed to be passed to test.php is undefined.
Any help would be most welcome.
<html>
<head>
<title>Main</title>
<script type="text/javascript" src="../scripts/jquery-1.7.1.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","test.php?var1=hello", true);
xmlhttp.send(null);
<?php include("test.php"); ?>
});
</script>
</head>
<body></body>
</html>
Here is the code in test.php which resides in the same folder as main.php
<?php
$name=$_GET['var1'];
echo $name;
?>
I believe you're running the request in asynchronous mode, so check for ready state change:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","test.php?var1=hello", true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
I noticed that it looks like you're using jQuery (if it is Sizzle, ignore the rest of this),
so you don't need to use that! jQuery has built in Ajax methods that simplify it greatly!
$.ajax({
url:"test.php",
method:"get",
data:{
var1:"hello"
}
}).done(function(data){
alert(data);
});
Will create an XMLHttpRequest and send it.
Related
I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.
I am trying to load the output of a PHP script into a using JavaScript and JQuery. The JavaScript function I am using uses the $.get function in JQuery to call a php script, which I want to display in another division. The script I wrote is:
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
});
});
}
</script>
The PHP script (dbtest.php) uses a simple echo statement:
echo "hello, world!!!";
I am getting the first alert here, but not the second. What Can I be doing wrong here?
I suppose uname is a ID, in that case you should use:
$("#uname").html(data);
You can add this to your php for debugging:
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", 1);
Try also to remove http:// from your ajax call and use relative path instead.
The guys below pointed out that the selector is wrong. Indeed that's a problem, but I think that the real issue is that you don't get the second alert. Probably your php file localhost/dbtest.php is not accessible. What happen if you open localhost/dbtest.php in a new tab?
I think the problem is the path to your dbtest.php file. You are saying you seecond alert will not be displayed so your request must be wrong.
Try to copy your page into the same folder like dbtest.php open the page in your browser with http://localhost/yourfile.php
If this does not display both alert-boxes try the same with an open developer console (Chrome/IE = F12) and look if there are errors.
You say you are trying to make ajax requests to your localhost from a Phonegap application. Phonegap prevents making ajax requests to other domains by default. You must add localhost to whitelist. Here is more detail: http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html
Here you have a working example:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div id="uname"></div>
<script>
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("#uname").html(data);
});
});
}
on_load();
</script>
Beware of the same-origin-policy. The page loading dbtest.php must be from the same origin, unless you grant other origins by adding a header from dbtest.php.
Try add some error handling to your code to better see what´s happening.
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
}).fail(function () {
alert("failed");
});
});
}
</script>
I am current have the following script. I want pass a value from javascript to php by using AJAX. What's wrong with my code?
<script type=" text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.post("index.php",{host:document.referrer},function(data){});
});
</script>
<?php
$dataString=$_POST['host'];
echo $dataString;
?>
Since the PHP is executed first, you will never see the echo $dataString from your AJAX request. This code will post your request to the server, but you'll never see the result.
Right now here is what is happening:
Your web server renders out your page.
Your browser posts a request to index.php, and ignores the result
From the docs you can see this:
$.post('index.php', function(data) {
$('.result').html(data);
});
The data in that function will return what echo $dataString; outputs from your script.
Also, your post isn't configured correctly. You need to put data: before {host:document.referrer}
I am using an external javascript file to call a function and it will not. i get function not defined in firebug too.
the name of the external js file is getpic.js
in the html, i put this in the header:
<script src="getpic.js" type="text/javascript">
</script>
php:
echo "<button id='sldkfj' onclick='hg();'>sdlkfj</button>";
js:
function hg()
{
alert("hello")
}
the file system is basically in one folder for wamp
this is all of getpic.js
function hg()
{
alert("hello")
}
for the php part
<html>
<head>
<script src="getpic.js" type="text/javascript">
</script>
</head>
<body>
<?php
echo "<button id='sldkfj' onclick='hg();'>sdlkfj</button>";
?>
EDIT-----
i also keep getting this in firebug:
Reload the page to get source for: http://localhost/iframe/getpic.js
Thanks
Edit:
add the code segment to the html page as a
<script type="text/javascript">
function hg()
{
alert("hello");
}
</script>
if still it doesnt work there should be something wrong with the browser.
(disabled java script) try a different browser
if it works,
obviously there's an error in linking the file.
on firebug go to the script panel and see whether it is loaded or not. (you can also use net panel as well)
try linking
<script src="/getpic.js" type="text/javascript">
if you are at the localhost(www) directory or the absolute path
<script src="/mytest/getpic.js" type="text/javascript">
add ; at the end of the alert() command
function hg()
{
alert("hello");
}
Try taking the script tag out of the head element and put it in the body. I've had this problem before and that's what fixed it for me.
How can I use AJAX to run a PHP file when the page is loaded, I'm trying to create a small chrome extension and need to run my PHP file however nothing seems to be working I have this so far
var req = new XMLHttpRequest();
req.open(
"GET",
"my_php_file.php",
true);
req.send(null);
I solved with jquery...
(put at the bottom of your page)
<script type="text/javascript" src="./jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#container-id-to-load-into').load('file-to-load.php);
});
</script>
I tried a couple solutions on my own that didn't work b/c I needed to do multiple calls on page load and finally went with the JQuery solution I could find.
Hope that helps...