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.
Related
In the below Javascipt code I am sending data to a page named "book.php".It is succesfully sending the data through post method(because I am getting the alert) but when I open book.php to display the recieved data,It is not showing anything.
<script type="text/javascript">
$(document).on("click", ".open-AddBookDialog2", function (f){
var train_date=$(this).data('id');
$.ajax({
type: 'post', // the method (could be GET btw)
url: 'book.php', // The file where my php code is
data: {
'train_date': train_date // all variables i want to pass. In this case, only one.
},
success: function(data) { // in case of success get the output, i named data
alert("success"); // do something with the output, like an alert
}
});
});
</script>
Book.php is showing output as nothing.
Is there any way I can open the same page while sending post data to it?I want to use that $_POST variable to sql.
book.php-
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<style>
body {
background-image: url("rail.jpg");
background-color: #cccccc;
background-size: 100% auto;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<p>
<?php
if(isset($_POST['train_date'])) { //if i have this post
// print it
echo $_POST['train_date']; }
else{
$var="nothing";
echo "nothing";
}
?>
</p>
</body>
</html>
Don't use XHR/Ajax. A simple solution is to create a hidden <form method="post"> element, create likewise hidden input fields for your data (in this case just train_date) fill it with values and then trigger the form submission using javascript. The browser will then be redirected as you request.
Example:
JS:
$(document).on("click", ".open-AddBookDialog2", function (f){
var train_date=$(this).data('id');
var hidden_form=$("#hidden-form");
var hidden_input=$("#hidden-form-input");
hidden_input.val(train_date)
hidden_form.submit()
});
HTML:
<form method="post" id="hidden-form" style="display:none" action="book.php">
<input id="hidden-form-input" name="train_date" />
</form>
Use ajax to send variable to php. In php stock that variable in a session (search around, is simple) then in your ajax success do a redirect: How to redirect to another webpage? . In php you will have now your var stocked in $_SESSION. Do what you need with it, manipulate the flow of execution with some if(isset()).
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.
I want to use an onclick event with PHP in order to accomplish the following. I would like to use ajax to avoid the page being refreshed. I want to create buttons on event click.
I don't know how to join the div buttons with the ajax result.
Here is my PHP file: Button.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dymanic Buttons</title>
<script type= "text/javascript" src ="jquery-2.1.4.min.js"></script>
<script type= "text/javascript" src ="test.js"></script>
</head>
<body>
<div>
<input type="submit" class="button" name="Add_Button" value="Add Button"</>
<input type="submit" class="button" name="Modify_Button" value="Modify Button"</>
<input type="submit" class="button" name="Delete_Button" value="Delete Button"</>
</div>
test.js contains this:
$(document).ready(function () {
$('.button').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue
};
$.post(ajaxurl, data, function (response) {
alert("action performed successfully");
});
});
});
And the other php that is ajax.php
<?php
if (isset($_POST['action'])){
switch($_POST['action']){
case 'Add_Button':
Add_Button();
break;
}
}
function Add_Button(){
echo '<input type="submit" class="button" name="Test_Button" value ="Test Button"</>';
exit;
}
?>
You're calling the <input>'s value, instead of it's name which you set it as.
Change your clickBtnValue to this:
var clickBtnValue = $(this).attr('name');
Since it has Add_Button/Modify_Button/etc.
To append the new button to your div, start by giving it an id, so that we can continue to call it:
<div id="my-buttons">
Now in your ajax request, simply jQuery.append() the html to the div:
$.post(ajaxurl, data, function (response) {
$('div#my-buttons').append(response);
});
You can add the result of request to your div with this:
$.post(ajaxurl, data, function (response) {
$("div").append(response);
alert("action performed successfully");
});
Note the value of your button is "Add Button", not "Add_Button"
You probably want to make sure that each component of your code is working first. The problem may be in your AJAX call, it should be similar to the following:
/** AJAX Call Start **/
// AJAX call to dict.php
$.ajax({
/** Call parameters **/
url: "ajax.php", // URL for processing
type: "POST", // POST method
data: {'action': clickBtnValue}, // Data payload
// Upon retrieving data successfully...
success: function(data) {}
});
Also, make sure you are using the correct routing to your PHP file and that your PHP file is returning a valid response.
EDIT: As per the jQuery Docs, I am fairly certain that the problem is within your AJAX call, specifically your $.post() setup. Please refer here for the proper setup is you want to keep your AJAX call structured as is instead of the way I suggested.
As per the jQuery Docs:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
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>
I'm trying to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST, but I get the error message "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on line 9".
I'm using XAMPP, I'm running the code in localhost, I'm using Mozilla Firefox and here's my HTML/PHP code (test1.php):
<!DOCTYPE html>
<html lang="hu">
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
</head>
<body>
<?php echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";?>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
And here's my jQuery code (script1.js):
$(document).ready(function() {
var temporaryVariable = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
alert('success');
}
}).done(function() {
$('.testParagraph').addClass( temporaryVariable );
});
});
What I tried changing so far (but didn't work of course):
test1.php:
charset was previously iso-8859-2
GET instead of POST in both codes
commenting out the script tag includes
script1.js:
commenting out the $(document).ready(function() {... lines
in data: I tried changing the quote symbols from ' to " or no quote symbols at all
commenting out the success: function... line and the two lines below it
Also, when I run the PHP code, the p tag gets the temporaryVariable class from the jQuery code.
Still, I get the error message written above. I would appreciate any help I get.
Change your test1.php to:
<!DOCTYPE html>
<html lang="hu">
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
</head>
<body>
<p id='testParagraph'> </p> <!-- You receive the value by jquery not from PHP. -->
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
And your script1.js to:
$(document).ready(function() {
var temporaryVariable = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
alert('success');
}
}).done(function() {
$('#testParagraph').html(temporaryVariable); //The value is inserted into the paragraph.
});
});
Hope works for you.
Unless you are getting the php page from a post request, using $_POST['testData'] will be of no use and will always give an index not found error. If you want to set the value in the p tag from jquery, you could use $('.testParagraph').html( temporaryVariable ) instead of .addClass
Use data : 'testData=2',
Instead of data : {testData:"2"},
Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php
on line 9
means your
data: { testData:"2" },
is wrong.
Didn't test it, but this should work:
data: [ testData:"2" ],
because $_POST is an Array
It sounds like you're posting test1.php to itself, and it's not clear why you would do that.
As #Rasclatt has pointed out in the comments check to see if the data exists before you try to access it.
Change:
<?php echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";?>
To:
<?php
if( isset( $_POST['testData'] ) ) {
echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";
}
?>
If, however, test1.php is a different script altogether then make the following changes:
Include a placeholder for the ajax content in your HTML:
<p class="tetParagraph"></p>
Trim and edit your JavaScript to the following:
$(document).ready(function() {
var tempVal = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
tempVal = result;
$('.testParagraph').html( tempVal );
alert('success');
}
});
});