I've started working with ajax a little lately, but I'm having trouble with something I feel is incredibly simple: storing a JS variable in PHP.
Say I want to store a zip code (assigned with Javascript) and pass that to a PHP variable via AJAX: Why doesn't this work?
Keeping it simple for demonstration purposes, but this is the functionality I desire..
zipCode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});
});
zip.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
<?php
echo $_POST['zip_code'];
?>
</body>
</html>
An error: "Notice: Undefined index: zip_code" is all that is returned. Shouldn't "123456" be echo'd out?
You are supposed to put this:
<?php
// query database before echoing an associative array of `json_encode()`ed data if a response is needed
echo json_encode(array('zip_code' => $_POST['zip_code']);
?>
on a separate page, that is not an HTML page. AJAX just sends to that page, so you can use it and echo it out, making database queries before that, or what have you. Upon success you will see the result of your echo as the argument passed to the success method in this case if you used data as the argument the result for zip_code would be held in data.zip_code. Also, set your dataType:'JSON' in $.ajax({/*here*/}).
Here:
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST',
dataType: 'JSON',
success: function(data){
// in here is where you do stuff to your page
console.log(data.zip_code);
}
});
When you load the page, a call is being made to the server for zip.php, however that request is in no way linked to the page you're currently viewing.
If you look at the response to your ajax request - you'll see a copy of the page with the correct zip code echo'd
The actual answer then depends on what exactly you're trying to do (and a less simplified version of the code) to give you the best option.
The current setup you have doesn't make sense in practice
That is not how AJAX works. Thake a look at the example below. It will make an AJAX post to handle_zip.php and alert the results (Received ZIP code 123456)
start_page.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
This is just a static page.
</body>
</html>
zipcode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'handle_post.php',
data: {zip_code:zip},
type: 'POST',
success: handleData
});
});
}
function handleData(data) {
alert(data);
}
handle_post.php:
<?php
die ('Received ZIP code ' . $_POST['zip_code']);
As others have mentioned, it sounds like you're expecting the two bits of code to run at the same time. The reality is that:
zip.php will be parsed on the server (and resulting in the error)
Server will then serve up the HTML to the browser (which will have a blank body due to the $_POST not existing when the PHP was parsed)
browser will see the javascript .ready() and run that code
server will handle the POST request to zip.php, and generate the HTML you're expecting. It'll be returned in the AJAX response, but as you're not handling the response, nothing is shown in the current session. (you can see the POST response using any of the common web developer tools)
Remember, PHP runs on the server, then any javascript runs on the client. You're also missing the step of handling the response from the request you made in your javascript.
try this to give you better idea of what's happening.
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});.done(function(data ) {
console.log(data)
});
In your code, the server is creating the page first, so no javascript is run yet, therefore it creates an error because $_POST['zip_code'] doesn't exist. Then it sends this page to your browser and you can see that. At this point is when your browser executes the javascript, it sends the request again, now with POST data, the server should return the response of the request and you should be able to see it in the console.
You could make this 2 separate pages, one for viewing the page, and anotherone for processing the ajax request, or if for your application you want to do it in the same page, you would need an if statement to get rid of that error, something like
if(isset($_POST['zip_code'])){
echo $_POST['zip_code];
}
Related
Is it possible to use Ajax, Jquery or Javascript to call a specific PHP Function and refresh / reload it every 10 seconds for example inside a specific Div or areas?
Connection.php
function TerminalStatus ($IPAddress, $portStatus ) // Responsible for current terminal status
{
$connectStatus = fsockopen($IPAddress, $portStatus, $errno, $errstr, 10); // Build cconnection to Terminal socket 25001
if (!$connectStatus) {
echo "$errstr ($errno)<br />\n";
} else {
$Status = fgets($connectStatus) ;
echo $Status ();
}
}
This connection is just to see the current status of a terminal.
I want to see the status of this function at the bottom of my index.php without refreshing the whole page.
I can accomplish this by putting this function in its own PHP Files (status.php) and using Javascript in the following way:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#Status').load('status.php');
}, 1000); // refresh every 1000 milliseconds
</script>
But i just want to utilise the function instead.
Is this possible?
The solution you have already is the correct way to do this: the JavaScript fetches a URL, and that URL renders the appropriate piece of content.
It's important to remember that, as far as the web browser is concerned, PHP doesn't exist. Any request from the browser - whether you've typed in a URL, followed a link, submitted a form, made an AJAX request, etc - is just a message to some remote server for a particular URL, perhaps along with some extra headers and body data. When the server receives that request, it can do whatever it likes to generate a response to the browser.
So when you write $('#Status').load('status.php');, the browser is sending a request to the server, which happens to be configured to execute the PHP script status.php. You can then do what you like in PHP to produce the response - but there is no direct link between a request and a PHP function.
However, as others have pointed out, you don't have to create a new PHP file for every piece of behaviour you want, because inside the PHP code you can check things like:
the query string parameters, in $_GET
submitted form data, in $_POST
the HTTP headers from the request
These can be set by your JavaScript code to whatever you like, so you could for instance write $('#Status').load('index.php?view=statusonly'); and then at the top of index.php have code like this:
if ( $_GET['view'] === 'statusonly'] ) {
echo get_status();
exit;
}
How you arrange this is entirely up to you, and that's what programming is all about 🙂
That's impossible to do this operation just with the PHP function.
you should use javascript as you use that or use socket in javascript to connect you status.php and update without refresh the whole page.
I'm not sure if i understood the problem but you can use AJAX to execute specific function. Something like this:
First build your ajax:
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus", // this will call the function
success: function(status){
$('#Status').text(status); // this will load the info you echo
},
});
Since you want to do it every second - wrap the whole thing with interval (i use your code from the question):
var auto_refresh = setInterval( function () {
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus",
success: function(status){
$('#Status').text(status);
},
});
}, 1000);
Then, on you PHP_FILE add condition the execute the specific function when POST been done:
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST['refreshStatus']) {
// run this code
}
Is that what you aimed to achieve?
jQuery::load() supports fragment identifiers. So you can just load the part that you want to replace:
$( "#Status" ).load( "status.php #PartId" );
This will load the HTML output of the script and extract the part. The PHP script will run completely - the rest of the HTML output will be thrown away on the JS side.
I am making a logout button which calls a PHP script via an AJAX call but somehow my php is not redirecting. Also when I try to use javascript it doesnt work either.
I tried the following things:
Adding ob_start() and ob_end_flush()
Changing exit; to exit();
Changing header("Location: http://localhost/page_login.html)
to echo("<script>location.href = http://localhost/page_login.html';</script>");
When I open the php script directly in my URL (by just typing it in) it redirects me to the page.login.html however from the ajax call its not. When I print the data it prints the page_login.html file which also excludes the option that its not in the correct map.
Anyone any ideas on how to fix this?
HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="logout_button">
Logout
</div>
<script src="jquery-3.2.1.js"></script>
<script src="logout.js" type="text/javascript"></script>
</body></html>
JAVASCRIPT (logout.js)
$('#logout_button').click(function(){
$.ajax({
type: 'POST',
url: 'logout.php',
error: function(response) { console.log(JSON.stringify(response))},
success: function(data){
console.log(data);
}
});
})
PHP (logout.php)
<?php
header('Location: http://localhost/page_home.html');
exit;
?>
You have a misunderstanding of how AJAX is working in this situation. When you're performing an AJAX call, a separate request is being sent as your POST to the given URL. This does not inherently affect the original page you are on in the client window. Essentially, what is happening is:
A user clicks 'logout'
The server (i.e. not the client's web browser) is sending a request to your logout.php
logout.php runs its code and returns a response to your original page (success/fail in this case; or some data if you had a return in your PHP page)
The AJAX here is only a means of sharing information between the two pages, not to run them in succession. What you need to do is redirect the original page, and you can do this with JavaScript! After all, don't forget that JavaScript is our client-side language, with PHP being the server-side one.
There are any number of ways to redirect in JavaScript which you can find. For example, you may use window.location.href in this case:
$('#logout_button').click(function(){
$.ajax({
type: 'POST',
url: 'logout.php',
error: function(response) { console.log(JSON.stringify(response))},
success: function(data){
window.location.href = "http://localhost/page_home.html";
console.log(data);
}
});
});
Use location.href in Javascript inside ajax to redirect or reload, not in .php file
$('#logout_button').click(function(){
$.ajax({
type: 'POST',
url: 'logout.php',
dataType: "json",
error: function(response) { console.log(JSON.stringify(response))},
success: function(data){
location.href = "/page_home.html";
//console.log(data);
}
});
});
Also send response data from .php to logout/session destroy, like
<?php
// Code here to logout or session destroy
// return json or string
$response["success"] = true;
echo json_encode($response);
?>
When you call directly your php file, header('Location: http://localhost/page_home.html'); add Location field to the HTTP Header that tell the browser to redirect the user to the specified location.
If you call it via ajax, jQuery doesn't care about this header field.
What you need is :
$('#logout_button').click(function(){
//Insert your ajax call here if you need to do something server side like destroy the session
window.location.replace('http://localhost/page_home.html');
})
EDIT: As mentionned in the comments, it will be simpler to use a link to your logout.php with the header('Location: http://localhost/page_home.html'); in it.
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 know it is not possible to simply call a function through ajax. As it only sends data via HTTP headers. However, I am trying to achieve something. I'm trying to execute a piece of PHP code, by the click of a button. The code consists of a shell_exec("omxplayer file.mp3")
So my ultimate goal is, to have a page load, display a button, which in turn, once clicked, will execute this piece of code (shell command).
I have looked for solutions and have not found one, even though there have been a lot of questions asked with a similar title to mine.
How can I achieve this concept?
EDIT: My ultimate goal is to use the shell_exec() to start playing a file using omxplayer on a linux machine.
You can use .get()
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$.get("script.php?code=myFunction", function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Execute Command</button>
</body>
</html>
script.php
if (!empty($_GET['code']) {
$output = shell_exec(<do shell command here>):
echo $output;
}
The following assumes that xxx is your PHP file and output is the response from the xxx file:
button.onclick = function() {
$.ajax({
url: '/my/site/xxx.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
};
You are looking at things the wrong way.
Create a separate page that executes the exec command and displays the result.
Create an interface page where - and you have a wide choice of options - when the user clicks a button you send him to the exec page.
I'm assuming you need or want to feed data to the exec command.
The page with the exec command can process values sent using GET and more securely POST (or REQUEST)
Just like any other html form would.
If you want to create a somewhat modern feel to an old school browser bash implementation you have a few options.
Submit onto self. Every time you submit the page will be redrawn
with the new data and the new exec will have run.
Submit into a target iframe. The interface will linger, the
iframe will update the contents.
xhtmlhttp post (asynchronous or "ajax" even though it doesn't
have to be) and update the contents of a div with the response -
from a separate php page.
I'm working on this function that loads a php file in the background:
<div id="content1"></div>
<script type="text/javascript">
<!--
$("#content1").load("/bm_products_filter.php");
//-->
</script>
The original php code is this:
<?php require('/bm_products_filter.php');
?>
With the original code the page works fine, with the java code it gives errors. This is because the php doesn't use the variables in the current page. I know how to pass variables to the external php but is there a way that it uses all the variables on the current page?
I am not sure if I got you wrong but you cannot load PHP files with JavaScript or JQuery.
JavaScript is client sided and has no access to the server if you want to load some data on a point of time when the template builds / is built without PHP oyu have to use an Ajax request which is also pretty simple with JQuery.
Please check out:
http://api.jquery.com/jquery.ajax/
If you can rewrite the bm_products_filter.php to return a JSON output, you can use a function as below to get values returned from the php.
jsonKey1 I have used below is one of the JSON keys returned from the php.
function getToken() {
var requestStr = "./bm_products_filter.php";
$.ajax({
url: requestStr,
type: "GET",
cache: true,
dataType: 'json',
success: function (data) {
bmProductsData = data.jsonKey1;
}
});
}
Hope this helps.