Response text from AJAX is blank - javascript

I am trying to do an AJAX call and I'm getting a successful (200) response but the response text is blank.
I've looked at several other SO answered to this question but none of them seemed to work.
<form id="status-code-form" v-on:submit="processStatusForm">
<input type="text" id="status-code-url" v-model="ajInput" />
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var appForm = new Vue({
el: '#status-code-form',
// our data
data: {
ajInput: ''
},
// our methods
methods: {
processStatusForm: function(e) {
e.preventDefault();
// start ajax
if (this.ajInput !== "") {
var newInputtedText = this.ajInput;
xhr = new XMLHttpRequest();
xhr.open('POST', './processes/check-url-code.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200 && xhr.readyState === 4) {
console.log("Response text was successfull" + xhr.responseText);
}
else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
var data = {action: 'content_fetch', inputtedText: newInputtedText };
xhr.send('action=content_fetch&inputtedText=' + newInputtedText);
} // end if input was empty
} // end process form
} // end methods
});
</script>
In my PHP file, it's very simple:
<?php
function content_fetch() {
echo "hello";
}
I would think that the response text is equal to "hello", but it's blank. I just get the console log of "Response text was successfull".

Related

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

Form fields gets cleared on POST data with knockout binding

I'm working with PHP on backend with Slim microframework, in case it be relevant.
Well, the problem is that the form gets cleared after submit. The server return an error code, in case of error, ofcourse, and the error message is showed to the user, but the fields are clean.
I must mention that I'm using the jquery-validation plugin.
HTML
<form action="{{ path_for('save_data') }}" method="POST" id="myForm" name="myForm" data-bind="submit: sendForm">
<input type="text" name="foo" data-bind="value: foo" required>
<button type="submit">Save data</button>
</form>
Javascript/Knockout JS
function MyView($) {
var self = this;
self.foo = ko.observable();
/* ... code ... */
self.sendForm = function(theForm) {
if (!$(theForm).valid()) {
return;
}
$.post(theForm.action, ko.toJS(self.foo), function(response) {
alert(response);
})
.fail(function(failResponse) {
alert(failResponse);
});
};
}
ko.applyBindigs(new MyView(jQuery));
Just for better understanding, the server code is something like this:
public function postSaveData($request, $response) {
if (TRUE) { // Some validations here
return $response->withJson("Error message", 400);
}
// save
return $response->withJson("OK", 200);
}
UPDATE
After some tests, occurs to me to test with pure javascript code, with no jQuery. Like as follows:
self.sendForm = function(theForm) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Response text: ", xhttp.responseText);
}
else if (this.status == 400) {
console.log("Response text: ", xhttp.responseText);
}
};
xhttp.open("POST", formElement.action, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(ko.toJS(self.imovel));
};
And voilá! Form perfect filled, as before send data. Somehow jQuery post is clearing the form.

Why won't Javascript code run?

I'm new new to javascript. This is my first real attempt to do something besides running hello world. I'm attempting to retrieve information from a url and display it. I checked the url and it returns json. The "Hello World" code runs but as soon as I add the code that retrieves the json inside the script tags nothing happens. I'm getting no syntax errors.
<!DOCTYPE HTML>
<html>
<body>
<p>Header...</p>
<script>
document.write("Hello World");
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "json";
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON("http://api.tvmaze.com/schedule?country=US&date=2016-08-31",
function(err, data) {
if (err != null) {
alert("Something went wrong: " + err);
} else {
alert("Your query count: " + data.query.count);
}
});
</script>
<p>...Footer</p>
</body>
</html>
I checked your html and js and one quick look into the console showed me that the problem was this line
alert("Your query count: " + data.query.count);
change the "data.query.count" to "data.length"
alert("Your query count: " + data.length);
Debuging code is one of the easiest ways to find errors.
You can hit F12 in basicly any browser to inspect the things behind the scene
If you examine the console on your browser you will see that your code is throwing the error of Uncaught TypeError: Cannot read property 'count' of undefined.
This is because you are attempting to access the length of the response array by means of data.query.count, when in fact it should be data.length.
So the working code should look like;
<!DOCTYPE HTML>
<html>
<body>
<p>Header...</p>
<script>
document.write("Hello World");
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "json";
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON("http://api.tvmaze.com/schedule?country=US&date=2016-08-31",
function(err, data) {
if (err != null) {
alert("Something went wrong: " + err);
} else {
alert("Your query count: " + data.length);
}
});
</script>
<p>...Footer</p>
</body>
</html>

Fetching data from php file and using javascript to print selected data

I have 2 divs in my html page. Using AJAX, JavaScript, I send my query parameters to a php file, which returns combined results for the 2 divs. I want to know how to separate the result in JavaScript and display in their respective divs.
<script>
function fetchData() {
var yr = document.getElementById('entry').value;
if (yr.length==0) {
document.getElementById("result1").innerHTML="";
document.getElementById("result2").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var content = xmlhttp.responseText;
if (content == "%<searchword>%")
document.getElementById("result1").innerHTML = content;
else
document.getElementById("result2").innerHTML = content;
}
}
xmlhttp.open("GET","db.php?q="+ yr ,true);
xmlhttp.send();
}
</script>
<body>
<form>
Enter year: <input type="text" id="entry" />
<input type="button" value="check here" onclick="fetchData()" />
</form>
<div id="result1">result 1 here</div>
<div id="result2"> result 2 here</div>
</body>
Return json as PHP output, that is best for Javascript (do not forget json php headers, use json_encode), like this:
{
"div1": "Content for div 1",
"div2": "DIV 2 content"
}
Easy with jQuery getJSON method, or jQuery $.ajax:
$.ajax({
dataType: "json",
url: urlToPHPFile,
data: dataToSend,
success: function( jsonResponse ) {
$('#result1').html( jsonResponse.div1 );
$('#result2').html( jsonResponse.div2 );
}
});
To send request with pure Javascript take a look at this article.
To parse JSON just read this article.
So, with pure Javascript you get something like this:
function alertContents(httpRequest){
if (httpRequest.readyState == 4){
// everything is good, the response is received
if ((httpRequest.status == 200) || (httpRequest.status == 0)){
var obj = JSON.parse(httpRequest.responseText);
var div1 = getElementById('result1');
var div2 = getElementById('result2');
div1.innerHTML = obj.div1;
div2.innerHTML = obj.div2;
}else{
alert('There was a problem with the request. ' + httpRequest.status + httpRequest.responseText);
}
}
};
function send_with_ajax( the_url ){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open("GET", the_url, true);
httpRequest.send(null);
};
function fetchData() {
var yr = document.getElementById('entry').value;
if (yr.length == 0) {
document.getElementById("result1").innerHTML = "";
document.getElementById("result2").innerHTML = "";
return;
}
send_with_ajax( "db.php?q=" + yr );
};
fetchData();

Passing values from javascript to servlet not working in chrome

Im trying to pass parameters to servlet from javascript with :
function selectHandler() {
var selection = table.getChart().getSelection()[0];
var topping = data.getValue(selection.row, 0);
var answer=confirm("Delete "+topping+"?");
if(answer){
document.location.href="/item?_method=delete&id="+topping;
alert(topping+" has been deleted");
location.reload();
}
else return false;
}
The values are getting passed to the servlet and is working fine when I'm using firefox as in I'm getting the url as: http://XXXXXXX/item?_method=delete&id=xxxx
But when I'm using chrome the URL that is send is http://XXXXXXX/item. as the values are not getting passed!! I have tried with window.location.href also with no change. what could be the issue?
What you need is ajax call or say XMLHttpRequest as below:
<script type="text/javascript">
function doAjax () {
var request,
selection = table.getChart().getSelection()[0],
topping = data.getValue(selection.row, 0),
answer=confirm("Delete "+topping+"?");
if (answer && (request = getXmlHttpRequest())) {
// post request, add getTime to prevent cache
request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
request.send(null);
request.onreadystatechange = function() {
if(request.readyState === 4) {
// success
if(request.status === 200) {
// do what you want with the content responded by servlet
var content = request.responseText;
} else if(request.status === 400 || request.status === 500) {
// error handling as needed
document.location.href = 'index.jsp';
}
}
};
}
}
// get XMLHttpRequest object
function getXmlHttpRequest () {
if (window.XMLHttpRequest
&& (window.location.protocol !== 'file:'
|| !window.ActiveXObject))
return new XMLHttpRequest();
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
}
</script>
You can also do it easily by jquery,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
function doAjax () {
...
$.ajax({
url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("It worked!");
// do what you want with the content responded by servlet
}
});
}
</script>
Ref: jQuery.ajax()

Categories

Resources