Solved

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

Posted on 2008-10-15
15
375 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 2

Expert Comment

by:tree33
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:MakeITRight
Comment Utility
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
Comment Utility
OK. Just trying to skin that cat ;-)
0
 

Author Comment

by:MakeITRight
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks for catching that error.
0
 

Author Comment

by:MakeITRight
Comment Utility
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
Comment Utility
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
Comment Utility
Thank you for your help and guidance on this.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
In this tutorial viewers will learn how to define a gradient in CSS. Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Gradient. Define the background as "linear-gradient(to right, #ee3668, black)". Ensure you …
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…

743 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now