readystate never reaching 4 - javascript

In the code below I try to post some data to a table and then retrieve several records from the table afterwards. For testing purposes I have only included a dummy query in the php, which returns a valid xml.
But the Javascript readystate only reach readystate 1 (twice). As the php seems to be working fine I suspect I have scripted the javascript incorrectly. Is it a problem with the "request" variable?
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
var name = $('input[name=name]').val();
var request = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var xml = request.responseXML;
var dynamiclist = '';
document.getElementById("myLink").innerHTML = '';
var posts = xml.documentElement.getElementsByTagName("post");
for (var i = 0; i < posts.length; i++) {
var Msg = posts[i].getAttribute("Msg");
alert("test");
var dynamiclist = dynamiclist + '<article class="middleContent"><header><h2>' + Msg + '</h2></header> </article>';
document.getElementById("myLink").innerHTML = dynamiclist;
};
};
};
request.open('POST', 'process.php', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send('name=' + name);
});
});

Using jQuery makes sense here.
Simple solution however most probably is to simply remove the last "true" in request.open(), which makes the request an asynchronous, non-blocking one (which it really should be anyway). MDN also states at onreadystatechange that you shouldn't be using it with synchronous requests (aka requests that have "true" as third argument for open())
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Try preventing the default form event from firing:
$('form').submit(function(event) {
event.preventDefault();
This prevents the form element from reloading the browser window.

Related

How to send an API get request using JavaScript with HTML variables

I am trying to make a GET request to a web API using what is inputted in a textbox. So far I have the input value established but can't seem to figure out to send the request.
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
console.log(requestdata);
This function correctly but I can't seem to figure out the rest.
I am trying to do the following:
https://api.example.com/request?=${requestdata}
or
https://api.example.com/request/${requestdata}/test
Keep in mind that this is a static HTML site with no Node
Something like this should work to make an asynchronous GET request:
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
httpGetAsync("https://api.example.com/request?=${" + requestdata + "}");
<input type="text" id="request" value="test">
If you check the developer tools > network tab you should see the GET request to the API endpoint.

Trouble with PHP form and Ajax

I’m trying to submit a form with data to a php file without reloading the page. I also have some js code that changes the form name and values when the next btn is clicked. I had 10 questions all on 1 page and I got it to work with PHP but now I’m trying to get 1 question per page. I looked in the network tab and it looks like the xhr requests are being sent but in my database.php file I wrote $user_anwser = $_POST[‘quiz_1’]; and var dumped it and I get a NULL value. Here is the ajax code.
form.addEventListener("submit", function(e){
if (ind < 10){
e.preventDefault();
} else {
form.setAttribute("action", "results.php");
}
let data = new FormData(form);
let xhr = new XMLHttpRequest();
xhr.open('POST', '../private/database.php');
xhr.onload = function() {
if (xhr.status === 200) {
// if the response is json encoded
let response = JSON.parse(xhr.responseText); // i get a parse error there
if (response.message == 'valid') {
// redirect here
}
}
// }
xhr.send(data);
}
});

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

Response div keeps disappearing after ajax request

I am building an online calculator and tried to send the values through AJAX to process them by a php script. The response from the server is set to the div but that div immediately disappears after showing. My ajax code is:
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // calls the function for the XMLHttpRequest instance
// gets data from form fields, using their ID
var c1 = document.getElementById('c1').value;
var c2 = document.getElementById('c2').value;
var c3 = document.getElementById('c3').value;
var c4 = document.getElementById('c4').value;
var c5 = document.getElementById('c5').value;
var c6 = document.getElementById('c6').value;
// create pairs index=value with data that must be sent to server
var the_data = 'c1='+c1+'&c2='+c2+'&c3='+c3+'&c4='+c4+'&c5='+c5+'&c6='+c6;
request.open("POST", php_file, true); // sets the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // sends the request
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById("ajaxform").submit();
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
Please note that I am using bootstrap CSS framework for the actual site and not applying any classes on the response div.
Thanks
In your onreadystatechange handler, you're submitting a form, which is causing the page to submit (and therefore the page to change).
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.getElementById("ajaxform").submit(); // <-- ?
document.getElementById(tagID).innerHTML = request.responseText;
}
}
The fact you're seeing the same page again means the form ajaxform has no action set.

Render HTML returned through AJAX call in JavaScript

I am a complete novice in the JavaScript and AJAX stuff. I am trying to make a call to the server using AJAX and display the returned HTML. However instead of rendering the HTML, the browser displays the HTML code. I am not using JQuery and I would prefer not using it (an acute shortage of time and my complete unfamiliarity with JQuery are two major reasons for sticking to basic JavaScript). Is there some way to render the HTML as it is supposed to be using just the basic JavaScript. Here is my code
function gotoNext(button){
try {
xmlHttp = new XMLHttpRequest ();
}
catch (e) {
try {
xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
catch (el) {
try {
xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");
}
catch (el1) {
alert ("Your browser does not support AJAX! Please use a compatible browser!!");
}
}
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var df = document.getElementById ("dataForm");
var data = xmlHttp.responseText;
df.innerText = data;
}
};
var id = document.editEnv.id.value;
var sId = document.editEnv.sId.value;
var fileName = document.editEnv.fileName.value;
var group = document.editEnv.group.value;
xmlHttp.open("POST", "newData.jsp", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
xmlHttp.send ("flag=" + flag + "&id=" + id + "&sId=" + sId + "&fileName=" + fileName + "&group=" + group);
You should use df.innerHTML = data;
innerText just gets/sets the value as plain text.
You can try to replace innerText with innerHTML The difference lies in the fact that innerText doesn't include any HTML tags whereas innerHTML does. For example
Here is a link
will display:
Here is a link
if you call innerText on it. However, if you call it with innerHTML it will display:
Here is a link
df.innerHTML = data;
should work!!
Because using innerHTML will render that html on browser.
innerText will just display HTML code as normal text.

Categories

Resources