Reputation: 39
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);
}
Upvotes: 1
Views: 370
Reputation: 345
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
.
Upvotes: 3