Process section of input URL - javascript

Simple question really, but I'm probably missing a really simple point.
I have an input form, that a user will paste a URL in to be navigated to the next section.
Say the user enters in: https://www.facebook.com/connect/login_success.html#access_token=XXXXXXXXXYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZAAAAAAAAAAAAAAAAAABBBBBBBBBBBB&expires_in=0
I want the form to only process the: XXXXXXXXXYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZAAAAAAAAAAAAAAAAAABBBBBBBBBBBB
So it will completely ignore:
https://www.facebook.com/connect/login_success.html#access_token=
and
&expires_in=0
Is this possible at all?
My form is incredibly simple:
<form action="home.php" method="GET">
<div class="form-group">
<label for="exampleInputEmail1">Access Token.</label>
<input type="text" class="form-control" id="exampleInputEmail1" name="accesstoken"/>
</div>
<button type="submit" class="btn btn-default btn-block">Confirm</button>
</form>
"Bootstrap"
Thanks!

You could do an explode(http://nl3.php.net/explode) on the ampersand('&') and paste it together in a string or variable.

Change your form to use POST, like this:
<form action="home.php" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">Access Token.</label>
<input type="text" class="form-control" id="exampleInputEmail1" name="accesstoken"/>
</div>
<button type="submit" class="btn btn-default btn-block">Confirm</button>
</form>
Then, you can retrieve your variable in PHP, like this:
<?php $accesstoken = $_GET['accesstoken']; ?>
which can easily be echo'ed into a JavaScript variable for your use.

At first, I suggest you to parse it on server side, not client side (JavaScript can be turned off etc.). If you need to have accesstoken as GET parameter on home.php, you can redirect user here after submit. Anyway, on server side, try it with parse_url:
$urlParts = parse_url($_POST['accesstoken']); // Now you have all URL parts in array
$urlQuery = $urlParts['query']; // Now you have only query part
$queryParts = explode('&', $urlQuery); // Separate them
foreach ($queryParts as $query)
{
$singleQueryPart = explode('=', $query); // Separate key from value
if ($singleQueryPart[0] == 'access_token') // If the key is same as we are looking for...
{
$token = $singleQueryPart[1]; // ...assign value and break loop
break;
}
}
echo $token;
NOTE 1: I assume that your URL in first post has type (# instead of ?). If not, just use same script as I post, but change $urlParts['query'] to $urlParts['fragment'].
NOTE 2: If you really want to/need to use JavaScript, look at php.js implementation of parse_url.
NOTE 3: Another nice JS library to handle URL operations seems to be URI.js.

I found a much simpler solution to my issue:
<script>
$(document).ready(function() {
$('#btnSubmit').click(function(e) {
var val = document.getElementById('exampleInputEmail1').value;
$('#exampleInputEmail1').val(val.substring(val.indexOf("=") + 1, val.indexOf('&')));
});
});
</script>

Related

Auto Submit form just once

I have configured the javascript code to do auto submit but what I want is that if the authentication fails, I do not do the autosubmit again.
My code is the following:
Form:
<?php echo form_open($this->uri->uri_string(), array('class' => 'login-form')); ?>
<div class="form-group">
<label for="email"><?php echo _l('clients_login_email'); ?></label>
<input type="text" autofocus="true" class="form-control" name="email" id="email">
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<label for="password"><?php echo _l('clients_login_password'); ?></label>
<input type="password" class="form-control" name="password" id="password">
<?php echo form_error('password'); ?>
</div>
<?php echo form_close(); ?>
Javascript
<script type="text/javascript">
window.onload=function(){
var auto = setTimeout(function(){ autoRefresh(); }, 100);
function submitform(){
document.forms["login-form"].submit();
}
function autoRefresh(){
clearTimeout(auto);
auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);
}
}
</script>
How can I do it?
I believe your problem lies in array('class' => 'login-form').
Looking at the documentation for document.forms, you access the forms with ID.
I am not familiar with code-igniter; however, your code tells me that you are probably setting the class for a form. You would need to set the id for a form.
For preventing the auto-submit from running twice. From what I see, I suspect that you are getting a normal HTML form at the end. When you submit a HTML form it would make a trip to the server and when it comes back it should reload the page (unless you make it an asynchronous form).
Since the page is reloading, the window.onload would be run every time. To prevent this you would have to use a true-false flag some wheres.
Here are some potential solutions:
You could try looking into accessing url parameters from JavaScript. Some quick searching shows that this is a lot more complex than I'd expect though...
Alternatively, you could move the JavaScript code into a <script> block and echo out a script block from PHP. If you are going with this option you should look into using addEventListener method instead of accessing onload directly. PHP would make it much easier to accessing URL parameters by using $_GET or $_POST.
A second alternative would be to echo out a <input type="hidden"> that holds the true/false value and then access the value using JavaScript.
Once you can use your flag, you just need to check the flag in order to decide whether or not to auto-submit or not.
if (myFlag){
//submit form
}else{
//don't submit form
}
This true-false value is not sensitive data so it should be safe to place it as a GET parameter.

call a javascript function after a submitted form data is written to DB

My question maybe looks awkward. But I strongly need the answer. Assume a form submit like:
<input name="button2" type="submit" class="test" id="button2" value="submit"
onclick="checkSubmitStatus();"/>
When the checkSubmitStatus function is called, the form is not submitted yet, so the form data is not arrived in database in server side yet. How can I make them execute in vice-versa? I mean firstly, the form submits and its data is inserted to the server database and then call that javascript function.
I think you want to give to user some feedback about if data was inserted successfully or not, right?
if so, I recomend you to follow different way. Eg.:
Your markup:
<form id="frm-post" method="post">
<input name="foo" value="bar" type="text" />
<button type="button" id="btn-submit">Submit</button>
Your Code:
$("#btn-submit").click(function(){
var objData = {
type : 'post' ,
url : 'your url' ,
data : $('#frm-post').serialize(),
dataType : 'text' ,
success : function ( dataReceived ) {
alert(dataReceived)
}
}
$.ajax(objData);
});
Considering the page you'll call will return just the message you want to show to the user.
I've not tested the code, but I think it will put you in the right way.

Two Buttons with different action on same php page

I have a PHP page with two Buttons named as Save and Submit.One for Saving form Data and other for submiting the final data.
<button id="save" name="save" onclick="saveForm();">Save</button>
<button id="submit" name="submit" onclick="validate();">Submit</button>
here are the two JavaScript functions:
function saveForm() {
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php";
document.submission.submit();
}
function validate() {
// some validation code here
// after validation the rest will work
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php";
document.submission.submit();
}
In 'SubmissionCheck.php' page I have defined two separate actions for save and submit button, but I am facing the same process of submit button when I click the save button. How do I solve this? Any one help please. Thank you in advance.
<button id="save" value="save" name="method" onclick="saveForm();">Save</button>
<button id="submit" value="submit" name="method" onclick="validate();">Submit</button>
PHP
if(isset($_POST["method"])){
if($_POST["method"] == "save"){
echo "Saving File";
}elseif($_POST["method"] == "submit"){
echo "Submitting File";
}
}
When you are doing what you are trying to do I tend to keep my name's the same. So that I can test against them. I generally use names such as action, method, mode,and data which I can then test the values. Another good practice I do, is just var_dump then entire $_POST
example
var_dump($_POST);
var_dump($_GET);
var_dump($_REQUEST);
By performing these test conditions you can have more control over your code without getting overwhelmed by names. Another thing I like to do is use these for page actions, these action,mode,method help me generate the exact page the user is looking for.
example
<input type="text" value="" name="method" placeholder="Insert a method">
<input type="text" value="" name="action" placeholder="Insert a action">
<input type="text" value="" name="mode" placeholder="Insert a mode">
Then when submitted I can use these like so
$path = "";
if(isset($_POST["method"])){
path.="method=".$_POST["method"];
if(isset($_POST["action"])){
path.="&action=".$_POST["action"];
if(isset($_POST["mode"])){
path.="&mode=".$_POST["mode"];
}
}
header("Location: /path/".$path);
}
This will output three ways... if only method, if method and action, and if method,action,and mode. So generally speaking, testing against universal names sometimes is better. Hope this little walk down PHP $_POST usage helps you a little bit.
note I never sanitized any of the $_POST values, but if you are using them as a path you really should, or if you are access mySQL database use mysqli_real_escape_string and other sanitation methods.
Also is your forms default action being prevented, because since you have no values, $_POST will be empty every time. Unless it's prevented then submitted correctly.
<form onsubmit="return false">
//buttons
</form>
you can differentiate in actions like this
function saveForm() {
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php";
document.submission.submit();
}
function validate() {
--some validation code here---
--after validation the rest will work--
document.submission.method = "POST";
document.submission.action = "SubmissionCheck.php?validate";
document.submission.submit();
}
then in SubmissionCheck.php file check
if(isset($_GET['validate']))
{
// perform actions for validation
}
check isset:
if (isset($_POST["save"]))
{
echo "save action";
}
if (isset($_POST["submit"]))
{
echo "submit action";
}

Get Input Value on the same page with PHP?

Well, first i'm new in PHP. Is there a way to get the input value from a existing input on the page on page load with php and pass it to a variable?
For example i have this input: <input type="text" name="g_id_p" id="example1" value"foo">
I want to do something like this: $got_it = $_GET['g_id_p'];
Sorry again if i wrote my code wrong, im noobie on this. Hope to someone help me.
First, would be great to know what method is the form. (GET or POST)
Then after know what type of method you could call it in PHP:
METHOD POST:
<input type="text" name="g_id_p" id="example1" value"foo">
$variable = $_POST['g_id_p'];
METHOD GET:
<input type="text" name="g_id_p" id="example1" value"foo">
$variable = $_GET['g_id_p'];
If you haven't defined a method, in html the tag for a form is:
<form>
<!-- Here goes your input and some stuff -->
</form>
Then it would be something like:
<form name="form_name" class="form_class" id="form_id" method="TheFormMethod" action="ThePageThatExecutesThisForm">
<!-- Here goes your input and some stuff -->
</form>
TheFormMethod can be post, get, delete, put.
You can't really get an associated value of an input tag within the same PHP page but what you can do is set the value of a variable beforehand.
What I mean is, create an array that will store all the values of all the input tags.
$inputValues = array();
$inputValues['g_id_p'] = 'foo';
Then when you have the tag later on just echo it from the PHP var.
<input type="text" name="g_id_p" id="example1" value="<?php echo $inputValues['g_id_p']; ?>">
As you can see, we aren't really 'getting' the value that you set but the end result is the same.
You have to check if the values is set isset(), where you want to use the variable do:
if(isset($_GET['g_id_p'])){
//your code
}

submitting a form with link

I have following form structure
<form action="{Basket-Addproduct}" method="post" id="items-form">
<button class="button-text button-gray-custom" type="submit" value="Submit" name="{dynamically generated name}"><span>Submit</span></button>
</form>
here "dynamically generated name" is the key field which tells which element or product to submit..
I want it to convert it into link,
I have tried following
Add This
Its getting submitted but not able to add the product...
Its expecting the name parameter also to be passed so it knows which product to add...
Stuck....:(
Any solution appreciated...
you should have <input type="submit".
There is no need to do JavaScript.
Just remove JS and then have as many <input type="submit" buttons as you want.
The GET/POST should have the key/value you look for.
E.g.
<input type="submit" name="item1" value="submit" />
when you click it, the recipient receives (sorry PHP used here):
$_GET['item1'] = submit
and other submits do not have value.
You can use jQuery to do this clean and easy.
So, here's your link:
<a id="form-submit-btn" href="#" name="{dynamically generated name}">Add This</a>
And your form:
<form action="{Basket-Addproduct}" method="post" id="items-form">
<!-- form contents -->
</form>
Now write a JavaScript which submits your form data on a button click:
$('#form-submit-btn').click(function(e) {
e.preventDefault();
var $form = $('#items-form');
$.post($form.attr('action'), $form.serialize(), function(data){
// do something with the data
});
});
Your code should work, I have created an example for you to test, here it is: http://jsfiddle.net/afzaal_ahmad_zeeshan/yFWzE/
<form id="form">
<input type="text" name="something" id="something" />
</form>
Submit
By using this you will submit the form using the id of it. And other user told you to use jQuery, which I am afraid you don't want to. In jQuery you use .preventDefault but if you want to stick to the simple JS then you will be using href="#" which will automatically prevent any anchor tag execution.
And the result of the request can be checked, which sadly is an error. But it makes sure that the request has been sent to the server.
Then you can test the methods and other type of executions by having some if else blocks as
if(condition == true) {
// if post
} else {
// if get
}
The parameter might be mis handled on the server side, because when the form is submitted you need to take out the data from the QueryString (the request is GET). So, you need to check that, or if that's not the issue then make sure you're pointing the element well. Otherwise if there is no such element, nothing will be sent.
I am not sure, which language you're using but here is the code for ASP.NET
var value = Request.QueryString["something"];
PHP version is already present above. That all depends on the parameters you send with the request. You are more likely to convert the code to a function. Such as
Submit
And the function
function submit() {
// create variable
var value = document.getElementById("something").value;\
// now submit the form and all that other bla bla, which
// you want to be process,
}
If you find this one tricky, using jQuery as
var values = $('form').serialize();
will be easy. This will create a string of the form and will send it with the request.

Categories