How do I send values between pages using javascript? - javascript

I am currently using a javascript code to make an entire row in my table clickable. Once the row is clicked a function is ran, I am wondering what I can use to redirect to a PHP page and preferably send a post variable along with it. My guess is AJAX but I am not sure how or if it would work.
Javascript
function DoNav(theUrl) {
document.location.href = theUrl;
};
HTML
<tr onclick="DoNav('myphpscript.php');">
I have access to jQuery so that is also an option. Any help is appreciated, Thanks!

If you need to POST the data (not use GET), One easy option is to create a form element on the fly, attach input elements with the values you need and submit it. You can do that like so if you use jQuery:
$(function() {
$('tr').click(function() {
var mail_id = /* get the mail id of this row... not sure where since I dont' have the HTML */
$('body').append('<form method="post" action="myphpscript.php" id="donavform" style="display:none;"></form>');
$('#donavform').append('<input type="hidden" name="mid" value="'+mail_id+'" />');
$('#donavform').submit();
});
});
Hope that makes sense. If not, let me know! It's, okay...
Explanation:
The very first line is a jQuery shortcut way of saying "when the document is done loading..." So, when the page is done loading, I'm going to attach an event listener to all elements in the document. When one of those elements is clicked, we can then extract the mail id (and whatever else you need) that is in relation to that particular table row. So, if you had HTML like this:
<!-- 8435 is the mail ID in this example. -->
<tr id="row3">8435</tr>
Then we could extract the mail_id variable like so:
var mail_id = $(this).html();
Now, we are going to attach a hidden form element to the end of the body of the HTML (it doesn't really matter where we put it since it is hidden... so, the end is fine). In this form element, we set the method to POST and the action to whatever php file you need to POST to. I also set an ID so it's easily referred to in the next step.
I'm now going to select the newly-created form element using its ID and I'm going to append a new hidden input element to it with the appropriate name value pair.
$('#donavform').append('<input type="hidden" name="mid" value="'+mail_id+'" />');
Finally, I'm going to use the jQuery JavaScript submit method to trigger the submit event on the form. This is basically equivalent to pressing the 'submit' button on a normal form.
Try it out, it should work flawlessly.

If you're going to a new page, just submit the form as usual. Put the data in form fields (hidden if required). No need to Ajax, jQuery or any other magic unless you want to stay on the same page and post in the background.

If the amount of data is not ridiculously large, use a query string...
<tr onclick="DoNav('myphpscript.php?key=value');">
Or if you need a natural HTTP post, you can programmatically submit the form with Javascript...
onclick="document.forms[0].submit();"

You could send the data along in a cookie. There's a nice jQuery plugin that helps with setting cookies in the jQuery namespace.
http://plugins.jquery.com/project/cookie

Related

Javascript, Ajax and form submission/response

I'm hoping there is a simple solution to this, or else its possible AJAX time!
I WAS using ClickBank. I had a simple button on my page. That sent the form data to a script, I processed the data, and then added a redirect at end of script to jump to the "pay" link. Nice n' easy
But now I'm switching to "Click2Sell" ... and they have a direct href to their site.
Now I COULD use javascript to read the form data, place it into their "cp_" prefix, and create a super long (about 400 chars) query string and send that to their server, then re-read the data at the IPN stage ...
?country=UK&area=essex&desc=This is the data entered by the user 'whatever'
(but that leads to a little fact that certain parts might need to be escaped(?) such as the spaces and the " ' " or whatever other symbol they enter)
So I devised this method:
<javascript>
function send_data(){
document.user.submit();
return true;
}
</javascript>
<div name="noshowdiv"><object name="noshow"></object></div>
<form method="post" target="noshow" name="user">
<input type="text" name="country">
<input type="text" name="area">
<textarea name="desc"></textarea>
</form>
<img src="xxx" onclick="return send_data();">
In a nutshell, when the button is clicked, it jumps to the function, and submits the form data to my script, and then returns to the hyperlink to submit the second form via the hyperlink.
Two problems: Firstly, the data returned by my script is opening in a new tab rather than the <div>, (I suspect 'cos the submit option loses track of the sending window) and also, I need to get a response from my script which I can then append to the href link.
For example, if the form records the user's data on line 5 on my server, the script will return "id=5" I would then make the hyperlink "click2sell.asp?cp_id=5"
As I've said, I suspect this is a job for Ajax and a HttpRequest ... which is a whole new area to me. Any advice?
For the first problem, it opens a new tab because you have target="no-show" on your form.
For the second problem, if you want to use Ajax, I recommend you use jQuery, it will simplify a lot of the code.
But the best option is probably that you completely remove the direct link to click2sell, and just add a submit button to your form. Post the form to your site, which will store whatever info it needs, assigns an ID, and builds the click2sell URL with the ID in one of the parameters, and redirect to it.
Now how you would do that depends on what server-side language you use.
(I think) I have managed to find a work around, which was using the first option to reconstruct the href link. I couldn't iterate through the form as there are values that don't need to be forwarded. First I get the value, load it into a variable, then use an encode function I discovered online, and then reassign to the form ...
var cp_cc=document.getElementById('cc').value;
var cp_cs=document.getElementById('cs').value; // plus 10 other values
var str='&cp_cc='+encodeURIComponent(cc)+'&cp_cs='+encodeURIComponent(cs)+ // etc
var send_str=document.getElementById('c2s_bn_lnk_36288').href;
document.getElementById('c2s_bn_lnk_36288').href=send_str+str;
The "no-show" was a slip up in my typing! Alas, the answer given above wouldn't work as the Click2sell button also includes two calls to external JS files - and they give you no idea what they do, but is something to do with initializing the button, (it passes the "36288" to the script to do ???). And whilst using "Location: ..\n\n" on my server would redirect to their site, it wouldn't action whatever those external files do. (OK, so I didn't give the full facts, but I didn't want to increase the post size with data I felt didn't relate to problem)
** Now got to amend the listening scripts such that rather than set the ID number up front then jump to C2S, it now waits for C2S to send the data back to me and then sets up the database!!

Store table data using localstorage and passing it to a form

Right now I am trying to use HTML5's localStorage API to grab a value from a table, and pass that value into a form.
For example, when a user clicks on "Sign Up Today" on this form: http://yft.ac/upcoming-workshops/, I want the information from the given row (Date, Time, Location), as well as the heading above it (ex: YFT Admissions Insights) to be stored, and then displayed in the field "Workshop Interested In" on this page: http://yft.ac/contact-us/.
I'm really not the best with JavaScript but here is what I have so far:
Contact Us:
$('input#workshop').text( localStorage.getItem('workshop') );
Upcoming Workshops Page:
$('body').on('click', 'a.button', function(){
var index = $(this).parents('table').index('table');
var cur_workshop = $(this).parents('.innercontent').find('h3').eq(index).text();
localStorage.setItem('workshop', cur_workshop);
});
I just tried to piece this together so the above code isn't working, but I hope that it is a good jump start for somebody that might be more well-versed in JavaScript.
You have few problems in the page.
Modernizer library is not included - you are using Modernizr.localstorage in your code
The localStorage.setItem('workshop', cur_workshop); code is added before jQuery library is added to the page - since this code used jQuery move it after inclusion of jQuery
Look like somewhere you/wordpress is calling jQuery.noConflict() - so $ does not refer jQuery anymore so use jQuery instead of $ in your code
Some quick thoughts. I believe your localStorage code should work....
But I think what might be happening is the browser is loading the contact page before you store the values in localStorage.
What you may want to do is remove the hyperlink and bind the click handler to a div, span or just a button element instead. In the click event handler use window.location = "xyz"; after you set the value to localStorage.
Again that may not be the real answer.. but try on a non hyperlink element and see. You can also do e.preventDefault; then store the value then do the window.location thing. That is sort of a progressive enhancement way to do it.
As for the localStorage I would encourage you to try to store the values in a JSON object instead of several items.
localStorage.setItem("workshop", JSON.stringify({'date' : '9/2/2012', 'time': '8:30AM', 'Princeton, NJ'}));
var workshop = JSON.parse(localStorage.getItem("workshop"));
hope this helps!

Datepicker initialization for class fields added after page load

I have fields where multiple extra fields can be added after the page loads (think education & work experience fields on job resumes). I am using this.
I can add a datepicker on the first field, but subsequent added fields do not access the datepicker, despite being cloned/essential duplicates of the original. I'm guessing that the datepicker only intializes on page load or for only one class on the page.
So on a page I initialize the datepicker:
$('.input-append.date').datepicker();
for a block of form code encapsulated by this class. OK for initial page load; and also OK if there is an error and the page reloads multiple fields previously input(there is a datepicker for all fields returned with any error). However, with another js function that adds new fields to the form, additional new fields do not have access to the datepicker. I do not see how to do this now, perhaps someone with more experience/wisdom can provide me a hint.
EDIT:
Simple enough: I simply added:
$('.input-append.date').datepicker();
to the code calling the new field. As to being the optimal solution I do not know, anyone who specializes in js can comment on that, and there are many other similar questions here I found once I expanded my search terms. However, good enough for me now in what I'm doing.
For elements which are being added on fly use data-provide="datepicker" attribute. It will be initialized lazily. For example if an input field is coming up in an ajax response and loaded in a container div. So in this case:
<input type="text" data-provide="datepicker" />
so when when you will load this ajax response it in cotainer div like
$('#container-div').html(ajax_response);
this will work.
In the same way if you are creating an element through jquery and appending it to some container (I think this is happening in your case), for example you have a function that creates textbox and append it to some container div and this function is called on click event of some element let's say it's button. Again data-provide attribute is the solution to this problem. For example
function createTextBox(){
var t = $('<input>').attr('data-provide','datepicker');
$('#container-div').append(t);
}
And this function is called on click event of some button like in this way:
$(document).ready(function(){
$('#someBtn).click(createTextBox);
});
In short whether that dynamic element is coming in ajax response as a string or being created through jquery, just use data-provide attribute to set bootstrap datepicker. Because in this case datepicker is initialized lazily in Bootstrap fashion.

Popup preview of textarea input

I want to create a preview function for posts that allows people to view the output of what they enter into a textarea how it would appear once submitted. The forum uses bbcode and does not allow html in posts and the id of the textarea box is "message"
Can anyone help me create a popup that would preview this post in a popup window without passing any of its data to a database and back?
I should really have supplied more info, I realise... Basically we have a post form in the form of
<textarea id=\"message\" name=\"message\" style=\"width:515; height:160; font-family: Verdana; font-size: 8pt; color: #000000\" onKeyDown=\"countit()\"></textarea>
with a submit button
<input type=\"image\" src=\"newlayout/images/reply.png\" height=\"35\" width=\"109\" border=\"0\" alt=\"Submit\">
When it's clicked, the form gets sent to another page, from where it's inserted into the database. I would like there to be a preview button like the one on livejournal, where a new popup gets created and shows what the post would look like. I looked at the source code on livejournal and it supplied jQuery, so I tried the code given here: http://haacked.com/archive/2009/12/15/live-preview-jquery-plugin.aspx
However, this did not work, as nothing showed up and also I wasn't fond of the live preview idea.
I also tried a javascript code from here: http://www.codingforums.com/showthread.php?t=174810, but once again, it didn't come up with anything...
I hope that's good info, if I should include anything else, please let me know :)
This question is getting close to "write my code for me", but if you're just trying to get help with the best approach, here are a few:
The cleanest would be have a button that (via javascript) changes the action and target of the form and triggers a submit()... this would send all the data via post to a template page which can pick up the $_POST data and place it into a template that mimics the live template.
Alternately, you could have JavaScript/Jquery grab all the field values, and build the HTML template in javascript and then pass this into div on the page that has been styles to look (a) like a pop-up and (b) has css that mimics the live page.
There are lots of ways to do this, but those would both work. If you try something and get into a tight spot, let us know and we'll give you a hand.
You would want to bind a keyup event to the textarea. Every time a user releases a key it would fire the function. Then your function grabs the value of the textarea and parses it for the BBCode, which I'm not familiar with. It then would take that output and place it as the contents of any element.
HTML:
<textarea id="myText"></textarea>
<div id="preview"></div>
JavaScript (jQuery):
$(document).ready(function() {
var $textarea = $('#myText'),
$preview = $('#preview');
$textarea.on('keyup', function() {
var $this = $(this),
output = $this.val();
// Do something with the value of the code to parse out the BBCode stuff.
$preview.html(output);
});
});
Why don't you try a WYSIWYG editor like TinyCME, or CKEditor?

JavaScript function calls within Django form fields

I'd like to create a form where I have checkboxes, and when clicked, they open separate textareas for the user to enter more information in.
If I want to use Django's dynamically created form fields, is there a way that I can put a function call in for each checkbox.
You can dynamically add event handlers using JavaScript. You can add a script that, once the page is loaded, will find all checkboxes you want and add the handlers there. In jQuery, you can write something like this:
$(document).ready(function() {
$(".my_form input[type=checkbox]").change(function() {
//Some code here
});
});
Be careful, I have not tested the code above! But should be enough to get you started.

Categories

Resources