AJAX works in jQuery but not in vanilla JS - javascript

I have a small form where when the username field is being blurred or out of focus, AJAX checks if the entered username is already recorded in the database. The problem is that the AJAX in jQuery works, but not in vanilla JS. I need to know what line or part of my code did I get it wrong.
HTML
<form action="process.php" method="post">
<input class="username" type="text" name="username" placeholder="Enter username" autocomplete="off">
<span class="uname_notice"></span><br>
<input type="submit" value="Submit">
</form>
jQuery
$('.username').blur(function() {
var username = $(this).val();
$.ajax({
url: 'process.php',
type: 'post',
data: {username: username},
success: function(responseText) {
$('.uname_notice').text(responseText);
}
})
});
Vanilla JS
document.querySelector('.username').onblur = function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
document.querySelector('.uname_notice').textContent = xhr.responseText;
}
}
xhr.send();
}

Send data along with the HTTP request.
document.querySelector('.username').onblur = function() {
var xhr = new XMLHttpRequest();
var data = new FormData();
var username = document.getElementsByClassName('username')[0].value;
data.append('username', username);
xhr.open("POST", "process.php", true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
document.querySelector('.uname_notice').textContent = xhr.responseText;
}
}
xhr.send(data);
}

You forgot to specify post value. Try to use this:
document.querySelector('.username').onblur = function() {
var params = 'username='+this.value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
document.querySelector('.uname_notice').textContent = xhr.responseText;
}
};
xhr.send(params);
};

Related

Empty request.POST on Django AJAX call

I am trying to send form data to one of my view. But I am getting empty request.POST
My ajax call is :
ajaxSubmit = () =>{
exam_type = document.getElementById('exam_type').value
total_marks = document.getElementById('total_marks').value
var request = new XMLHttpRequest();
request.open('POST', "{% url 'addExamForm' %}", true);
request.setRequestHeader("X-CSRFToken", "{{ csrf_token }}")
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
alert("Success");
} else {
alert("Fail");
}
};
request.send(JSON.stringify({"exam_type":exam_type,"total_marks":total_marks}));
}

Not able to echo POST paramenters sent in ajax, inside PHP

I am sending two parameters inside the send method to index.php. But the PHP returns an error "Undefined index". echo $_POST['fname'];
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
In order to send form data through Ajax, you have to specify the content type of the request. In you case it will be 'application/x-www-form-urlencoded:
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
So your code will be:
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});

How to send AJAX post request and receive back JSON data in Vanilla JS?

I have used JQuery example to send form data and receive back JSON data. Now I would like to do the same thing in plain/vanilla Javascript. Here is example of my JQuery code:
$('.frmSubmitData').on('submit', function(e){
e.preventDefault();
var formData = $('#myForm').serialize();
console.log(formData);
$.ajax({
type: 'POST',
encoding:"UTF-8",
url: 'Components/myTest.cfc?method=testForm',
data: formData,
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
console.log(obj.FORMDATA);
}else{
alert('Error');
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
});
And here is what I have so far in plain JS:
function sendForm(){
var formData = new FormData(document.getElementById('myForm')),
xhr = new XMLHttpRequest();
xhr.open('POST', 'Components/myTest.cfc?method=testForm');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(formData);
}
I think that something is wrong in way how I handle response with JSON data. If anyone can help me with problem please let me know. Thank you.
Optimally, for Firefox/Chrome/IE and legacy IE support, first determine the request type:
function ajaxReq() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser does not support XMLHTTP.");
return false;
}
}
Then, send the request:
var xmlhttp = ajaxReq();
var url = "http://random.url.com";
var params = "your post body parameters";
xmlhttp.open("POST", url, true); // set true for async, false for sync request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params); // or null, if no parameters are passed
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var obj = JSON.parse(xmlhttp.responseText);
// do your work here
} catch (error) {
throw Error;
}
}
}

JQuery Ajax call working but not native JavaScript

I have two AJAX calls, one in native JavaScript and another with JQuery, which call a PHP Script. The JQuery one is working, but the JavaScript one not. Here goes the code:
JQuery:
$.ajax({
url: "/Tests/index.php",
method: "POST",
data: {'Id': "2"}
});
Native JavaScript:
var Data = {Id: "2"};
XHR = new XMLHttpRequest();
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.send(JSON.stringify(Data));
PHP Script:
echo var_dump($_POST);
The one with JQuery returns 2, but the JavaScript one, doesn't return anything. All the data is seen through the console of the web browser.
Try this code:
var Data = {"Id": "2"};
var XHR = new XMLHttpRequest(); // declared XHR var
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.send(Data); // sending data without converting to string
Reference: https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

How to display POST values which are coming from javascript XMLHttpRequest() in php

I am sending parameters using XMLHttpRequest() javascript function to another php page in Json formate, but $_POST['appoverGUID'] not getting post values.
Here is my Javascript code.
function loadPage(href){
var http = new XMLHttpRequest();
var url = json.php;
var approverGUID = "Test";
var params = JSON.stringify({ appoverGUID: approverGUID });
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('bottom').innerHTML = http.responseText;
}
}
http.send(params);
}
And here is my json.php file code.
if(isset($_POST['appoverGUID'])){
echo $_POST['appoverGUID'];
}
First of all remove these headers since they will be send automatically by the browser and it's the right way to do it.
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
This code is a cross browser solution and it's tested.
// IE 5.5+ and every other browser
var xhr = new(window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
var params = "appoverGUID="+approverGUID;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
console.log(JSON.parse(this.responseText));
}
}
}
xhr.send(params);
xhr = null;
You need use json_decode. Some like this:
if ("application/json" === getallheaders())
$_JSON = json_decode(file_get_contents("php://input"), true) ?: [];
Fill params this way (did no escaping/encoding of approverGUID content, here..):
params = "appoverGUID="+approverGUID;
Also see:
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

Categories

Resources