I have the following JS code:
<script>
$('#mpxModalEdit').on('show.bs.modal', function(e) {
var editId = $(e.relatedTarget).data('edit-id');
$(e.currentTarget).find('input[name="editId"]').val(editId);
});
</script>
This places the CORRECT edit-id value into a form text box name=editIdas I wish.
I would like to add another line of JS so that it ALSO places the value into a PHP variable since I need to make a subsequent
$query = "select * from playlists where id='editId'
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
That could be the best solution only.
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
Or the another way is to use AJAX.
PHP-Scripts are only run, when you load your page before any js is run or make an AJAX. In addition, PHP runs on the server, while JS is client-side.
My first suggestion would be, to really think, whether you need to do this (or even tell us, why you think it is).
If you really need it, you can perfom an AJAX and send your variable as data to the Server.
Using AJAX call you can pass js values to PHP script. Suppose you are passing editId js value to logtime.php file.
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data: { editId : editId },
success: function(data)
{
alert("success!");
}
});
});
});
<?php //logtime.php
$editId = isset($_POST['editId']);
//rest of code that uses $editId
?>
Place the AJAX call after
$(e.currentTarget).find('input[name="editId"]').val(editId);
line in your js script.
then you can assign to your desired PHP variable in logtime.php file
Related
I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!
I need help on something that sounds easy but is difficult for me.
So when someone clicks on this div:
<div onclick="<go to url sending data using the post method>">Click Me</div>
I want it to send data to a PHP file that will take the information that i want it to. I would use the GET function but I have heard that its easily hackable. If their is a lot simpler solution or something more secure please help me out.
If you need to use div you can do it like this but I suggest that you use button or input of type submit.
<form id="form-id" method="post" action="your-php-file-url">
<input type="hidden" name="your-variable-name" value="your-variable-value">
<div onclick="document.getElementById('form-id').submit();">Click Me</div>
</form>
Also you may use jQuery or some other JS library.
NOTE: Keep in mind that if the data that you send is provided via browser it's really easy to manipulate (doesn't mater if you use POST or GET) so it's important to check it out when you process it.
Using form would be ideal. If for some reason if you don't want to use form or want to build a dynamic app then use it in this way.
//jquery library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="someInput">
<div onclick="sendData()">Click Me</div>
<script>
function sendData(){
//get the input value
$someInput = $('#someInput').val();
$.ajax({
//the url to send the data to
url: "ajax/url.ajax.php",
//the data to send to
data: {someInput : $someInput},
//type. for eg: GET, POST
type: "POST",
//datatype expected to get in reply form server
dataType: "json",
//on success
success: function(data){
//do something after something is recieved from php
},
//on error
error: function(){
//bad request
}
});
}
</script>
You can use <form> to send data
<form action="yourpage.php" method="post">
//form contents
<input type="submit" value="Submit">
</form>
The action URL specifies the URL of the page to which your data has to be send.
I'm new to PHP and am trying to figure something out that I'm sure is very basic. What I am wanting to do is generate variables in javascript and pass these to a PHP page which then loads and displays. The problem is, I seem to be able to both POST variables to the PHP page and load the PHP page but am unable to load the PHP page with the variables that I POSTed.
Here is an example of my code:
index.php
...
<script language="javascript">
function passToPHP(){
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
data: {
varToPass: "foo"
},
success: function(){
window.location.href="/TraceExperiment/TraceExperiment.php";
}
})
}
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
TraceExperiment.php
<?php
$tempVar = $_POST["varToPass"];
echo("hello" . $tempVar);
print_r($_POST);
?>
What is happening when I click displayPHP is that the ajax POST succeeds and
TraceExperiment.php loads fine (it actually has a whole heap of other html, php etc. code that loads and displays fine but for simplicity I've excluded that) but the $_POST array seems to be empty.
i.e. what ends up being displayed when I try to echo and print the POST array and variables is:
Notice: Undefined index: varToPass in C:\xampp\htdocs\TraceExperiment\TraceExperiment.php on line 3
helloArray ( )
Any help resolving this would be much appreciated. Ultimately, I'm simply after a way to display a PHP page that uses variables passed from a javascript file.
You can dynamically create a form in JavaScript and submit it rather than calling ajax and refreshing the page:
<script language="javascript">
function passToPHP(){
$('<form action="/TraceExperiment/TraceExperiment.php" method="POST"><input type="hidden" name="varToPass" value="foo" /></form>').appendTo('body').submit();
}
</script>
<input type="button" value="displayPHP" onclick="passToPHP()"></input>
You can do a get request like this
<script language="javascript">
function passToPHP(){
var varToPass= "foo"
window.location = "/TraceExperiment/TraceExperiment.php?varToPass="+varToPass;
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
<?php
$tempVar = $_GET["varToPass"];
echo("hello" . $tempVar);
?>
or a post request by creating a simple form
$('#frm').submit(function(e){
var varToPass= "foo"
e.preventDefault();
$(this).find('#varToPass').val(varToPass);
$(this).submit();
});
<form id ="frm" method="POST" action="/TraceExperiment/TraceExperiment.php">
<input type="hidden" id="varToPass"/>
<input type="submit"/>
</form>
dont redirect to the same page on success. you are getting the undefined var on second go to that page
function passToPHP() {
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
dataType:text,
data: {
varToPass: "foo"
},
success: function(data) {
console.log(data);
}
})
}
try doing like this
if you want to show the message in the html
try
success: function(data) {
$('body').append(data);
}
There is 2 solution for This
by the different approach
Generate your variable value by JavaScript and than use
Write in TraceExperiment.php
function genratenumber(){
return "number"
}
window.location.href= "/TraceExperiment
/TraceExperiment.php?yourvar="+genratenumber()
</script>
<?php }else{
// get the value of $_GET['yourvar']
} ?>
Than get it by using $_GET['yourvar'] on same page
By using your approch
you need to put that variable in session (in ajax file) than only you can get that variable
UPDATED:
Okay, Thanks to OneSneakyMofo's Help below, I have managed to use ajax to call a submit.php form and have it return for example an echo statement. My problem is that none of my $post values are being carried over, for example if my start my php script with if (isset($_POST['pizzacrustformid'])) { the javascript will return blank, also when I do a var_dump($_POST);, Nothing is being saved into it which means the data is not being carried over, the php script is just being called. Please let me know if there is something I need to do in order to get the POST information to get carried over from the form as it would with a
< Submit > Button traditionally.
I Have Updated my code on Github to reflect my progress. https://github.com/dhierholzer/Basiconlineordering Thanks Again!
ORIGINAL POST:
I am new to using jquery and having forms be submitted without loading a newpage /refreshing the page.
In my Code I have multiple forms on one page that display one at a time via fade in and out effects by hitting the next button.
My problem is now that I do this, I cannot seem to get a PHP script to activate when hitting the next button to save those form options into sessions.
So here is an example:
<!--First Pizza Form, Pick Pizza Crust Type-->
<div id="pizzacrust">
<form method="post" name="pizzacrustform" id="pizzacrustformid">
<div id="main">
<div class="example">
<div>
<input id="freshpizza" type="radio" name="pizzacrust" value="1" checked="checked"><label style="color:black" for="freshpizza"><span><span></span></span>Fresh Dough</label>
</div>
<div>
<input id="originalpizza" type="radio" name="pizzacrust" value="2"><label style="color:black" for="originalpizza"><span><span></span></span>Original</label>
</div>
<div>
<input id="panpizza" type="radio" name="pizzacrust" value="3"><label style="color:black" for="panpizza"><span><span></span></span>Deep Dish Pan</label>
</div>
</div>
</div>
</form>
</div>
<div><button href="#" id="btn">Show Pizza Size</button></div>
So this Is my First Form, One thing to pay attention to is that instead of a < Submit > button, I am using a normal button and using javascript to do the submitting part.
Here is that Javascript:
<!--Controls All Button Fades-->
$('#btn').click(function(e){
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
$('#pizzacrustformid').submit();
});
});
and Then:
$(document).ready(function () {
$('#pizzacrustformid').on('submit', function(e) {
e.preventDefault();
});
});
Now Traditionally being a php programmer, I just had a button in my form and then my php activated by having something like:
if (isset($_POST['submitted'])) { //MY Code To save values into sessions}
I cant seem To Get a function like that working when the form is submitted via a javascript function as I have it.
Here is my full code in my GitHub which may make it easier to see more so how these forms are working together right now.
https://github.com/dhierholzer/Basiconlineordering
Please Let me know any solutions that might be possible
Thanks again.
Edit:
OP, it looks like you are wanting to do AJAX, but you don't have anywhere to submit your AJAX to. Firstly, you will need to create a file that accepts the form.
Let's call it submit.php.
With that in place, you can start working on the AJAX call. To begin, you will need to separate your code from index.php.
Take this out of index.php and put it in submit.php:
if (isset($_POST['pizzacrustformid'])) {
// use a foreach loop to read and display array elements
echo '<p>hello!<p>';
}
In your Javascript, you will need to do something like the following:
$('#btn').click(function(e){
$.ajax({
method: "POST",
url: "some.php",
data: $('#pizzacrustformid').serializeArray()
})
.done(function(data) {
alert(data); //should be "Hello world"
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
});
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
});
What is happening here is is on submit, your form data will pass over to the submit.php page, and it will generate the PHP code. That code will hit the done function (if it's successful), call an alert, then fade out to the next section.
That should get you on the right path. I would create another branch and strip out all of the forms and work on getting this done before continuing.
Also, I would set this all up in one single form and show the first section, do some validation, and then move on to the next section before finally submitting eveyrthing you need.
Hope this helps.
I recommend you do requests via ajax, here a tutorial and examples:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
delete all jquery functions about submit
create a file called blu.php with the php code
add the jquery code in index.php
with this you only do once request at the end. I hope this helps you.
<?php echo 'tus datos son: ';
echo ' '.$_POST["data1"];
echo ' '.$_POST["data2"];
echo ' '.$_POST["data3"]; ?>
<script>
$(document).ready(function(){
$("#btn5").click(function(){
var pizzacrust= $('input[name="pizzacrust"]:checked').val();
var pizzasize= $('input[name="pizzasize"]:checked').val();
var pizzatoppings= $('input[name="pizzatoppings"]:checked').val();
$.post("blu.php",
{
data1: pizzacrust,
data2: pizzasize,
data3: pizzatoppings
},
function(data,status){
alert("Data: " + data);
});
});
});
</script>
I think you need to using click() func call ajax, dont use on() submit. Submit action makes current page will refresh. I will review your code later, but you should to try this solution above.
Recently I am confused about whether it's possible to send input/textarea data directly without being included in html <form>. I thought in web page, if we want to get information from user then send the text to authentication server, we must use <form> irrespective of in which way it's submitted.
But an anonymous reviewer of my paper claims that <html> can be bypassed by using an html5 tag "textarea" and JS AJAX post. While I did lots of experiments trying to implement his way but all failed.
I wonder if there is really some way to submit user info without using <form> tag?
Thank you
Thanks for everyone's reply.
Update: I followed "the_void"'s code and changed the url of AJAX to a ServerSocket (implemented by Java). The server was able to get the POST event, but it cannot read the "data" of AJAX. The following is the html code:
HTML
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
// information to be sent to the server
info = $('#foo').val();
$.ajax({
type: 'POST',
url: 'http://10.0.0.3:8888',
data: ({ foo: info }),
// crossDomain: true,
// dataType: 'json'
});
return false;
});
});
</script>
</head>
<body>
<label>Text</label>
<textarea id="foo"></textarea>
<button id="submit">Submit via Ajax</button>
</body>
</html>
It seems that the socket server cannot read from AJAX (but it can read from < form > + < action >). Is there any way to fix the reading issue?
Thank you
Ajax (Asynchronous Javascript & XML) is a way to send data from client to the server asynchronously. For that you'd have to write code for sending the data in the client-side using Javascript/HTML and also to process the received data using server-side languages (eg PHP) on the server-side.
And, yes you don't need a <form> tag to do so.
Check out this example.
HTML:
<label>Text</label>
<textarea id="foo"></textarea>
<button id="submit">Submit via Ajax</button>
Javascript:
$('#submit').click(function(e) {
e.preventDefault();
// information to be sent to the server
var info = $('#foo').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {foo: info}
});
});
Server-side Handler (PHP): server.php
<?php
// information received from the client
$recievedInfo = $_POST['foo'];
// do something with this information
See this for your reference http://api.jquery.com/jquery.ajax/
Perhaps your reviewer was referring to the HTML5 textarea attribute "form". It allows a textarea to be part of a specified form without being inside the form element.
http://www.w3schools.com/tags/att_textarea_form.asp
But generally speaking, as long as you can identify an element, say a textarea, you can access the text inside it and send it to the server without submitting any forms using ajax.
From Sable's comment:
http://api.jquery.com/jquery.post
OR
http://api.jquery.com/jquery.ajax/
Yes, you can submit data to a server without putting it into a form. Form's provide a simpler mechanism for sending larger amounts of data to a server without the developer having to tell the browser how to encode the form.
EG:
HTML
JS
var text = $("input[type='text']").val();
$.post("/my/server/url", { userInput : text }, function(data){ /* Success! */});
This would technically post the data to the server without a form.