javascript variable to external php and back - javascript

I need to pass value from javascript file (javascript.php) to php file (php.php), and get it back.
file javascript.php
<script>
var name = 'catalin';
$.post('php.php', {jsvar: name});
</script>
file php.php
$phpvar = $_POST['jsvar'];
How do I get variable's value back on the file javascript.php ?
Thanks!

$.ajax({
type: "POST",
url: url,
data: {"var":"value"},
success: function(data) {
// do something
}
});
https://api.jquery.com/jquery.post/

You can use callback function as below:
file javascript.php
<script>
var name = 'catalin';
$.post('php.php', {jsvar: name},function(data,status,xhr){
alert(data);
});
</script>
file php.php
$phpvar = $_POST['jsvar'];
echo $phpvar;

if you r doing this with ajax then just echo the php value and get it with return value in jquery
<script>
$(document).ready(function(e){
var name = 'catalin';
$.post('php.php', {jsvar: name},function(returnedValue){
alert(returnedValue);
});
})
</script>
in php do this
$phpvar = $_POST['jsvar'];
echo $phpvar ;
you can see the result in alert.

My answer is nothing new but find the complete code. I haven't tested it. Please be aware there might be a minor typo.
javascript.php
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="test_request()">Test Request</button>
<script>
function test_request() {
$.post("php.php", {jsvar: name}, function(data_from_php) {
console.log(data_from_php);
});
}
</script>
</body>
</html>
php.php
<?php
$phpvar = $_POST['jsvar'];
echo 'Hello' . $phpvar;
What's happening is jQuery is posting some value to the HTTP server (aka a POST request) and the anonymous function(data_from_php) is waiting for the server to respond with some data. As soon as the data arrives the function is triggered.
You can verify it from the Chrome's debugger window (or Firefox etc). For example, in Chrome just press Ctrl+Shift+I to open the developers tools. Click on the Network tab and click on XHR and notice when the request is made. You will be able to see what is happening under the hood and how it is working.

Related

Sending POST parameters between PHP files using AJAX calls

I have a PHP file test.php that has a simple link, which after being clicked, calls an AJAX function to send data as POST parameters to another file testPHP.php. The second file then receives the POST parameters from the AJAX call and then alerts the contents inside the $_POST array. The issue I am facing is that in the second file, the $_POST array is empty (I checked that using print_r($_POST)), so I think that the data hasn't passed through.
These are the 2 files:
test.php
<a id="link" role="button" href="testPHP.php">Test</a>
<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
data: {
parameter1: 'test',
parameter2: 'test2'},
success: function(msg) {
alert('wow' + msg);
}
});
alert('function end');
document.getElementById('#link').setAttribute('href','testPHP.php');
});
testPHP.php
if(isset($_GET))
{
echo "<script>alert('GET is there');</script>";
print_r($_GET);
}
if(isset($_POST))
{
echo "<script>alert('POST is there')</script>";
print_r($_POST);
}
if(isset($_POST['parameter1']))
{
echo "<script>alert('$_POST is set')</script>";
header('Location: HomePage.php');
}
else
{
echo "<script>alert('No post variable set')</script>";
}
What I have tried so far is to send a SUCCESS message if the AJAX call has been executed successfully, and it does alert me the Success message. I have also checked to see the contents of the $_POST array in the 2nd file to see if I am receiving data in a format other than a POST request (like a string that might have to be exploded to get the contents), but the $_POST array comes up empty.
This is the output I get when it redirects to the 2nd page:
Array() Array()
The $_POST and $_GET (for testing purpose) arrays come up empty.
I have also gone through the AJAX documentation, but can't get this simple POST data transfer to work. Can someone please help me with this issue so that I can understand how to properly send POST parameters and receive the data into $_POST['parameter1'] and $_POST['parameter2'] strings so I can process the data further.
Note: I have used the FORM's POST method using hidden form elements and that works fine, but I want to try this approach to better understand how AJAX works.
A slightly different version of the above which should help you solve your problem. For ease in debugging it is all one page but you can clearly see the script in operation once you click the button. Simply echoing javascript in the php code and hoping it will execute client side is not going to work - simply echo a message or a JSON object would be better.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
print_r( $_POST );
exit();
}
?>
<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<script>
$('#link').click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: location.href,
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}
});
alert('function end');
});
</script>
</body>
</html>
As 2 separate pages ( both in same directory otherwise edit page to the ajax target )
<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<br /><br />
<script>
$('#link').click(function(e) {
e.preventDefault();
$.ajax({
url: 'jquery-ajax-target.php',
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}
});
});
</script>
</body>
</html>
And the ajax target, jquery-ajax-target.php
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
$parameter1=( isset( $_POST['parameter1'] ) ) ? $_POST['parameter1'] : false;
$parameter2=( isset( $_POST['parameter2'] ) ) ? $_POST['parameter2'] : false;
$_POST['modified']=array(
'p1'=>sprintf('modified %s', strrev( $parameter1 ) ),
'p2'=>sprintf('modified %s', strrev( $parameter2 ) )
);
$json=json_encode( $_POST );
echo $json;
exit();
}
?>
Here is my version. It will return a JSON response to your ajax which will be visible in your console for easy debugging.
Your main page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="link" role="button" href="#">Test</a>
<script>
$(document).ready(function(){
$("#link").click(function(e) {
e.preventDefault();
console.log('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
dataType: 'json', //This tells your ajax that you are expecting a json formatted string as a response.
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
console.log(msg); //This will show the results as an object in your console.
}
});
console.log('Function End');
//document.getElementById('#link').setAttribute('href','testPHP.php'); //Why are you doing this. It's not needed.
});
});
</script>
Your testPHP.php page:
$results = array();
if(isset($_GET)){
$results[] = array(
'GET' => 'TRUE',
'getData' => $_GET
);
}
if(isset($_POST)){
$results[] = array(
'POST' => 'TRUE',
'postData' => $_POST
);
}
echo json_encode($results);
Here is an explanation of what is happening:
You make an initial call to your ajax by triggering some event. In your case it is the click of the link.
The click function leads to the actual ajax call which simply sends a post request to the testPHP.php.
The testPHP.php receives the post request and performs some sort of operation with the data that was provided by the ajax call.
The testPHP.php then sends back some sort of answer back to the ajax function. The data will be available in the success function.
You then get to decide how to use the data that was passed back from the testPHP.php page to the success function.
This is all done without your original page's code being refreshed.
You are not actually redirecting your user to another page.. You are just telling your page to goto another page and do some operation, which then gets reported back to the original page for you to do something with.
Hope it helps.
It does work after removing type attribute on script tag. I am using <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> before main script tag. It is working here. Also close the script tag. I hope I can help.
Also change the
document.getElementById('#link').setAttribute('href','testPHP.php');
to
document.getElementById('link').setAttribute('href','testPHP.php');
The problem with your code is that you are using javascript to change the attribute and in javascript once you used getElementById you no longer have to use # sign. try the following and it will work fine.
<?php
if(isset($_GET))
{
echo "<script>alert('GET is there');</script>";
print_r($_GET);
}
if(isset($_POST))
{
echo "<script>alert('POST is there')</script>";
print_r($_POST);
}
if(isset($_POST['parameter1']))
{
echo "<script>alert('$_POST is set')</script>";
header('Location: HomePage.php');
}
else
{
echo "<script>alert('No post variable set')</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="link" role="button" href="index2.php">Test</a>
<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
data: {
parameter1: 'test',
parameter2: 'test2'},
success: function(msg) {
alert('wow' + msg);
}
});
alert('function end');
document.getElementById('link').setAttribute('href','testPHP.php');
});
</script>
</body>
</html>
Furthermore it's a good practice to use the failed callback for the request.
error: function (xhr, status, error) {
alert(" Can't do because: " + error);
},

post in ajax with php get me undefined index

i want to send/pass data from the client to server by (ajax to php) but when i try this code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
console.log(w);
}
});
</script>
<?php
echo $_POST['data'];
?>
in my browser i got success print out which mean that the javascript code is working fine i guess , by in php i got Undefined index
p.s my file name is loo.php all the code is in the same file
edit: i have tried to separate my files like this:
my loo.php file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'test.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>
my test.php file:
<?php
echo $_POST['data'];
?>
still got undefined index
p.s. i navigate Manual to test.php file after i run loo.php file
You get this error because when loading the page the POST request has not yet been sent. So show the submitted data only if it exists, otherwise, show the JavaScript code.
<?php
if (isset($_POST['data'])) {
die($_POST['data']);
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>
Try this.
<?php
$data = json_decode(file_get_contents('php://input'), true);
echo $data['data'];
?>
Try this
Html file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data_value"></div>
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
$("#data_value").html(response);
}
});
});
PHP file (loo.php)
<?php
print_r($_POST);
?>
try to change the handler this way:
if(isset($_POST['data'])){
function return_data() {
die(json_encode($_POST['data'])));
}
return_data();
}
Answer after you edit the question:
$_POST is the array sent by the HTTP Post request. so if the request to the page named test.php or whatever is not HTTP POST Request the $_POST array will be empty. but the $_GET array may have some data if you sent them.
and navigation to a page is a get request to that page unless you used a form with method="post".
so what you are doing with ajax call is correct. but navigating to test.php manually without a form with post method is not gonna fill the $_POST array.
because when you make the Ajax call, it is done, it just makes the post-call correctly and everything is ok but when you navigate to that page it is a get request and it won't fill the $_POST array.
to do so, you don't need ajax at all. you can have this form
<form method="POST" action="test.php">
<input type="text" name="data" value="some data" />
<input type="submit" value="submit" />
</form>
so either you use ajax and handle whatever you want to handle in the ajax success method. or use form and send the request to the page and handle it there.
the answer to the question before the edit
If they are in the same file it won't work like that, because when the file loads the $_POST['data'] is not exists at all, and after you run the ajax call, it exists within that call, not in your browser window.
so you can check if $_POST['data'] exists so you are sending it from ajax call so you can return it and use it inside your ajax success function.
conclusion:
you cannot put them in the same file and expect ajax will load before the actual php.
it will first load the whole file then it will run the ajax.
the undefined index is from the server before you even see the HTML page.
A solution could be:
File with your html and ajax functions index.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
// use the response here
console.log(w);
}
});
</script>
and another with your logic loo.php
<?php
header("Content-Type: text/plain"); // if you want to return a plain text
// if you want to return json it could be header('Content-type: application/json');
echo isset($_POST['data'])? $_POST['data']: ''
?>

POST method does not display but GET method does

My POST method does not display on the webpage, but my GET method does even though I haven't create a method with it in my global.js. Does the GET method come with POST? I want my POST to display not GET. How do I do that? I know that my POST work i think because in network (that is in the browser with console), the POST method is there, and the preview prints out the $_POST and $_SESSION. How do I make POST to display on the page instead of GET.
Button.php
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script src ="global.js"></script>
<title>Button POST</title>
</head>
<body>
<button id ="postbutton" onclick="location.href='storage.php'">GO</button><br>
</body>
</html>
storage.php
<?php
print_r($_POST);
if(isset($_POST['json'])){
$_SESSION['object'] = $_POST["json"];
print_r($_SESSION);
echo 'True';
}else {
echo 'False';
}
global.js
var oject = [{name:'John', age:17},{name:'James', age:22}];
var json = JSON.stringify(oject);
$(document).ready(function(){
$('#postbutton').click(function(){
$('#output').html('sending..');
var jobject = JSON.stringify(oject);
console.log(jobject);
$.ajax({
method:'post',
url:'storage.php',
data:{json:oject},
})
.done(function(data){
console.log(data);
});
});
});
Your GET method is work because you used onclick with location.href method .That will always redirected with GET method so it can display your output ! But to work with POST method in ajax you need to remove onclick method and append return data to body element .
Button.php
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script src ="global.js"></script>
<title>Button POST</title>
</head>
<body>
<button id ="postbutton">GO</button><br>
</body>
</html>
global.js
var oject = [{name:'John', age:17},{name:'James', age:22}];
var json = JSON.stringify(oject);
$(document).ready(function(){
$('#postbutton').click(function(){
$('#output').html('sending..');
var jobject = JSON.stringify(oject);
console.log(jobject);
$.ajax({
method:'post',
url:'storage.php',
data:{json:oject},
})
.done(function(data){
$("body").append(data);
});
});
});
Why there's a onclick in button which you happen you call $.ajax() at the same time:
<button id ="postbutton" onclick="location.href='storage.php'">GO</button><br>
If you want to use $.ajax() no need for onclick. You can call location.href indside done(function(data) {}) if it met your conditions and you want to redirect the user somewhere else.

get post jquery and echo it in $_POST(is that possible?)

I'm learning how to post data to server.I want to click on a link and post its data to the server in the same page, do I need to have a form to do that? is it possible to post data without having a form? I cannot see the result in php should I have any success or done function here to have the results? I also have tried Last example of Jquery manual and there is no content div to see any results and so I couldn't figure it out.
I do not want to show data and append it in the html I want to see it in $_POST and if it is not possible to show it in the same page I am ok with that all I want is to see $_POST can have the data from JQUERY
<?php
if(isset($_POST["name"]))
echo $_POST["name"];
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(){
$.post("newfile5.php",
{
name: $("#link").val()
}
});
$('form#myform').submit();
});
</script>
</head>
<body>
<form id="myform" action="newfile5.php" method="POST">
<a id="link" href="" value="A">Send</a>
</form>
</body>
</html>
PS:I updated upon answers, and still not result:
<?php
if(isset($_POST["name"]))
echo $_POST["name"];
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(e){
e.preventDefault();
$.post("newfile5.php",
{
name: $("#link").data("value")
},
function(data)
{
// Whatever is returned by newfile5.php
}
});
});
</script>
</head>
<body>
<a id="link" href="" data-value="A">Send</a>
</body>
</html>
I expect to see $_POST['name'] having the value A, just this
Use data-attr to store data.
<a id="link" href="" data-value="A">Send</a>
Use
console.log($("#link").data("value"));
to fetch it.
So your code becomes
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(e){
$("#disp_name").html($("#link").data("value"));
e.preventDefault();
$.post("newfile5.php",
{
name: $("#link").data("value")
},
function(resp)
{
console.log(resp); // Whatever is returned by newfile5.php
}
});
});
</script>
</head>
<body>
<div id="disp_name"></div>
<form id="myform" action="newfile5.php" method="POST">
<a id="link" href="" data-value="A">Send</a>
</form>
</body>
</html>
and dont use $('form#myform').submit();
and to fetch data in PHP, use
$name = $_POST["name"];
I want to click on a link and post its data to the server in the same page, do I need to have a form to do that?
No. You can post the data without having a form.
EDIT
To answer the question after edit (if I well understand it):
Seems to me actually like a X-Y problem but the answer is - No .
PHP isn't able to interfere with the client browser. The AJAX is only a "bridge" between the server (PHP) and the page that has been fully rendered.
(you may want to read about WebSockets)
Fully rendered page have no access to the PHP variables anymore (doesn't matter if it's jQuery or any other client-side language). When connection to the server is completed (page fully rendered), all the PHP named variables and methods cease to exist. They could be set only at the time when the page is being rendered (and that's the only way to get these two languages to work together at the same time), eg:
<script>
var myData = "<?php echo 'something'; ?>";
</script>
Basically, the $.post is used to communicate with the server. If that's not required, you can access the data within the page itself and $.post is not even necessary.
You have an trigger event (click). You set the event to determine when an action should be taken and what is supposed to happen then. Whether it's an AJAX request or anything else.
If the AJAX is required:
var myData = '';
$("#link").click(function(e){
$.post(
"newfile5.php",
{name: $("#link").attr('value')},
function( data ) {
myData = data;
doSomething();
// do something else with the data here. ...
}
);
});
If there's no need to post any data:
var myData;
$("#link").click(function(e){
myData = $("#link").attr('value');
doSomething();
});
The method:
function doSomething(){
if(myData){
alert(myData);
}else{
// ...
}
}
in php access the $_POST variable
Edit:
First of all, you are combining two different ways and doing them wrong at the same time. You are making an AJAX request, and then sending a normal HTTP request without a value. Both wrongs, try this example, it will make an Ajax Post Request and show you the result in an Alert.
<?php
if(isset($_POST["name"]))
echo $_POST["name"];
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(){
$.post("newfile5.php",
{
name: 'Some Name'
}, function(data) {
alert(data)
}
});
});
</script>
</head>
<body>
<form id="myform" action="newfile5.php" method="POST">
<a id="link" href="" value="A">Send</a>
</form>
</body>
</html>
<?php
if(isset($_POST["name"])) {
echo $_POST["name"];
exit; //So we don't show the HTML in $.post response
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(){
$.post("newfile5.php",
{
name: $("#link").attr('data-value');
}).done(function(response) {
//Handle the response, just alerting for testing
alert(response);
});
//No need
//$('form#myform').submit();
//Event to see the response
});
});
</script>
</head>
<body>
<!--anchors don't have value attributes, use data- attribute-->
<a id="link" href="" data-value="A">Send</a>
</body>
</html>

Ajax PHP not returning updated variable

My apologies, similar questions have been asked before - Tried a lot of things and can't figure out why this is not working. I'm calling ajax via a click function. I can't seem to get the jList value to return, updating the variable in the main page.
Here is a simplified version of what is not working. PHP file:
<?php
echo <<<END
<script type="text/javascript">
jList = "ELLO!!??";
//alert(jList);
</script>
END;
?>
Main Page is this:
<script>
var jList = false;
...
...
...
function loadMore(listFile, nextS, nextE) {
url = 'files/php/jList.php?l='+ listFile +'&s='+ nextS +'&e='+ nextE;
$.ajax({
url: url,
type: 'POST',
success:function(results) {
console.log(jList); // can't get the var to update with the value from PHP
}
});
}
...
...
...
$("#readMore").unbind("click").click(function(e){
loadMore(listFile, nextS, nextE);
});
</script>
Continually returns (console.logs) the value set initially on the main page. What am I missing? Thanks.
Your PHP should be:
<?php
echo 'jList = "ELLO!!??";';
?>
And the jQuery should be:
$.getScript(url, function() {
console.log(jList);
});

Categories

Resources