Post variable on hyperlink - javascript

I have a drop down list in my php page that is hyperlinked to different pages contained on different servers; html, asp.net pages etc.
The URL of these pages do not contain the same domain name as the drop down list. Therefore, in order to prevent the user from directly entering the URL in the address bar, I would like to post a variable when the user clicks an item in the list.
This variable will be sent along the hyperlinked URL. The asp.net page will check whether the variable is received along with the request, if yes the page will load otherwise the asp.net page will redirect the user to my home page.
My question: What is the process of posting a variable? Where in the hyperlink does this variable need to be included. I am totally lost.
EDIT: I tried to post through form.submit
<li><form id="sampleForm" name="sampleForm" method="post">
<input type="hidden" name="total" id="total" value="">
<a onclick="setValue();">ELMSTest</a>
</form></li>
<script type="text/javascript">
function setValue(){
document.sampleForm.total.value = 100;
document.forms["sampleForm"].submit();
}
</script>
I dont know how to proceed from here.

Try this as you are using the POST action. Which you are by virtue of having `method="post" on your tag.
`<form id="sampleForm" name="sampleForm" method="post">`
Because you have no action="script.php" it will send your inputs to the script that generated this page and run it again. So assuming this is called script.php...
In the PHP code of script.php the data will be delivered to you in the $_POST array.
<?php
if ( isset($_POST['total'] && $_POST['total'] == 1 ) {
// I have a foo variable with the value of one. So do something with it.
}
If you want to use the get action or add variables to a hyperlink as:
www.domain.net/script.php?foo=1&bar=2
The ? starts the list of variables, the querystring and each variable is seperated by an & if you want to pass more than one.
And of course the variables are passed in the $_GET array to your PHP code.
<?php
if ( isset($_GET['foo'] && $_GET['foo'] == 1 ) {
// I have a foo variable with the value of one. So do something with it.
}
if ( isset($_GET['bar'] && $_GET['bar'] == 2 ) {
// I have a bar variable with the value of two. So do something with it.
}

Related

How to call set value through ajax response from inline script in html?

I set value of my input type hidden in ajax response and then I wanna display my page with set content.
Ajax :
var JSONObject = JSON.parse(data);
$("#hiddenSearchedTextValue").val(JSONObject[1]);
window.location = JSONObject[0]; // redirect on my page
on My page, where I wanna display my set value:
<script>
var value = "";
window.onload = function () {
$ = jQuery;
value = $("#hiddenSearchedTextValue").val();
}
</script>
<div class="container">
<h1> Searched for: <script>document.write(value)</script></h1>
</div>
<input type="hidden" id="hiddenSearchedTextValue" value="">
Now it returns nothing. Anyone have some advice for me, please? I tried to read something about global scope, but nothing helped. Thank you
Unless I'm misunderstanding from your code snippets you are getting a response from Ajax and then redirecting the page? If this is the case then you loose your value when the page is re-loaded i.e. once you have your response.
I think you need to pass the value as a parameter in your url, then set it on page load
I think you want to just update the value and then reset the input, something like (in PHP):
value = $("#hiddenSearchedTextValue").val();
.....
....
<input type="hidden" id="hiddenSearchedTextValue" value="' . $_GET['searchString'] . '">
(with some appropriate security checking etc). Although you might as well just do this in the h1 tag. Maybe seeing some more of your code and your Ajax would make it easier to understand how you think it should work

How to retrieve data from database using jQuery and information in a form from a previous page?

So I am trying to get a user's first name so that I can display it on my chatting app. I have the user's information. I can get the user by playing around with res.render(). In jade I can do something like #{user.firstName} to have it printed out but I am not sure how I can use this data in jQuery.
Check if you can build an element as follwed:
case 1
<input id='user-first_name' type='hidden' value='#{user.firstName}' />
// Then you can use the value of input field as.
var firstName = $('#user-first_name').val()
case 2
you can directly write a script tag where you will initialize some window variables as :
<script>
window.user_first_name = #{user.firstName}
</script>
case 3
Also you can try assigning that value to data field of any html element(html tag) as followed :
<element data-first_name='#{user.firstName}'>
// Now you can use a jquery selector for selecting that element and you
// will be able to retrieve that value using data function
var firstName = $(element_selector).data('first_name');

Saving information on HTML page without using variables

So I'm trying to create a webpage where the user puts in there course information. There is an add button on the page, that adds another text field for them if they need more fields.
Once the Add button is pressed, the page is reset and all of the information that has been previously entered is gone. I could save the information in an array, and when or if the the add button is pressed save the information into an array, and re populate the fields using what was stored in the array.
My question is: Is there a way to refresh a page, and keep the information in the text fields, without taking the long process mention above, is there some attribute that I can use that will not delete information that has been previously entered into ?
If you code HTML5, you can use localStorage with a fallback to cookies. Also, if the information should be removed after session end, then you may use sessionStorage instead.
You can use ajax i think...it runs in background no page reload is done.
Assuming this HTML:
<form id="course-info-form" action="submit-course-info.php" method="post">
Professor name: <input type="text" name="professor"><br>
Additional info:<br>
<input type="text" name="additional0"><br>
<input type="submit" value="Submit">
</form>
<br>
<button id="add-button">Add Field</button>
<!-- Use jQuery for DOM manipulation -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
With JavaScript / jQuery:
var courseInfoForm = $('#course-info-form');
var addButton = $('#add-button');
// Keep track of how many fields there are, so each can have a unique "name" attribute
var additionalFieldsAdded = 1;
// Whenever "Add Field" is clicked, create another input field
addButton.on('click', function() {
var newInput = $("<input>", {
type: "text"
name: "additional" + additionalFieldsAdded
});
courseInfoForm.append(newInput, "<br>");
additionalFieldsAdded += 1;
});
I'm not very good at PHP. In your PHP script, make a while loop that checks to see if isset($_POST['additional0']), and additional1, additional2, etc, until you are sure that there were no more additional fields passed. Then store all those additional details into an array, and handle it how you see fit.
As for your original question, I recommend using my solution instead. It's better to avoid unnecessarily reloading the page, if all you're doing is simply adding a new form each time.
I suppose you could capture the information that was "tentatively-submitted" when the "Add Field" button is clicked, and then in your PHP script loop through all the additional fields and create 1 more input element each time another field is added, and set the value attribute of each "old" input element to whatever was "tentatively-submitted."
So, to answer your question, you can set the default value of an input field (server-side) with:
// add-course-information.php
<?php
$addingField = false;
// Check for the optional "?do=addfield" parameter
if (isset($_POST['do']) && $_POST['do'] == 'addfield') {
$addingField = true;
$fields = array();
$nextField = 'additional' . count($fields);
// Get each piece of POSTed field data
while (isset($_POST[$nextField]) && $_POST[$nextField] != '') {
array_push($fields, $_POST[$nextField]);
$nextField = 'additional' . count($fields);
}
}
?>
<!-- Silly HTML! -->
<?php
// If adding a field, recreate and repopulate all previous fields
if ($addingField) {
for ($i = 0; i < count($fields); i++) { ?>
<input type="text" name="additional<?= $i ?>" value="<?= $fields[$i] ?>">
<?php } ?>
<input type="text" name="additional<?php echo count($fields) + 1 ?>">
<?php }
// Otherwise, show the default additional field
else { ?>
<input type="text" name="additional0">
<?php } ?>
<!-- More awesome HTML! -->
That might work... (Currently untested.)
What that page is supposed to do (if it works) is:
On default, give the user his initial setup, with just 1 additional input field, "additional0".
When the user clicks "Add Field," ?do=addfield should be POSTed to add-course-information.php (you can write that part), and when this page receives the do=addfield parameter, then it knows to loop through all the submitted additional fields, and store them each into an array, and then afterwards output all the submitted data back into another loop's-worth of dynamically generated <input> elements.
But I think that that would be much more complicated, and unnecessarily increase the processing your server has to do. It could even be abused if someone was to hammer the "Add Field" button hundreds of thousands of times a minute, eventually making your for-loops iterate millions of times... (Unless you imposed a limit on the maximum number of fields, which would be easy.)
However, you might as well leverage the client's processing power if it's available.

Passing value between pages. What am I doing wrong?

I have 2 pages, one called details.page and the other, maps.page
In the first page, I have a declared a search input like so :
<form method="get" id="form-search" data-ajax="true" action="maps.page">
<input type="search" name="search" id="search" value=""/>
</form>
And in my second page, maps.page, I have one declared like so :
<form action="maps.page">
<input type="search" name="search" id="search-field" value=""/>
</form>
Now, I was assuming that when I type something in the search bar from my first page and hit enter, the search bar on maps.page would be populated with the value previously entered.
I am correctly redirected, but the search bar is empty.
What am I doing wrong ?
Thanks in advance for your help.
EDIT : Also, I see in the URL that it seems to be working, because I can see what I searched in the URL like this : /maps.page?search=something
You have a few option in how to do this without using a back end script.
1) You can set the form method to GET so that the variables are passed in the address bar, then grab them on the other side using a script like the one below (this actually reads the address and then parses it for variables). After that, you can put that value in your input field.
var getVars = new Array();
var locvartemp = ( window.location.href.indexOf( "?" ) + 1 ) ? window.location.href.substr( window.location.href.indexOf( "?" ) + 1 ) : "";
locvartemp = locvartemp.split( "&" );
for( var x = 0; x < locvartemp.length; x++ ) {
var lvTempVar = locvartemp[x].split( "=" );
getVars[ unescape( lvTempVar[0] ) ] = unescape( lvTempVar[1] );
}
2) You can use the jQuery cookie plugin to set the value as a cookie prior to submitting the form and then read it on the other side and set it to your input field.
jQuery.cookie("myCookie", document.formName.myFieldName.value);
Let me know if you need more details.
The value is not automatically filled. You need to print it from the server side.
<form action="maps.page">
<input type="search" name="search" id="search-field" value="<insert value>"/>
</form>
I was assuming that when I type something in the search bar from my first page and hit enter, the search bar on maps.page would be populated with the value previously entered.
That is what you are doing wrong.
The field will only be populated if you set the value attribute (or set the DOM value property after the element has been added to the DOM).
This is generally done using a server side process. The specifics depend on the language you are using to create that process, but do watch out for XSS as including unfiltered, unescaped user input will create a security hole.

JQTouch: passing data between 'views'

Hi I have been playing around with jqtouch today and I'm just wondering how to manage data.
I tried looking around but couldn't see much documentation.
If I had a list of links for say products? And I click on one i can navigate to the product 'view'. How to I pass variables like you would a $_GET variable to select THAT product?
Or even if I set the id of the link to the id of the record and use JS to grab the ID and somehow pass it to the next view?
Any help with this would be most appreciated!
NOTE: I also want to use it with the offline extension so I'm not sure get ajax would work
Regards,
Billy
You can use the referrer property for the data object. The link would look like:
Product #1
where the HTML ID would correspond to the product ID. Then in the "pageAnimationEnd" event you can retrieve the product details like this:
$('#view').bind('pageAnimationEnd', function (e, info) {
// get the id of the calling href
var id = $(this).data('referrer')[0].id;
$.getJSON('/products/' + id, function (data) {
// do something with the data
});
});
You could look at the demo to see how it does form submission, i.e. AJAX > POST Form Example. Essentially, you create a form and a jQT-style submit button:
<form id="ajax_demo" action="ajax_demo.php" method="POST" class="form">
...
<a class="submit whiteButton" href="#">Submit</a>
</form>
Then in your receiving page (i.e. ajax_demo.php), you can access the form fields, e.g. PHP's $_GET or JavaScript's location.search.
Another way is to store the data in the DOM with jQuery:
// in global level
$('body').data('ajax_demo', "some data for the page");
// in page/view level
$('#ajax_demo').data('key', 'value');

Categories