Reputation: 619
When I pass POST data through AJAX to my controller it is empty. In the AJAX the data is still there but after I send it the controller it says it is empty.
AJAX:
function usernameCheck()
{
var input = document.getElementById("usernameInput");
var icon = document.getElementById("userIcon");
var xmlhttp,
username = document.getElementById("usernameInput"),
message = document.getElementById("usernameMessage");
if (username.value != "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// FOR DEBUGGING
console.log(xmlhttp.responseText);
}
}
}
xmlhttp.open("POST", "usernamevalidation", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username.value);
}
}
Routes.php:
Route::post('usernamevalidation', 'UserController@validateUsername');
UserController.php:
class UserController extends BaseController {
public function validateUsername() {
// FOR DEBUGGING
dd(Input::all());
}
}
The code that I console.logged (which is empty and should contain the username):
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
<i><font color='#888a85'>empty</font></i>
</pre>
Upvotes: 9
Views: 6009
Reputation: 1641
In the awareness that I'm giving my answer here one year later since the last comment, I've stumbled on the some error using Laravel 5.2 and working with XMLHttpRequest
objects: finally I ended to analyze and compare post request headers, which led me to simply setting both:
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
That solved my empty responseText
.
Hope this can help someone else or can be used for future reference.
Upvotes: 7