Answer the question
In order to leave comments, you need to log in
How to send ajax request?
Hello! I'm trying to send an ajax request from a view, but I get an error POST localhost:8080/account/interface 400 (Bad Request)
The request function is called when the button is clicked, but there is some trouble with the url. The request is NOT written in jQuery, because there is already code in js, and I decided to send a request on it. The handler is the interface action in the accauntController controller. Here is part of the code in the view:
var ajax = new XMLHttpRequest();
function request(){
url = 'interface'
ajax.onreadystatechange = response
ajax.open('POST', url, true)
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
ajax.send('name=me&msg=mymsg&time=2019')
}
Answer the question
In order to leave comments, you need to log in
<div id="names"></div>
<!-- AJAX: Asynchronious Javascript And XML -->
<form action="test.php" method="post">
<input type="text" name="firstname" id="firstname"><br>
<input type="text" name="lastname" id="lastname"><br>
<button type="button" name="myBtn" onclick="ajax_post();">Отправить</button>
</form>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "test.php";
var fn = document.getElementById('firstname').value;
var ln = document.getElementById('lastname').value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST",url,true);
hr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
document.getElementById('names').innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById('names').innerHTML = 'Данные отправляются, пожалуйста, подождите...';
}
</script>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question