I could see that this question was being asked a lot of times and I did extensive research on what methods could be used to transfer a couple of Javascript variables to a PHP script.
Post data in a form as hidden values
Post to URL, i.e. '/txt.php?h=' + var
Use a cookie
I'm trying write a piece of code that will let you download what you've written in Wrrrite.com - I'm the developer of this website. (I also did a client-side approach of putting the variables into the URI and setting a header to download stuff)
None of this is working. Either there's a character that's causing an error, or there are html elements.
Is there something I can code to guarantee a 1:1 transfer of the work/variables?
Datatype: HTML + various different Characters "!§!' etc.
Output: .txt File, perferably a 1:1 translation of what was being written on the form
You should maybe use a Base64 encoding of your data, before sending it. Have a look at MDN for the JavaScript part and here for the PHP decoding. This should prevent special characters from breaking your code.
Hope it helps
//PHP
if(isset($_REQUST['submit']))
{
$download=$_REQUEST['download'];
// from database get value of all the downloadable items
// and check if the input is in that array then to the suitable thing.
}
//HTML
<form method="post" action=''>
Type :<input type="text" id="txtField" name="txtField" />
<input type="hidden" name='download' />
<input type="submit" name="submit" onclick="return onSubmit() " />
</form>
//Javascript
<script type="text/javascript">
function onSubmit()
{
if(document.getElementById("txtField").value != '')
{
document.getElementById("download").value=document.getElementById("txtField").value;
return true;
}
else
{
alert("Please enter item to download");
return false;
}
}
Here's the Cookie Approach, which doesn't work http://pastebin.com/SKNtxLi5
That just slaps values together without any consideration for the data format used in cookies.
Quirks Mode has a decent guide to cookies with JS if you want to fix that.
However… the point of cookies is that the data persists. It isn't a sensible transform for one shot messages.
Related
I have a HTML form in list.php that submits the data from text box ("item" in below code) to check.php. This check.php validates the text entered to be not empty or white spaces only. After validation, it redirects to list.php for the entered text to be displayed. list.php is below. I want the "add" button to be enabled only when valid text is entered in the text box. I would like this feature to be done with php and probably not with javascript.
I can use "disabled=\"disabled\" in the form, but this does not work in real-time disabling depending on validation.
<form action="check.php" method="post">
<input name="item" type="text" size="25" autofocus="autofocus" />
<input type="submit" value="Add" id="add" />
</form>
You say:
I would like this feature to be done with php and probably not with javascript.
Unfortunately, if you want "real-time" then you're gonna need JavaScript. You'll need it to make AJAX calls to your PHP code to check for validation.
So either A) you don't validate in "real-time" at all, or B) You use JavaScript in one shape or another.
Let's say you opt for B), to use JavaScript, and presuming ALL you need to do is check for an empty string or whitespace, then you can do all of this client-side in JavaScript and not require a server call at all, also making it truly "real-time".
And so, here is my solution, using JavaScript (jQuery) without relying on server calls. This may not be suitable for your current implementation, but just in case it is, this might be helpful.
JSFiddle:
http://jsfiddle.net/VKfrw/1/
JavaScript:
function hasWhiteSpaceOrEmpty(s)
{
return s == "" || s.indexOf(' ') >= 0;
}
function validateInput()
{
var inputVal = $("#myInput").val();
if(hasWhiteSpaceOrEmpty(inputVal))
{
//This has whitespace or is empty, disable the button
$("#add").attr("disabled", "disabled");
}
else
{
//not empty or whitespace
$("#add").removeAttr("disabled");
}
}
$(document).ready(function() {
$("#myInput").keyup(validateInput);
});
HTML:
<!-- give this guy an ID -->
<input id="myInput" name="item" type="text" size="25" autofocus="autofocus" />
This implementation uses jQuery.
As mentioned, if you want this done in real time some javascript will be needed.
However I think this problem is actually more suited to javascript in general. PHP validation can be useful if you need to cross reference for data with data in your database.
eg. In a sign up form, checking a user is not already registered with the entered email address.
But in your case, depending on what you mean by "valid text" it is probably easier and better to use javascript.
There are some great jQuery plugins which make javascript validation really simple.
http://docs.jquery.com/Plugins/Validation/validate
Since I am a complete n00b in every aspect when it comes down to JS, JQuery and PHP, I will be needing some help.
Probably it's really simple for someone with basic knowledge of JS, but it ain't that simple for me.
I have the following part in my index.php:
<form method="get" id="searchform" action="http://wwwapps.ups.com/WebTracking/track?HTMLVersion=5.0&loc=nl_NL&Requester=UPSHome&WBPM_lid=homepage%2Fct1.html_pnl_trk" target="_blank" >
<input type="text" value="" name="trackNums" id="ups" />
<input type="hidden" name="track.x" value="Traceren">
<input type="hidden" name="loc" value="nl_NL">
<input type="image" src="afbeeldingen/search_btn.png" id="searchsubmit" />
</form>
In the .js file I have this:
$(document).ready(function() {
$("#ups").attr("value", "UPS Trackingscode...");
var text = "UPS Trackingscode...";
$("#ups").focus(function() {
$(this).addClass("active");
if($(this).attr("value") == text) $(this).attr("value", "");
});
$("#ups").blur(function() {
$(this).removeClass("active");
if($(this).attr("value") == "") $(this).attr("value", text);
});
});
I added this (at the top of) the .js file:
function removeSpaces(string) {
return string.split(' ').join('');
}
But when I add this part to the index.php (form-section) it doesn't work:
<input type="text" onblur="this.value=removeSpaces(this.value);">
I guess I have to incorporate it to the current JS as well, but I have no clue how to do this or what to change / add.
What I am trying to achieve here, is that whenever I paste a trackingcode into the text field, it should automatically remove the spaces (if there are any, because a bad copy/paste action).
It's not for any special website, but just for my personal use, so I can track packages more easily from my own starting page.
I hope I explained it correctly. Probably it takes less than a minute for someone with basic JS skills, but for me it's very difficult. :(
The function itself is working well. It's solely a scoping issue. You have two options:
1) You move your function outside the $(document).ready(function() { }) part
2) You remove the onblur="this.value=removeSpaces(this.value);" from your element, discard your function and write an according event-handler
// identifier or class needed to target the element, i use id="target"
$("#target").on("focusout",function(){
this.value = this.value.replace(/\s*/g,"");
});
The second way (using event handlers) is considered the cleaner and better way. But valid are both.
Sidenotes:
to remove spaces from your string, it's better to use the replace method with an according regular expression /\s*/g (replace zero or more whitespaces \s* in your entire string (globally g) ).
Instead of $(this).attr("value") use $(this).val().
My question is should I convert two html pages to php pages, so the called page can access its POSTed parameters, or is there a way for a called html (.html extension) page to access posted parameters?
I've been reading that because posted parameters are server-side there is no way for JavaScript to do this being client side. I've seen nothing about one html page accessing
parameters if that .html page was accessed via a POST.
Here is my calling form. The called form, needs access to TransDesc (below), which is a text field.
<script type="text/javascript" language="JavaScript1.2">
// Check where we came from so that we can go to the right spot when the
// form gets posted from outside of our HTML tree.
var PostURL = '/event.html';
</script>
Enter a Donation Amount
<script type="text/javascript" language="JavaScript1.2">
document.write(
'<form name="InvGenPayDonation"
action="'+PostURL+'"
onsubmit="return validateForm();"
method=POST>');
</script>
<p> $ <input type='text' name='Amount' value="0.00">
</p>
<p>In honor of <span style="color: #FF0000">
<input type='text' name='TransDesc' id='TransDesc' value="" >
</p>
<input type="submit" value="Next"> <br /><br />
A static HTML file cannot access variables that have been POST'ed to it. It can't even know they're there as they're sent to the server in the HTTP request, the server then deals with them and sends the HTML page in the HTTP response. They're 'consumed' before the page is even sent to the client.
You could use GET and access them via JavaScript, or configure Apache to server .html files as PHP files instead though.
In my opinion, php is the easiest way to go, and as far as languages go is pretty easy to learn and pretty intuitive.
You'll have to either convert them to PHP or use GET instead of POST, as GET parameters are accessible through window.location.href
Yes, I would recommend converting the pages to php. If you are set on using HTML files you will have to edit your htaccess file to run HTML pages as php.
You can always use ajax to retrieve and send post and get values.
You can retrieve it with js by creating a php file and access those with ajax from your html files.
I'm newbie in PHP.I want to know that,I taking data by html form and a .php file.
like:
<form id="form1" name="form1" method="post" action="show.php">
<strong>Please Enter the Unique id</strong><br/><br/>
Unique id:
<!-- name of this text field is "tel" -->
<input name="id" type="text" id="id" />
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>
</html>
Then,I used show.php file to get the 'id'.like:
$id=$_POST['id'];
Is there any way to take input by php code???
Update:
In "C" we take ant input by this way
scanf("%d",a);
is there any way to do so in PHP.I think now all you may be clear what I'm trying to say??
Thanks
Yasir Adnan.
What you are you trying to get is wrong!
HTML:- It is the communicator between the user and the browser. It displays the contents according to the user input or html code.It gets data from user or from html code.
Php :- It is the communicator between server and the browser. It has the capability of collecting from some where else other than the code like mysql data base and then uses html to display the content!
Here you are asking php to do html work which is not correct!!
the html
<input name="sb_id" type="text" id="sb_id" />
php
$id=$_POST['sb_id'];
Well, you do take the input by your php code. Your variable $id took the value of $_POST['id'] which contains the input of the textfield.
After this step you can work with the variable like any other
$id = $_POST["sb_id"]; ?
Remember that $_POST["field_name"] where field_name must be match the name attribute of your <input /> tag.
the id attribute of input tag is not sent to server inside the $_POST array. It`s typically used in client-side.
You can get data in your PHP code through GET and POST parameters. Those parameters are part of the HTTP request.
The GET parameters are in the url :
http://mywebsite.com/id=3&name=test
Then you get them using:
$id = $_GET['id'];
$name = $_GET['name'];
So you can get input data through this way when people visit the URL, call it in AJAX, or call the URL in another application (like a webservice). But no matter how it's called, it's the same for you on the PHP side.
The POST parameters are in the HTTP request, you can't pass them through the URL. You can do that by using an HTML form, or by creating the HTTP request yourself. If you are using Javascript to call your PHP code (and pass data to it), you can use AJAX to do that for example. You, in your PHP code, can get the variables this way:
$id = $_POST['id'];
$name = $_POST['name'];
If you want console-style I/O, you should probably check JavaScript/AJAX. The second one will allow you to write your own wrapper that will help you to process the input by your server "on air".
The problem is, you still need to use $_POST for AJAX. And, which is more important, it's easier (and cheaper for the server) to validate and process input by JS (and to validate and process it further on the server-side after submit).
And if the question is "how can I get the variable from the needed format?", the answer is: try using regexps/parsing the string.
Oh, btw: there IS scanf() in php, and it's called 'sscanf' ('fscanf' for files).
I want to create a login script on HTML page. I read that I need to use an intermediate script so that I can let my HTML use the database. So, I`ve written a PHP page that checks the username/password regarding the database.
I also read that I should use AJAX to connect to the database.
I would like to know how to write the AJAX code to return the value of the login either true or false.
You should really at-least try Google before posting here.
Google Search: ajax login code
This is a very simple implementation but can be a starting point.
http://woork.blogspot.com/2007/10/login-using-ajax-and-php.html
You may need to read up on ajax a little if this doesn't make sence:
http://code.google.com/edu/ajax/tutorials/ajax-tutorial.html
AJAX is really nothing more than JavaScript which connects to a server-side resource (such as a PHP-backed page), receives a result, and likely does some UI manipulation of the HTML as a response to that result. A good place to get started is the jQuery ajax method. Using the jQuery JavaScript library will make the process much simpler. But, ultimately, it'll connect to your PHP code on the server to perform the actual database interaction.
Beyond that, it sounds like you're lacking a good bit of design oversight in this project. The statement "I also read that I should use AJAX to connect to the database." is particularly troubling. Where did you read that? Why did you read that? There seems to be little value in that suggestion beyond someone somewhere thinking that "AJAX is cool and people should use it for stuff."
Is there a specific design concern for using AJAX vs. just posting a form to some PHP code?
Although it's not necessary to use AJAX for this, you can use something like below.
Considering you have an element that has a username and password like below:
<div id="login">
<label for="txtUsername">Username:</label>
<input type="text" id="txtUsername" />
<label for="txtPassword">Password:</label>
<input type="password" id="txtPassword" />
<button id="btnLogin">Log In</buton>
</div>
<div id="logout" style="display: none;">
Log Out
</div>
Then, having jQuery already referenced call your PHP page ("login.php" in the example):
<script type="text/javascript">
$(function() {
$("#btnLogin").click(function() {
$.ajax({
url: "login.php",
data: {username: $("#txtUsername").val(), password: $("#txtPassword").val()},
success: function(data){
$("#login").toggle();
$("#logout").toggle();
}
});
});
});
</script>
If I understand your question correctly, there are two ways you could handle this. The first (and most common) way is to just set the PHP script as the action of your HTML form:
<form method="post" action="folder/phpfile.php">
<input type="text" name="username" />
<input type="password" name="password" />
</form>
After doing this, make sure your PHP script takes in the post variables as $_POST['input_name'], where input_name is the name you used in the inputs on your HTML form (as 'username' and 'password' are used above).
Using AJAX for authentication is not always the best way to handle things in my opinion, but it is doable. I would recommend you try using JQuery behind your JavaScript if you are going to go the AJAX route. They have a really handy framework for handling AJAX queries and events.