Javascript, Ajax and form submission/response - javascript

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!!

Related

Javascript: Auto Submit Form based on Value? (with short delay)

I would like to auto-submit a form on my page after a short delay based on a variable value (which is present in the URL string, as well as declared by another JS script). Not sure what the best practice way to do this would be?
MY PAGE URL:
http://www.domain.com/mypageaddress?var_1=value1&var_2=value2&var_3=Returning%20Applicant&var_4=value4
So when var_3=Returning%20Applicant , the form should submit without user input (and I would love a 1-second delay built in before that auto submit). Another script on the page also declares a JS variable for that same condition that might be easier to work with than the query string - JS var/value pair returningapplicant=1 is the same as the URL string var_3=Returning%20Applicant that I'm trying to target. This is powered by a third party tool which I don't 100% understand, but they say that this JS variable can be referenced.
I would love some sample code that I could try for this function. Any help much appreciated and here's the extra info that will probably be needed for the JS script:
FORM ACTION URL
<form method="post" action="https://www.tfaforms.com/responses/processor" class="hintsSide labelsLeftAligned" id="tfa_0">
CURRENT FORM SUBMIT ELEMENT
<div class="actions" id="tfa_0-A"><input type="submit" class="primaryAction" value="Next"></div>
-in js
Wait for the window to load.
document.onload = function() {}
Evaluate the url with the condition/s you describe. /
If the condition/s are met submit the form after waiting one second.
if (window.location.href.match('var_3=Returning%20Applicant')) {
setTimeout(function() {
//submit form
document.forms["your-form"].submit();
},1000);
}
Are you doing anything if something doesn't pass the conditions?
Your asking a whole bunch of stuff at once but that's the gist of what you're looking to do. I'd probably parse the url params and evaluate them individually, validate the form, etc... if I were serious about this. Hopefully this can get you started. Good luck.

See the result of a form process submit button in adobe analytics

I have a form in a classic version with a submit button
<form action="" name="frm" mathed="">
<input type="submit" value="submit">
</input>
I have enabled a jquery command in order to track in adobe anlytics site that the submission of form was succesfull and have some values with this
$("#frm").submit(function(){
s.linkTrackVars="pageName";
s.pageName = 'test_form';
s.tl(true,'o','link', null,'navigate');
});
How can I confirm in omniture (adobe analytics) side that the submission was successful and se the results?
Firstly, you mention wanting to track that the form has been successfully submitted. I'm not sure how you define "successful" but commonly that means that the form passed validation (e.g. all form fields filled out, proper format, etc.). However, you currently have the Adobe Analytics (AA) tracking implemented to pop on the submit event, which may not necessarily mean the form has actually passed whatever validation you may have in place.
Secondly, the only AA variable you are setting is pageName, which is one of the few AA vars you should usually never set (override) on s.tl() calls. Generally speaking, pageName is set for a page view which is done with an s.t() call. Then, events/actions that happen on the page are tracked with an s.tl() call, and AA code already automatically includes the current page's pageName value in that request. Within the reports, AA then associates the activity with that page name, but disregards it as far as an actual page view happening.
Now, it may be that you want to track successful form submissions as a separate page view, in which case, you should indeed set pageName with a new (unique) value, but you don't need to "register" it in linkTrackVars and you should be using s.t() not s.tl() to trigger it. Ideally though, you should place it on a real "thank you" / "confirmation" page (though it may be that you don't actually have that).
So what should you pop then? If you go the "track it as a separate page view (s.t()) call with a unique pageName value, for your purposes that may be enough. You can look at your pages report and see your value show up and how many times a visitor hit it.
But in general, the more common method of form tracking involves at least one eVar and two events. This is the common basic form tracking setup.
I use the following AA var/events in this example
eVar1- This signifies a name for the form. Expiration should be set to expire on event2.
event1 - This signifies form view happened
event2 - This signifies successful form complete happened.
On form view
On form view, your on-page code should look something like this in principle:
<script src='s_code.js'></script>
<script>
s.pageName="unique page name"; // leave blank if you want AA to default to using URL in pages report
s.eVar1="unique descriptive form name here";
s.events="event1";
s.t();
</script>
On successful form submit
Ideally, you should have a "thank you" / confirmation page that the visitor is redirected to upon successful form completion, and on that page, you should have this in principle:
<script src='s_code.js'></script>
<script>
s.pageName="unique page name"; // leave blank if you want AA to default to using URL in pages report
s.events="event2";
s.t();
</script>
If you really want to do it your method (attaching to submit event), it'd look like this (p.s.- according to your posted code, your form doesn't have an id='frm' so the selector won't actually work, but I'm only addressing the actual AA code here):
$("#frm").submit(function(){
s.linkTrackEvents="event2";
s.linkTrackVars="events";
s.events="event2";
s.tl(true,'o','form submit');
});
Or, if you want to track it as a separate page view but triggered on submit (note: this will also record any other vars you already have set from initial page view, so you may need to do something about that (e.g. set different values for them too, or blank them out, etc..) depending on the intended purpose of any other vars you have):
$("#frm").submit(function(){
s.pageName="unique page name"; // leave blank if you want AA to default to using URL in pages report
s.events="event2";
s.t();
});
But as I mentioned above.. this may or may not accurately signify that a visitor actually successfully completed the form..
What report to look at
Okay so with the example above, you can then look at eVar1 report and select event1 and event2 as your metrics. This will show you how many people viewed and then went on to complete the form. If you have more than one form, you can use a different value in eVar1 and the report will show views/completes for each form.

post multiple forms on a single button press

My page conisits of x amount of forms. One for each database entry. The user can change the data and save the individual item back to the database.
But where I am stuck is with a SAVE ALL button. Can you post multiple forms?? I am pretty certain you cannot with php, so I'm looking at javascript to solve my problems. Specifically:
document.forms.submit();
All that is going on is happening on the same page (i.e. when a form is submitted it puts a value at the end of the URL (foo?delete=true), and there is php at the top of the page which does something like: if delete is true -> delete field... else carry on as normal
My brain is saying I should do something like: (where $size is a count of how many forms there are)
<p onclick="saveAll('.$size.')">saveall</p>
and the javascript function:
function saveAll(size) {
for(i=0;i<size;i++)
{
document.forms[i].submit();
alert(i); // for testing purposes
}
}
The result of this was that the page started to refresh, then a popup with "0" came up, then the page refeshed and nothing else happend.
Is what I need to do even possible? If so, hoooww?
Thanks
I see 2 ways to escape this situation:
Put all your fields to one form
Submit your forms using AJAX and after last form submition is complete go to next page if needed.
But are all forms in the same page???
If yes I think the only way out is the ways suggested by Konstantin Likhter.
Otherwsie place each form in an IFRAME, then place all these IFRAMEs in the same main page, then using your code from the main page you can submit all the forms at once.

Need sample JavaScript to query MySQL and display result upon combo box update

I have a combo box that will be loaded with a list of choices. When the user selects a choice, I need a JavaScript to simply run a query of MySql (obviously based on the user choice in the combo box) which will return a simple, discrete value that then needs to be displayed on the page next to the combo box.
The query is nothing more than SELECT foo FROM tblexample WHERE id = blah (where blah is the combo box value). The value will be a simple number. If the user chooses a new value, then it should just re-query and display the result.
I'm open to reading the whole table in upon page load into an array or something too. I work in PHP but I don't know Javascript; I was only hoping for a sample code bit; I can read and extrapolate most of the time.
I just didn't want to put a submit button in a form and force the user to do that each time they look at a new combo box choice. I wanted a more seamless, quick display for them.
JavaScript is a client-side language. It will not run MySQL queries (safely, at least). Use PHP to dynamically create the HTML and JavaScript for the combo box.
PHP has an entire section of their documentation reserved for MySQL.
I think you are actually looking for a reference in Ajax programming using PHP on the backend and javascript on the front end.
My recommendation would be to look at using one of the excellent Javascript development frameworks. Great candidates would be JQuery or Prototype. They both give you solid libraries to simplify programming in javascript.
Rather than working with sample code, you'll probably get a lot further by developing javascript expertise. Ajax is complicated, and you'll need to at least get basic skills together before you can start to integrate javascript and PHP.
Here's a good query to get started- I'd recommend beginning with JQuery if you have to pick one.
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=ajax+php+jquery+tutorial
Once you get started on jQuery as Tim mentioned you could do this,
The select box,
<form name="formName" action="" method="">
<select name="selName">
<option value={uniqueId}>Option 1</option>
</select>
</form>
<p class="displayMsg">No message to display.... yet</p>
The javascript and jQuery in a script tag of the head tag,
$(document).ready(function() {
$('select[name=selName]').change(function() {
function processData(data, success) {
...do something with the query results echoed into var data...such as
$('p.displayMsg').txt(data); // which will update the text node of the p tag class displayMsg
} // end function processData
var formData = $('form[name=formName]').serialize(); // this will encode the variables from the form to pass into post headers. You can access in your ajax called script with $_POST['selName']
$.post('phpAjaxProcessScript.php',formData,processDataClose); // sends data to script and when it's done it calls function processData
}); // end select change event function call
}); // end document ready event function call

How do I send values between pages using 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

Categories

Resources