Solved

How to manipulate values from an HTML form to make a call to a JSON service

Posted on 2008-10-15
15
379 Views
Last Modified: 2012-05-05
I am more comfortable in SQL. But I really need to understand how to program in JavaScript.
So as much as I need a solution to this issue, I will really value the thinking behind the solution, as I fear the solution is trivial, I am not seeing how to approach the problem.

I have a form (name="myForm")
It has 5 fields: (firstName,lastName,phone,zip,email)
The form will come back to the same page on submit.
I already have validated the form on submit, but after the validation, I want to take these values and craft a string (entryString) that looks like this:
(entryString = ?f=firstName?l=lastName?z=zip?p=phone?e=email)
and then make a call to a url  to look like this:
<script type="text/JavaScript" src="http://service.mysite.com/mycontest/entryString/json"></script>
really like this:
<script type="text/JavaScript" src="http://service.mysite.com/mycontest/?f=firstName?l=lastName?z=zip?p=phone?e=email/json"></script>.  

I did not create the JSON service, so I am not sure why they used the question marks as delimiters. But that is what I have to do.

Thanks in advance.

<html>
	<head>
		<script language="JavaScript" src="gen_validatorv31.js" type="text/javascript"></script>
		<script language="JavaScript" src="json.js" type="text/javascript"></script>
 
</head>
<body>
<script language="javascript" src="gen_validatorv31.js"></script>
<div style="BACKGROUND: #451516; TEXT-ALIGN: center"><span><img height="615" alt="Hershey's Presents Brad Paisley - the Paisley Party Tour 2008" src="http://media.mysite.com/images/BradPaisley.jpg" width="660" /></span>
<div style="BACKGROUND: #451516; COLOR: #fdd49e; TEXT-ALIGN: center">
<div class="break-higher">&nbsp;</div>
Register today<br />10 winners -- pair of lawn tickets to the concert<br />10/18/08 7:30 PM <br />Winners will be called by 2pm on Thursday and can pick up tickets Thursday afternoon or anytime on Friday.<br /><div class="break-higher">&nbsp;</div></div>
<div style="BACKGROUND: #f7ce9a; COLOR: #451516">
<table cellspacing="0" cellpadding="2" width="251" align="center" border="0" class="text">
    <form action="#" method="post" name="contestForm" onsubmit="<script type='text/JavaScript' src='http://service.mysite.com/bradpaisleycontest/?f=Joe?l=Blow?z=90210?p=5554442411?e=jblow@mysite.com/json'></script>">
        <tbody>
        	<tr><td colspan="2">&nbsp;</td></tr>
            <tr>
                <td colspan="2">
                <div style="BACKGROUND: #451516; COLOR: #fdd49e">
                <div style="PADDING-RIGHT: 3px; PADDING-LEFT: 3px; FONT-SIZE: 15px; PADDING-BOTTOM: 3px; PADDING-TOP: 3px; FONT-FAMILY: Trebuchet MS, Arial, sans-serif; text-align:center">
                	Enter here to win tickets
                	</div>
                </div>
                </td>
            </tr>
            <tr>
                <td class="formcaption" width="116">
                <p align="left"><strong>First Name:</strong></p>
                </td>
                <td width="127">
                <p align="left"><input class="formelement" name="firstName" /></p>
                </td>
            </tr>
            <tr>
                <td class="formcaption">
                <p align="left"><strong>Last Name:</strong></p>
                </td>
                <td>
                <p align="left"><input class="formelement" name="lastName" /></p>
                </td>
            </tr>
            <tr>
                <td class="formcaption">
                <p align="left"><strong>Zip:</strong></p>
                </td>
                <td>
                <p align="left"><input class="formelement" size="5" name="zip" /></p>
                </td>
            </tr>
            <tr>
                <td class="formcaption">
                <p align="left"><strong>Phone:</strong></p>
                </td>
                <td>
                <p align="left"><input class="formelement" size="12" name="phone" /></p>
                </td>
            </tr>
            <tr>
                <td class="formcaption">
                <p align="left"><strong>E-mail:</strong></p>
                </td>
                <td>
                <p align="left"><input class="formelement" name="email" /></p>
                </td>
            </tr>
            <tr>
                <td><input type="hidden" name="ContestName" value="bradpaisley" /> <input type="hidden" name="AGE" value="n/a" /><input type="hidden" checked="checked" name="mailinglist" value="Yes" /> </td>
                <td><input class="formbutton" type="submit" name="submit" value="Enter Me!" /></td>
            </tr>
        </tbody>
    </form>
</table>
<div class="break-higher">&nbsp;</div>
<div align="center">Please see <a href="/brad_paisley_rules.html">complete rules</a> for details.</div>
<div class="break-higher">&nbsp;</div>
</div>
<div style="BACKGROUND: #451516; TEXT-ALIGN: center">&nbsp;</div>
</div>
    <script language="JavaScript" type="text/javascript">
  
 var frmvalidator = new Validator("contestForm");
 
 frmvalidator.EnableMsgsTogether();
 
 frmvalidator.addValidation("firstName","req","Please enter your first name");
 frmvalidator.addValidation("firstName","maxlen=20","Max length for FirstName is 20");
 frmvalidator.addValidation("firstName","alpha");
 
 frmvalidator.addValidation("lastName","req","Please enter your last name");
 frmvalidator.addValidation("lastName","maxlen=20");
 
 frmvalidator.addValidation("zip","maxlen=5");
 frmvalidator.addValidation("zip","req","Please enter your zip code");
 frmvalidator.addValidation("zip","numeric");
 
 frmvalidator.addValidation("phone","maxlen=50");
 frmvalidator.addValidation("phone","req","Please enter your phone number");
 frmvalidator.addValidation("phone","numeric");
 
 frmvalidator.addValidation("email","maxlen=50");
 frmvalidator.addValidation("email","req","Please enter your e-mail address");
 frmvalidator.addValidation("email","email");
 
</script>
</body>
</html>

Open in new window

0
Comment
Question by:MakeITRight
  • 8
  • 4
  • 3
15 Comments
 
LVL 29

Expert Comment

by:Badotz
ID: 22722835
Since you do the work on the server (with the submit) why not build the special URL and then Response.Redirect to it?
0
 
LVL 2

Accepted Solution

by:
tree33 earned 500 total points
ID: 22723044
Are looking for a way to build up the URL string on the cilent.
Does this work for you?
 var f = document.forms[0];
 var callURL = '?f=' + f.firstName.value + '?l=' + f.lastName.value

Open in new window

0
 

Author Comment

by:MakeITRight
ID: 22723200
So if you were to comment this for a complete noob, would it look like this?
var f = document.forms[0]; // create a variable called f (which is an array?)
//and make it equal/contain the values from the form in the document
//What does the [0] do?
 var callURL = '?f=' + f.firstName.value + '?l=' + f.lastName.value // create a variable called callURL
// and concantinate some string with each of the aray items (called by name)


0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 2

Expert Comment

by:tree33
ID: 22723556
Yes, It would look like this.
document.forms is an array of all <form> elements on the page.
The forms[0] points to the first <form> element of the document. You could also use document.forms.contestForm is your case.
0
 

Author Comment

by:MakeITRight
ID: 22723853
So it looks like I could create the whole url string like this:
 var f = document.forms[0];
 var callURL = 'http://service.mysite.com/mycontest/entryString/json?f=' + f.firstName.value + '?l=' + f.lastName.value'?z=' + f.zip.value'?p=' + f.phone.value'?e=' + f.email.value+"/json/"

If so then How exactly do I place that in the onsubmit=???
I assume it would be callURL but it would need to be in a script tag and it would need to be after the above code. Is this assumption correct?
Thanks again and in advance.
0
 
LVL 29

Expert Comment

by:Badotz
ID: 22723917
That is why I suggested doing it on the server and then using Response.Redirect to actually go to the URL.

var callURL = 'http://service.mysite.com/mycontest/entryString/json?f=' + f.firstName.value + '?l=' + f.lastName.value'?z=' + f.zip.value'?p=' + f.phone.value'?e=' + f.email.value+"/json/"

Response.Redirect callURL;
0
 
LVL 2

Expert Comment

by:tree33
ID: 22723968
The onsubmit is just an event which is fired before the form is submitted.
When you define a function in the onsubmit which returns false, then the form will not be submitted.
The submission of the data inside the form happens in the action property of the form. You can set that using forms[0].action.
You can try this:
forms[0].action = callURL.
Another way would be to call that URL in a hidden frame or an iframe using myframe.location.href = callURL.
You might also consider to use the XMLHttpRequest object to do a asynchronous call to that WebService.
0
 

Author Comment

by:MakeITRight
ID: 22724036
Badotz,
I appreciate the idea. It is just that I can not do this on the server. I am narrowly tasked with doing this from the client side. Also, I need to understand how to craft the JavaScript for furure needs.

tree33,
These are excelent contributions for me. As I want to explore how each will work.
Sense I am posting back to this page, I am hoping to use the json response to show a previously hidden div that acknowledges the success of the form submission and invites the user to move on.
0
 
LVL 29

Expert Comment

by:Badotz
ID: 22724066
OK. Just trying to skin that cat ;-)
0
 

Author Comment

by:MakeITRight
ID: 22725141
Ok, So I am tryng the XMLHttpRequest method. After the form validation code I have added this code (below)

But what happens is that I get an error that says that says:
"Error: 'f.firstName.value' is null or not an object."
I get the error on page load so I think I need to fire it on submit. But sadly I do not know how to do that.
 var f = document.forms.contestForm[0];
 var callURL = 'http://service.mysite.com/mycontest/entryString/json?f=' + f.firstName.value + '?l=' + f.lastName.value+'?z=' + f.zip.value+'?p=' + f.phone.value+'?e=' + f.email.value+'/json/';
 
 var http = new XMLHttpRequest();
 var params = "";
 http.open("POST", callURL, false); // set to false here to troubleshoot the success of the call to json.
 
 //Send the proper header information along with the request
 http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 http.setRequestHeader("Content-length", params.length);
 http.setRequestHeader("Connection", "close");
 
 http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
	}
 }
 //http.send(params); // No params being sent for this form

Open in new window

0
 
LVL 2

Expert Comment

by:tree33
ID: 22725883
You're using a wrong pointer for var f.
Either use:
var f = document.forms[0];
or
var f = document.forms.contestForm;
Please be aware that the XMLHttpRequest is not working the same way in every browser, but there are many solutions availlable wich wraps the XMLHttp functionality to make it work in in different browsers. http://www.ilinsky.com/articles/XMLHttpRequest/
0
 

Author Comment

by:MakeITRight
ID: 22725983
Thanks for catching that error.
0
 

Author Comment

by:MakeITRight
ID: 22726159
Sorry to be lame, but this is not working. I realized that I would not try the XMLHttpRequest until I saw it work with the other methods.
I put this in the code: alert(callURL);
To see what was being created and sent. The forms values seem to be empty.

I know it fires on load and is empty but once the form is filled out, then it is still empty
<html>
	<head>
		<script language="JavaScript" src="gen_validatorv31.js" type="text/javascript"></script>
		<script language="JavaScript" src="json.js" type="text/javascript"></script>
 
</head>
<body>
<script language="javascript" src="gen_validatorv31.js"></script>
<div style="BACKGROUND: #451516; TEXT-ALIGN: center"><span><img height="615" alt="Hershey's Presents Brad Paisley - the Paisley Party Tour 2008" src="http://media.mysite.com/images/BradPaisley.jpg" width="660" /></span>
<div style="BACKGROUND: #451516; COLOR: #fdd49e; TEXT-ALIGN: center">
<div class="break-higher">&nbsp;</div>
Register today<br />10 winners -- pair of lawn tickets to the concert<br />10/18/08 7:30 PM  <br />Winners will be called by 2pm on Thursday and can pick up tickets Thursday afternoon or anytime on Friday.<br /><div class="break-higher">&nbsp;</div></div>
<div style="BACKGROUND: #f7ce9a; COLOR: #451516">
<table cellspacing="0" cellpadding="2" width="251" align="center" border="0" class="text">
    <form action="#" method="post" name="contestForm" >
        <tbody>
        	<tr><td colspan="2">&nbsp;</td></tr>
            <tr>
                <td colspan="2">
                <div style="BACKGROUND: #451516; COLOR: #fdd49e">
                <div style="PADDING-RIGHT: 3px; PADDING-LEFT: 3px; FONT-SIZE: 15px; PADDING-BOTTOM: 3px; PADDING-TOP: 3px; FONT-FAMILY: Trebuchet MS, Arial, sans-serif; text-align:center">
                	Enter here to win tickets
                	</div>
                </div>
                </td>
            </tr>
            <tr>
                <td class="formcaption" width="116">
                <p align="left"><strong>First Name:</strong></p>
                </td>
                <td width="127">
                <p align="left"><input class="formelement" name="firstName" /></p>
                </td>
            </tr>
            <tr>
                <td class="formcaption">
                <p align="left"><strong>Last Name:</strong></p>
                </td>
                <td>
                <p align="left"><input class="formelement" name="lastName" /></p>
                </td>
            </tr>
            <tr>
                <td class="formcaption">
                <p align="left"><strong>Zip:</strong></p>
                </td>
                <td>
                <p align="left"><input class="formelement" size="5" name="zip" /></p>
                </td>
            </tr>
            <tr>
                <td class="formcaption">
                <p align="left"><strong>Phone:</strong></p>
                </td>
                <td>
                <p align="left"><input class="formelement" size="12" name="phone" /></p>
                </td>
            </tr>
            <tr>
                <td class="formcaption">
                <p align="left"><strong>E-mail:</strong></p>
                </td>
                <td>
                <p align="left"><input class="formelement" name="email" /></p>
                </td>
            </tr>
            <tr>
                <td><input type="hidden" name="contestName" value="bradpaisley" /> <input type="hidden" name="age" value="n/a" /><input type="hidden" checked="checked" name="mailingList" value="Yes" /> </td>
                <td><input class="formbutton" type="submit" name="submit" value="Enter Me!" /></td>
            </tr>
        </tbody>
    </form>
</table>
<div class="break-higher">&nbsp;</div>
<div align="center">Please see <a href="/brad_paisley_rules.html">complete rules</a> for details.</div>
<div class="break-higher">&nbsp;</div>
</div>
<div style="BACKGROUND: #451516; TEXT-ALIGN: center">&nbsp;</div>
</div>
    <script language="JavaScript" type="text/javascript">
 document.forms.onsubmit = callURL;	
  
 var frmvalidator = new Validator("contestForm");
 
 frmvalidator.EnableMsgsTogether();
 
 frmvalidator.addValidation("firstName","req","Please enter your first name");
 frmvalidator.addValidation("firstName","maxlen=20","Max length for FirstName is 20");
 frmvalidator.addValidation("firstName","alpha");
 
 frmvalidator.addValidation("lastName","req","Please enter your last name");
 frmvalidator.addValidation("lastName","maxlen=20");
 
 frmvalidator.addValidation("zip","maxlen=5");
 frmvalidator.addValidation("zip","req","Please enter your zip code");
 frmvalidator.addValidation("zip","numeric");
 
 frmvalidator.addValidation("phone","maxlen=50");
 frmvalidator.addValidation("phone","req","Please enter your phone number");
 frmvalidator.addValidation("phone","numeric");
 
 frmvalidator.addValidation("email","maxlen=50");
 frmvalidator.addValidation("email","req","Please enter your e-mail address");
 frmvalidator.addValidation("email","email");
 
/*
//Commented out until I can wrap the XMLHtmlRequest for cross browser use
 function sendXMLHtmlRequest()
 {
var f = document.forms.contestForm;
 
 var callURL =  'http://service.mysite.com/bradPaisleyContest/?f=' + f.firstName.value + '?l=' + f.lastName.value+'?z=' + f.zip.value+'?p=' + f.phone.value+'?e=' + f.email.value+'/json';
alert(callURL);
 var http = new XMLHttpRequest();
 //var params = "";
 http.open("POST", callURL, false);
 
 //Send the proper header information along with the request
 http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 http.setRequestHeader("Content-length", params.length);
 http.setRequestHeader("Connection", "close");
 
 http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
	}
 }
 //http.send(params); // No params being sent for this form
 
}
*/
var f = document.forms[0];
 
var callURL =  'http://service.mysite.com/bradPaisleyContest/?f=' + f.firstName.value + '?l=' + f.lastName.value+'?z=' + f.zip.value+'?p=' + f.phone.value+'?e=' + f.email.value+'/json';
alert(callURL);
 
//forms[0].action = callURL;
</script>
 
 
 
</body>
</html>

Open in new window

0
 

Author Comment

by:MakeITRight
ID: 22734774
Actually it does work. But it is never visable from this page because once the onsubmit happens it comes back to this page and the form is clear.
0
 

Author Closing Comment

by:MakeITRight
ID: 31506351
Thank you for your help and guidance on this.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Lazy load not working with masonry js 1 18
AdminLTE with wordpress 15 54
Outlook opens HTML email as text 4 22
how can i get the string decoded ? 2 8
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question