I earlier asked a question about a xmlHttp.send() code that wasn't working. I thought I had fixed all of it, but now I've got another problem.
In the handleServerResponse() function, the code errors out in the if (xmlHttp.readyState == 4) and if (xmlHttp.readyState == 200). Why is it doing that? An example php code is under the JavaScript.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("cant create that object hos");
}else{
return xmlHttp;
}
}
function newuser() {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
name = encodeURIComponent(document.getElementById("name").value);
queryString = "name=" + name;
xmlHttp.open("GET", "code/php/core.php?" + queryString, true);
xmlHttp.onreadystatechange = handleServerRespons;
xmlHttp.send();
}else{
setTimeout('newuser()', 1000)
}
}
function handleServerRespons(){
if (xmlHttp.readyState == 4){
if (xmlHttp.readyState == 200){
alert('1234545');
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert(message);
}
}
}
php code:
$name = $_GET['name'];
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
echo $name;
echo '</response>';
instead of using a variable (xmlHttp) you must use this in an onreadystatechange event callback
so your function will be:
function handleServerRespons() {
if ( this.readyState === 4 && this.status === 200 ) { // and also use "status" here not "readyState"
xmlResponse = this.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert( message );
}
}
or wrap your code with (function(){...})(); like below
(function() {
// all your code goes here, so you can use that 'xmlHttp' instead of 'this'
})();
xmlHttp.readyState can't be 200. you should use xmlHttp.status.
xmlHttp.readyState has status of the XMLHttpRequest The XMLHttpRequest Object
xmlHttp.status will be available when xmlHttp.readyState is 3 or 4. When available xmlHttp.status should represent the HTTP status code.
Related
I'm requesting data from my data.php file with the following request:
xmlhttp.send('request=getchartdata&'+'chart='+chart+'&'+'key='+key);
Here's the content of data.php:
if ($_POST["request"] == "getchartdata") {
/*Removing dash from key*/
$key = str_replace("-", "", $_POST["key"]);
if ($_POST["chart"] == "associationEvolutionSubventions") {
$result = $conn->prepare("SELECT grantYear, grantAmount FROM granttoassociation WHERE HEX(grantReceiver) = ? ");
/*grantReceiver is in binary*/
}
$result->execute(["{$key}"]);
while($rs = $result->fetch()) {
if ($outp != "") {
array_push($outp,$rs);
}
}
}
$outp = json_encode($outp);
echo($outp);
However, I'm getting an empty array in xmlhttp.responseText.
The connexion to the MySQL Database isn't the issue (another xmlhtpp request is returning data correctly). There's a few point where I'm unsure about my code though:
$result->execute(["{$key}"]); Is the syntax correct here?
HEX(grantReceiver) Is it correct to do this, given grantReceiver is in binary?
$key = str_replace("-", "", $_POST["key"]); Is it the correct syntax for removing dash?
Edit: here's the full AJAX code as requested.
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("POST", "wp-content/plugins/mygaloochart/data.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('request=getchartdata&'+'chart='+chart+'&'+'key='+key);
Rearrange your code. You should listen to onreadystate after Opening the request and setting request headers(The following is your revised code):
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "wp-content/plugins/mygaloochart/data.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.send('request=getchartdata&'+'chart='+chart+'&'+'key='+key);
I have to check weather invoice number is duplicate or not for that i am using following ajax.
function check_duplicate_invoice(num){
var isDuplicate ;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","check_duplicate_invoice.php?in="+num, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
isDuplicate =xmlhttp.responseText.trim() // reponceText will be 0 or 1
}
}
alert(isDuplicate); //result undefined
if(isDuplicate== 1){
alert("Invoice Number Already Exist");
}
}
I am not able to store ajax output into isDuplicate variable. Please help.
That's because ajax calls are asynchronous. You are looking at the variable before the request has had a time to complete. Try this:
function check_duplicate_invoice(num){
var isDuplicate ;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","check_duplicate_invoice.php?in="+num, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
isDuplicate =xmlhttp.responseText.trim() // reponceText will be 0 or 1
alert(isDuplicate); //result undefined
if(isDuplicate== 1){
alert("Invoice Number Already Exist");
}
}
}
}
I'm trying to calculate text box value via ajax, on event onkeyup :
index.php
<html>
<head>
<script type="text/javascript">
function calc() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var text = document.getElementById('txtField').value;
var target = "calc.php";
var parameter = "txtValue=" + text;
xmlhttp.open('POST', target, true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameter);
}
</script>
</head>
<body>
Price: <input type="text" id="txtField" onkeyup="calc();">
<div id="myDiv"></div>
</body>
</html>
calc.php
if ($_POST['txtValue'] && !empty($_POST['txtValue'] )) {
echo $_POST['txtValue'] * 4;
}
But won't show the result. Please tell me what am i missing here ?
Try to change your calc.php like:
if (isset($_POST['txtValue']) && !empty($_POST['txtValue'] )) {
echo $_POST['txtValue'] * 4;
}
use the following to see if you are getting correct response:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
ok hre is your problem:
use:
if (($_POST['txtValue'] != '') && !empty($_POST['txtValue'] ))
instead of:
if ($_POST['txtValue'] && !empty($_POST['txtValue'] ))
cuase $_POST['txtValue'] is not a boolean and can't be used in if condition
This is my code snippet, couldn't understand what's wrong with this as xmlhttp.readyState is not changing to 4.
document.getElementById("opencloseimg").src = "images/minus.jpg";
//The page we are loading.
var serverPage = "calendar.php";
//Set the open close tracker variable.
showCalendar = false;
var obj = document.getElementById(objID);
xmlhttp.open("GET", serverPage,true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
Maybe because the URL you are fetching is not available?
Do you see any errors in the JavaScript console?
Put a message display at the beginning of your statechange function :
xmlhttp.onreadystatechange = function() {
console.log ('xmlhttp : ' + xmlhttp.readyState + ', ' + xmlhttp.status);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
See what is displayed.
Maybe the response status code is not 200, it could be 304 (not modified) etc.
I have a textarea where I put some C++ code, then I get that code with javascript and send it to a PHP script via AJAX to be processed. The problem is that the code gets corrupted in the way.
Here is my code:
function showResult()
{
var code = document.getElementById('code').value;
var input = document.getElementById('input').value;
if (code != '') {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ideone.php?code=' + code + '&input=' + input, true);
xmlhttp.send();
}
}
PHP:
<?php
echo 'Code: '.$_GET['code']; // Empty string
?>
You need to quote your query string:
xmlhttp.open('GET', 'ideone.php?code=' + encodeURIComponent(code) + '&input=' + encodeURIComponent(input), true);