post data to page and open that page at the same time - javascript

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()).

Related

javascript variable to external php and back

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.

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.

Ajax using GET to PHP

I have seen many posts close to this but not this specifically so I will still ask it. I have a simple webpage that I am using to pass a value from to a server and then based on the value pass a response to the original webpage. Right now for testing purposes I am just using an alert for the final value.
My client side code is as follows submitAjax.php:
<!DOCTYPE html>
<html>
<head>
<script src="./jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#thisForm").submit(function () {
processData();
});
function processData() {
$.get('ajaxSubmit.php', function(data) {
alert(data);
});
}
});
</script>
</head>
<body>
<form method="get" id="thisForm">
<tr>
<td><input type=text name=box ></td>
<td><input type=submit value=Add></td>
</tr>
</form>
</body>
</html>
Server side ajaxSubmit.php:
<?php
$value=$_GET["box"];
if ($value==2){
echo "This is the returned text.".$value;
}else{
echo "not sent";
}
?>
As you can see from the code, I am trying to print the text "This is the returned text.2" as the output but when I enter "2" into the textbox my failure case of "not sent" is returned.
Any help would be great. I am very very new to all things javascript so please point out anything else I am doing incorrectly as well.
You're not passing anything when you're requesting ajaxSubmit.php.
$.get('ajaxSubmit.php?box=' + $("[name='box']").val(), function(data) {
alert(data);
});
So you want to request, ajaxSubmit.php?box=value, where value is the value of the html element named box.

getting value of html result after ajax postback

I need to get the html result of the ajax postback after changing the select option. The new-result-item is part of the new result div html which has a value generated from server side after ajax postback. The problem i am having here is if i call new-result-item is empty value although after ajax postback the value for new-result-item is actually display. So how can i get the new-result-item value after postback using javascript or jquery?
Note: new-result-item value is empty by default, it is generated by server side after ajax postback
<div id ="new-result">
<span id="new-result-value">#Model.NewResult</span>
</div>
$('select#select-option').change(function(){
$.ajax({
url: ...,
type: "POST",
cache: false,
success: function (result) {
$('#new-result').html(result);
},
complete: function (result) {
alert($('#new-result-item').val());
}
});
});
you can use the below sample code POST FORM DATA VIA ajax TO THE PHP PAGE it will work
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>ajax test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#restaurant').change(function()
{
if ($(this).val() == "") {
document.getElementById("txtHint").innerHTML = "";
}
else
{
$.ajax({
url: "test.php",
data : "q="+$(this).val(), //if you want to pass one variable
//data : "name="+name+"&natives="+natives, //if you want to pass more than 1 variable
type : "POST", // if you want to pass data via get method put "GET"
success :function(text){
alert(text);
document.getElementById('txtHint').innerHTML=text;
}
});
}
});
});
</script>
</head>
<body>
<table>
<form>
<td>
<select name="restaurant" id="restaurant">
<option value="">selection</optoin>
<option value="101">DA</option>
<option value="102">FV</option>
<option value="103">CS</option>
<option value="104">TO</option>
</select>
</td>
</form>
</table>
<b>Select restaurant</b> <div id="txtHint"></div>
</body>
</html>
test.php code
<?php
echo $_POST['q'];
?>
The construct $('#new-result') parses the current document for an element with ID new_result. Same with new_result_item
You want to parse the HTML returned by the ajax call which is currently NOT in the dom of the current document. You may look at this stackoverflow:
....
success: function (result) {
alert($(result).find('#new-result-item').html());
}
....
may give you the inner content of the returned HTML snippet

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>

Categories

Resources