Issue using Ajax's Post Method to Send Multiple Values - javascript

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";
}

Related

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

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.

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>

Jquery form serialization is not working on facebox with Scala Play Framework 2.2

I know some similar questions are also available, but they doesn't help me.
I am doing it in Scala Play Framework. I am posting my code below:
var saveNameRequest;
function saveName(){
if(!saveNameRequest){
saveNameRequest=$.ajax({
type:"POST",
url:"edit?editType=saveName",
data: $("#nameForm").serialize(),
complete:function(){saveNameRequest=false},
success: function(data){
alert($("#nameForm").serialize())
}//end success
});
}
}
Form serialization is not working, and an empty string is being printed.
nothing is going through post, please help
<form method="POST" name="nameForm" id="nameForm">
<tr>
<td><font color=#3b5999>First Name:</font></td>
<td><input type="text" name="fname" id="fname" value="#fName"></td>
</tr>
<tr>
<td><font color=#3b5999>Middle Name:</font></td>
<td><input type="text" placeholder="optional" name="mname" id="mname" value="#mName" ></td>
</tr>
<tr>
<td><font color=#3b5999>Last Name:</font></td>
<td><input type="text" name="lname" id="lname" value="#lName"></td>
</tr>
<tr>
<td></td>
<td><input name="save" id="save" type="button" value="save" onClick="saveName()"></td>
</tr>
</form>
i found form serialization does not work with facebox in scala 2.10
we have to send data of all fields,it is the only solution that i got,
data:{
"fname":document.getElementById("fname").value,
"mname":document.getElement‌​ById("mname").value,
"lname":document.getElementById("lname").value
}
You have not closed your saveName() function. Try after closing it. Also, make sure saveName() is outside document.ready().
Add a key to ajax data parameter to send the serialized string like below:
data: { formData: $("#nameForm").serialize() },
Edited the fiddle and it seems to work

JavaScript: how to access the textbox in the second row of the table

I have an html code like this -
<table border="0" cellspacing="2" cellpadding="2" width="99%" id="subAccTable">
<tr>
<h2>Sub Accounts</h2>
</tr>
<tr>
<th>action </th>
<th>account</th>
<th>homeDir</th>
<th>primaryGroup</th>
</tr>
<tr>
<td><input type="hidden" name="vtierId" value="" /></td>
<td><input type="text" name="subAcc"
value=""/></td>
<td><input type="text" name="subHomeDir"
value=""/></td>
<td><input type="text" name="subPriGroup"
value=""/></td>
</tr>
</table>
Now i want to fill the values of textboxes named subAcc, subHomeDir, subPriGroup using javascript. How can i do it ?
There are multiple ways to get the proper DOMElement; including:
Giving each element an id and getting it using document.getElementById
Using document.getElementsByName. This is not preferred since there can be multiple elements with the same name, however there can be only one with the same id.
Using the form directly. For example if your form's name is form1: form1.subAcc
Using document.getElementsByTagName('input') and then getting the proper index.
I'd recommend using the id to retrieve the proper element.
The easiest way would be to give these textboxes a unique id, then reference them like this:
<input type="text" id="subHomeDir" name="subHomeDir" value=""/>
var tb = document.getElementById("subHomeDir");
tb.value = "foo";
If you're stuck with the names only, then you can use document.getElementsByName, just remember, this will return a collection of elements (since names are not necessarily unique), which you'll have to index:
var tb = document.getElementsByName("subHomeDir")[0];
tb.value = "foo";

How to create and submit a form using Java Script

I'm writing a Firefox extension that's to be used in house. Basically, I need to submit a pdf file and some text values to a web service. Right now I have a html page that does this. I need the extension to automate the gathering and submission of the data to the web service.
Here's the html that works.
<body>
<form name="frm_upload_file" enctype="multipart/form-data" method="post" action="my web service address">
<table cellpadding="2" cellspacing="0" border="0">
<tr>
<td>ClientID</td>
<td><input type="text" name="client_id" /></td>
</tr>
<tr>
<td>HTML</td>
<td><input type="text" name="html" /></td>
</tr>
<tr>
<td align="right" class="inputtxt"> File: </td>
<td class="inputtxt">
<input name="pdf" type="file" />
</td>
</tr>
<tr>
<td align="left" colspan="2" class="inputtxt">
<p><br /><input type="submit" name="submit" value="Submit" /></p>
</td>
</tr>
</table>
Here's the javascript that doesn't
postToURL: function(html, file) {
var form = content.document.createElement("form");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("method", "post");
form.setAttribute("action", "address to my web service");
var clientIDField = document.createElement("input");
clientIDField.setAttribute("type", "text");
clientIDField.setAttribute("name", "client_id");
clientIDField.setAttribute("value", "123456");
form.appendChild(clientIDField);
var htmlField = document.createElement("input");
htmlField.setAttribute("type", "text");
htmlField.setAttribute("name", "html");
htmlField.setAttribute("value", html);
form.appendChild(htmlField);
var fileField = document.createElement("input");
fileField.setAttribute("type", "file");
fileField.setAttribute("name", "pdf");
fileField.setAttribute("value", file);
form.appendChild(fileField);
content.document.body.appendChild(form);
form.submit();
When submitting the data with the js, I get the following exception from the server.
exception
javax.servlet.ServletException: com.sun.jersey.api.container.ContainerException: javax.mail.MessagingException: Missing start boundary
Any ideas?
You can't set the value of a file input - otherwise you could steal files from people's machines.
I don't think you can modify the value of a <input type="file"> field for security reasons. You'll likely need to find another way of automating this.

Categories