How to send a POST method without refreshing/submitting the page - javascript

I am trying to update a specific field in the database, namely "assigned" from the Phone model.
I tried to make a function(setBooleanForCurrentPhone()) in javascript that would change the value of id="assignPhone" from "true" to "false" at the onchange in select.
The problem is that the "assigned" is not changed in database, because I am not submitting anything yet.
Also, I tried to make a button, just to test it, that would call the setBooleanForCurrentPhone() function onclick, but the problem is that
this is submitting the data, the page jumps to another one and I don't get to use the last submit button which calls setBooleanForPhone().
Basically, I want to find a way update that value from dataBase without refreshing/changing the page.
<tr>
<td>Employee id:</td>
<td><input type = "text" th:field="*{id}" readonly="readonly" ></td>
</tr>
<tr>
<td>Employee last name:</td>
<td><input type = "text" th:field="*{lastName}" ></td>
</tr>
<tr>
<td>Employee first name:</td>
<td><input type = "text" th:field="*{firstName}" ></td>
</tr>
<tr>
<td>Phone:</td>
<td style="display: none"><input type="text" id="destination" th:field="*{phone}"></td>
<td style="display: none"><input type="text" id="assignPhone" th:field="*{phone.assigned}"></td>
<td>
<select id="source" onchange="copyTextValue(), setBooleanForCurrentPhone()" th:field="${possiblePhones}" >
<option th:value="${employee.phone?.id}" th:text="${employee.phone != null ? employee.phone.brand +' '+ employee.phone.model : 'no phone'}">select phone</option>
<option th:each="possiblePhone : ${possiblePhones}" th:value="${possiblePhone.id}" th:text="${possiblePhone.brand +' '+ possiblePhone.model} "></option>
</select>
</td>
</tr>
<!--submit button-->
<tr>
<td colspan="2">
<button onclick="setBooleanForPhone()" type="submit">Save</button>
</td>
</tr>
</table>
I have found something on the internet but I am pretty sure that I am not doing it right:
function setBooleanForCurrentPhone() {
var n = 'false';
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("assignPhone").innerHTML = this.responseText;
}
};
http.open("POST","employee/edit/{id}",true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(n);
}

You can use Ajax to achieve this. Ajax stands for Asynchronous JavaScript and XML. It will allow you to submit forms without refreshing the page. If you are using jQuery then you can do that using$ajax else if you are using JavaScript then it will be available using XMLhttprequest.

Related

How to retrieve references from group Checkbox name arrays using JS or jQuery

I have a hard JS/jQuery riddle ! Hard because I couldn't find it on Google nor here, neither now, nor months ago when I was looking for it previously.
A large framework is using checkboxes in a table:
<table class="ListTable">
<tr>
<td><input name="blnChecked[70_20]" type="checkbox" value="1" id="some_unusable_gobbledy_gook" /></td>
<td></td>...
</tr>
<tr>
<td><input name="blnChecked[71_20]" type="checkbox" value="1" id="some_more_unusable_gobbledy_gook" /></td>
<td></td>...
</tr>
<tr>
<td><input name="blnChecked[70_25]" type="checkbox" value="1" id="some_further_unusable_gobbledy_gook" /></td>
<td></td>...
</tr>
</table>
I now need to collect all checkbox name references into an array: 70_20, 71_20 and 70_25 in the above example. Then join them up, and submit them as a URL parameter to a different page (although this joining is not essential to my question).
Question: Using JS/jQuery on the same page, how do I get these references from the name strings in these (checked) checkboxes in an array ?
I prefer not to use regexes (a bit messy, or 'overkill' for such a seeming trivial matter imho), although such a solution is not off my table.
(If someone asks why the table is structured as such: This is not my doing. But I can see that when such a form, in which this table is submitted to a PHP page, the PHP stores all such checkboxes into a single array, which is very nice, and I wanted to achieve a similar effect with JS/jQuery.)
A way to create on client side the array is based on using:
.map()
string .replace()
$('#btn').on('click', function(e) {
var retVal = $('table.ListTable :checkbox[name^="blnChecked["]:checked').map(function(idx, ele) {
//
// if the name value has always the same format...
//
return ele.name.replace('blnChecked[', '').replace(']', '');
//
// or....
//
// return ele.name.split('[').pop().replace(']', '');
// return ele.name.substr(11, 5);
//return ele.name.replace(/blnChecked\[(.*?)\]/g, '$1')
}).get();
var param = $.param({'param': retVal.join(',')});
console.log('Array: ' + retVal);
console.log('URL param: ' + param);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="ListTable">
<tr>
<td><input name="blnChecked[7125_2355]" type="checkbox" value="1" id="some_unusable_gobbledy_gook" /></td>
<td></td>
</tr>
<tr>
<td><input name="blnChecked[71_20]" type="checkbox" value="1" id="some_more_unusable_gobbledy_gook" /></td>
<td></td>
</tr>
<tr>
<td><input name="blnChecked[70_25]" type="checkbox" value="1" id="some_further_unusable_gobbledy_gook" /></td>
<td></td>
</tr>
</table>
<button type="button" id="btn">Click Me</button>

I'm trying to create an html form to generate an url address based on input to a field

I am trying to create a small HTML document for my team to use to create fake devices for testing purposes in our program. We currently have a link to do this with but we have to manually change parts of it in the URL field before hitting enter to process it. I came up with the idea of creating this form so we can make sure that we are filling in all the elements of the URL correctly and then copy and paste the created URL into the browser. There are static parts of the address that we don't change and then there are values we update after the '=' sign. There are 4 different environments that we can use this in.
I admit it has been a while since I last worked in HTML so I've been trying to search forums and sites like W3School to find the segments of code that I think will serve the purpose I'm aiming for. The following code is where I have gotten so far but can't get it to work the way I've intended it to. If anyone can provide suggestions or feedback on what I missed or did wrong I'd appreciate it. Thank you!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Item birth generator</title>
<script>
function mySubmit() {
var addStart;
var addPart1 = "part1=";
var addPart2 = "&part2=";
var addPart3 = "&part3=";
var addPart4 = "&part4=";
var addPart5 = "&part5=";
var addPart6 = "&part6=";
var addPart7 = "&part7=";
var addPart8 = "&part8=";
var myChoice = "choice";
if (myChoice.value == "choice1")
{addStart="https://address1?";}
else if (myChoice.value == "choice2")
{addStart="https://address2?";}
else if (myChoice.value == "choice3")
{addStart="https://address3?";}
else (myChoice.value == "choice4")
{addStart="https://address4?";}
var address = addStart.concat(addPart1, "mInput1", addPart2, "mInput2", addPart3, "mInput3", addPart4, "mInput4", addPart5, "mInput5", addPart6, "mInput6", addPart7, "mInput7", addPart8, "mInput8");
document.getElementById("demo").innerHTML = address;
}
</script>
</head>
<body>
<font> <H3>Please fill in the appropriate fields and then click Generate to create a url for an item in the chosen environment.</H3></font>
<form target="_self" id="demo" name="item" method="post" onSubmit="return checkValue();">
<input type="radio" name="choice" id="ch1" value="choice1" checked> Choice 1 <input type="radio" name ="choice" id="ch2" value="choice2"> Choice 2 <input type="radio" name="choice" id="ch3" value="choice3"> Choice 3 <input type="radio" name ="choice" id="ch4" value="choice4"> Choice 4
<br><br>
<table>
<tbody>
<tr>
<td>Item Part 1</td>
<td><input type="text" name="mInput1" maxlength="13"></td>
</tr>
<tr>
<td>Item Part 2</td>
<td><input type="text" name="mInput2"></td>
</tr>
<tr>
<td>Item Part 3</td>
<td><input type="text" name="mInput3"></td>
</tr>
<tr>
<td>Item Part 4</td>
<td><input type="text" name="mInput4"></td>
<tr>
<td>Item Part 5</td>
<td><input type="text" name="mInput5"></td>
</tr>
<tr>
<td>Item Part 6</td>
<td><input type="text" name="mInput6"></td>
</tr>
<tr>
<td>Item Part 7</td>
<td><input type="text" name="mInput7"></td>
</tr>
<tr>
<td>Item Part 8</td>
<td><input type="text" name="mInput8"></td>
</tr>
<tr>
</tr>
<tr>
<td><input type="submit" value="Generate" onclick="mySubmit()"></td>
</tr>
</tbody>
</table>
<br>
<input type="text" size="250" name="address" value=''>
</form>
</body>
</html>
There is an error with this line:
var s.address = s.addStart.concat(addPart1, mInput1, addPart2, mInput2, addPart3, mInput3, addPart4, mInput4, addPart5, mInput5, addPart6, mInput6, addPart7, mInput7, addPart8, mInput8);
Verify what you are using is valid by testing the variables (output with a console.log or an alert) and check the command syntax. :)

Hiding placeholder Div, then using same code on another page giving javascript error

I have code that is generated by passing data from an ajax call to an ActionView method in my controller. I can only access that data when the ajax call returns. The area where I am trying to display my data is not getting refreshed so I added it to my PartialView to return back to the page div I created. My issue is that I have a placeholder of exactly the same small table so that the page does not look goofy before the user submits what they need to to call the ajax request. My issue is that the button I have in the placeholder area and area that I have displaying back are not working correctly. I think what is happening is that the javascript is getting confused by the two areas having the same information, but changing the names/ids doesn't seem to fix it. Here is my code. (I also need the placeholder table to be functional before it is hidden)
This is in the main page:
<tr>
<td>Comments: #Html.TextBox("comments2", comment)</td>
<td></td>
</tr>
<tr>
<td style="vertical-align: middle;">Booking#:#Html.TextBox("bookNum2", bookNum)</td>
<td><input id="saveOrder2" type="button" value="Save Order2" onclick="saveOrder2(true)" /></td>
</tr>
<tr>
<td style="vertical-align: middle;">Ship Date:#Html.TextBox("shipDate2", shipDate)</td>
<td>
<input id="Build" type="button" value="Build Load" /> </td>
</tr>
</table>
In the PartialView page I have this:
<tr>
<td>Comments: #Html.TextBox("comments", comment)</td>
<td></td>
</tr>
<tr>
<td style="vertical-align: middle;">Booking#:#Html.TextBox("bookNum", bookNum)</td>
<td><input id="saveOrder" type="button" value="Save Order" onclick="saveOrder(true)" /></td>
</tr>
<tr>
<td style="vertical-align: middle;">Ship Date:#Html.TextBox("shipDate", shipDate)</td>
<td>
<input id="Build" type="button" value="Build Load" /></td>
</tr>
</table>
Then the javascript function I am using:
function saveOrder(isSave)
{
var comments = document.getElementById("comments2").value;
var bookNum = document.getElementById("bookNum2").value;
var shipDate = document.getElementById("shipDate2").value;
var itemList = grabSaveItems();
//alert(itemList.toString());
var request = $.ajax(
{
type: "POST",
url: "/Home/saveOrder",
data: "itemList=" + itemList+"&isSave="+isSave+"&comments="+comments+"&bookNum="+bookNum+"&shipDate="+shipDate,
success: function (itemList) {
}
});
request.done(function () {
if (isSave == true)
{
alert("The Order Was Saved");
}
});
request.fail(function (Check, textStatus) { alert("Request failed: " + textStatus); });
}
So based on the order number I add the information I need to the Model and then return my PartialView to display what I need.
When I click Save Order after this ajax call is made I get the following runtime error:
Microsoft JScript runtime error: Member not found. Which occurs just after the call to save Order, the debugger points to the line just after this function, not sure what that means. Any help would be appreciated.
Ok, I knew it was something dumb. It looks like Javascript gets freaky when you assign the id of the input the same name as your function so it doesn't know what to do/call.
<td><input id="**saveOrder"** type="button" value="Save Order" onclick="**saveOrder**(true)"/></td>

Issue using Ajax's Post Method to Send Multiple Values

My goal is to submit an entire form through an ajax function which will then send those values to a php file. I'm using Post for several reasons - one being that I will be changing data within a MySQL database.
I've seen a few examples while I was searching for an answer, but none of them seem to have addressed the issue I'm having directly.
For instance, this example:
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
// 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");
// Call a function when the state changes.
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
starts to address it.
To be specific, I am not sure how to go about sending multiple values. In the example I found above, I see that they hard coded two values into their statement in the variable params. I'm wanting to know how to pass those values to the function without having to hard code them.
My form:
<table border="0" cellpadding="2" cellspacing="5">
<th colspan="2" align="center">Check Out</th>
<form name="checkOut" method="post" onSubmit="return(validate(this))">
<tr>
<td>Territory Number</td>
<td><input type="text" name="numberOut" tabindex="1" maxlength="3" size="3" /></td>
</tr>
<tr>
<td>First Name of Publisher</td>
<td><input type="text" onKeyUp="showHint(this.value)" name="fName" tabindex="2" maxlength="15"/></td>
</tr>
<tr>
<td>Last Name of Publisher</td>
<td><input type="text" onKeyUp="showHint_l(this.value)" name="lName" tabindex="3" maxlength="15" /></td>
</tr>
<tr>
<td>Special Campaign</td>
<td><input type ="checkbox" name="specialC" tabindex="4" value="Yes"/></td>
</tr>
<tr>
<td><input type="button" onClick="clearForm()" value="Reset" /></td>
<td><input type="submit" value="Check Out" /></td>
</tr>
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</table>
Here, I want to pass the values of numberOut, fName, lName, and specialC. I know how to pass each of them individually, but not as a group. Ultimately, I want to then be able to access those value through php with $_POST['fName'] for instance.
From seeing several answers to similar questions on this site, a number of people say to use jQuery. I'm aware that it is easier, but I want to learn to use ajax first as I'm new to web-based languages.
You will have to create the params
Here is a sample code for you
var params = "numberOut="+document.getElementsByName("numberOut")[0].value;
params+="?fName="+document.getElementsByName("fName")[0].value;
params+="?lName="+document.getElementsByName("lName")[0].value;
var isSc = document.getelementsByName("specialC")[0].checked;
if(isSc){
params+="?specialC=Yes";
}

Javascript form validation isn't working

I'm writing a form validation script in JavaScript. When the form is submitted, I want it to be validated before going to the next page.
This page is being called from another page using Perl Interchange. Validation is performed for the three fields on the form.
Update: here is the full code:
<FORM ACTION="[process]" name="outofstock_form" METHOD=POST onsubmit="return validate_outofstockform();" >
<INPUT TYPE=hidden NAME="mv_todo" VALUE="return">
<INPUT TYPE=hidden NAME="mv_nextpage" VALUE="outofstock_wish_submit">
<INPUT TYPE=hidden VALUE="[perl scratch session]$which_search;[/perl]" NAME="search_key">
<script type=javascript>
function validate_outofstockform() {
var m = document.forms["outofstock_form"]["email"].value
var e = document.outofstock_form.email.value
var f = document.forms["outofstock_form"]["name"].value
var p = documnet.forms["outofstock_form"]["wish_product"].value
var atpos = e.indexOf("#");
var dotpos = e.lastIndexOf(".");
if (document.outofstock_form.email.value == "") {
alert("The Email field is required.");
return false;
}
if (document.outofstock_form.name.value == "") {
alert("The Name field is required.");
return false;
}
if (document.outofstock_form.wish_product.value == "") {
alert("The Product field is required.");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= e.length) {
alert("Please enter a valid e-mail address");
return false;
}
if (f == null || f == "" || f == "First Name") {
alert("Please enter your first name");
return false;
}
if (p == null || p == "" || p == "Product") {
alert("Please enter your first name");
return false;
}
return false;
}
</script>
<br/>
*Fields in bold are required.<br/>
<table cellpadding="1" cellspacing="5" width="360px" border="0">
<tr>
<td><b>Name:</b></td>
<td>
<input type="text" id="name" name="name" size="40">
</td>
</tr>
<tr>
<td><b>E-mail:</b></td>
<td>
<input type="text" id="email" name="email" size="40">
</td>
</tr>
<tr>
<td>Phone:</td>
<td>
<input type="text" name="phone" size="40">
</td>
</tr>
<tr>
<td> State/ Province:</td>
<td>[include pages/ord/widget_state.html]</td>
</tr>
<tr>
<td > Zip/Postal Code:</td>
<td><INPUT TYPE="text" NAME="zip" VALUE="" size="40" maxlength="10"></td>
</tr>
<br/>
<tr>
<td valign="bottom">Country:</td>
<td>[include pages/ord/widget_country_s.html]</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Salesperson:</td>
<td align=left colspan=2>
<SELECT NAME="salesrep" class="field">
<OPTION VALUE="WEB">(Optional)
[query list=1 prefix=s sql="SELECT id AS username, real_name AS disp_name, everest_id AS int_id FROM employee WHERE sales_ddown = 'Y' AND everest_id != '' ORDER BY real_name"]
<OPTION VALUE="[s-param int_id]"[calc]'[value salesrep]' eq '[s-param int_id]' ? 'selected' : '';[/calc]>[s-param disp_name]
[/query]
</SELECT>
</td>
<INPUT TYPE=hidden NAME="salesperson" VALUE="[s-param username]">
[perl values scratch]
$Scratch->{salesperson} = q{[s-param username]};
[perl]
<tr>
<td colspan="2">
Provide us with the product you are looking for, or the brand and product type
of interest and we will inform you if we find a match.
</td>
<td></td>
</tr>
<tr>
<td><b>Product:</b></td>
<td>
<input type="text" id="wish_product" name="wish_product" size="40" value="">
</td>
</tr>
<tr>
<td>Item Description:</td>
<td>
<textarea name="wish_descrip" rows="2" cols="40"></textarea>
</td>
</tr>
<tr>
<tr>
<td>Brand/Manufacturer Preference:</td>
<td><input type="text" name="wish_man" size="40"></td>
</tr>
<tr>
<td>Product Category :</td>
<td>
<select name="wish_cat">
<option value="" selected>Any Category</option>
[include pages/CATLIST.html]
</select>
</td>
</tr>
<tr>
<td>Is this for a business?:</td>
<td>
<input type="radio" name="option" value="Yes"> Yes
<input type="radio" name="option" value="No"> No<br>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="2"><font size="0px">
We do not sell, rent or otherwise share your information with anyone.<br/>
</font>
</td>
<td></td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="Submit" value="Submit" class="button">
</td>
</tr>
</table>
</form>
Make your JavaScript valid (remove part with multiple dashes) and make it return false to avoid sending the form.
It's hard to tell what exactly is causing the problem, because there are several errors in your code.
A couple of pointers:
You're referencing document.outofstock_form, while the form's name is frm.
<//code table> is not valid HTML. Remove it or replace it with an HTML comment (e.g.: <!-- table code: -->).
It's more common to use a regular expression (search here on SO) to validate form input.
If you're sending the input to a server, perform validation on the server as well. Never trust input from the browser.
You never open the <tr> (presumably a copy-paste error).
And finally, but most importantly:
Always look at your browser's JavaScript error console first. This must be your starting point when debugging JavaScript code. It can help you find the problem and if it doesn't, it can help others help you.
Read How to Ask.
Have you debugged your code?
Use tools like Firebug to debug your scripts. Put a breakpoint in the first line of your validation function and then debug it step by step. You will eventually get to the line that's causing your problems.
A suggestion of how to improve your validator
But apart from debugging I would do validation differently. Instead of checking every single aspect of individual fields I'd rather just add a custom attribute to those inputs that need validation and just check whether they match or not. If any fails inform your user about non-valid field...
<input name="SomeName"
validation-expression=".+"
display-name="Required text field"
type="text" />
Using libraries like jQuery would be even more helpful when working with such data because it would be much easier to enumerate these elements and work with their data... I would of course warmly suggest you use jQuery anyway because it will make your code much more cross-browser. It's a simple library with short learning curve but huge benefits.
But using those special attributes would make your validator function universal so it could be used with any element and on any page. All you'd have to do is to put particular validation attributes to your elements.
Just a suggestion of course.

Categories