I wrote small calculator script with JS and PHP. As i saw all is correct, but in output server show me blank ('0') value. I cant find a solution for 2 hours.
JS script, that open connection with POST method with action 'calc.php':
<script type="text/javascript">
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function summa() {
var how0 = document.getElementById("how0").value;
var xmlhttp = getXmlHttp();
xmlhttp.open('POST', 'calc.php', true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("how0=" + encodeURIComponent(how0));
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("how").value = xmlhttp.responseText; //
}
}
};
}
</script>
Form for calculating:
<input type="number" required name="how0" id="how0" min="100" max="999999" placeholder="100">
<input type="number" required readonly name="how" id="how" min="200" max="999999" placeholder="200">
<input type="button" value="Calcul" onclick="summa()" />
Calc.php for checking:
<?php
$a = is_numeric($_POST["how0"]);
$a = floor($a);
if ($a>1) {
$a = $a * 2;
}
if ($a>10000) {
$a = $a * 3;
}
echo $a;
?>
This line:
$a = is_numeric($_POST["how0"]);
Assigns the return value of is_numeric to $a — e.g., true or false. Then you use $a as though it contained the value posted to the script, but it doesn't.
You probably meant to use intval or floatval or similar:
$a = intval($_POST["how0"]);
Note that unless you need to support really old browsers, there's no need for your getXmlHttp function. All vaguely-modern browsers support new XMLHttpRequest.
Related
index.php:-
<!DOCTYPE html>
<html>
<head>
<script src="food.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body onloadd="process()">
<div class="container">
<h2 class="page-header">The Chuff Bucket</h2>
<strong>Enter the food you want to order:</strong><br><br>
<input type="text" class="form-control" id="userInput">
<div id="underInput">
</div>
</div>
</body>
</html>
foodstore.php
<?php
header('Content-Type:text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','loaf','sandwich','pizza');
if(in_array($food, $foodArray))
{
echo 'We do have'.$food.'!';
}
elseif($food=='')
{
echo 'Enter a food chomu';
}
else
{
echo 'We have no'.$food;
}
echo '</response>';
?>
food.js"-
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("Cannot create the object!!");
}
else
{
return xmlHttp;
}
}
function process() {
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
var food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET","foodstore.php?food="+food,true);
xmlHttp.onreadystatechange = handleServerResponse();
xmlHttp.send(null);
}
else
{
setTimeout('process()',1000);
}
}
function handleServerResponse() {
if(xmlHttp.readyState == 4)
{
if (xmlHttp.Status == 200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocElm = xmlResponse.documentElement;
msg = xmlDocElm.firstChild.data;
document.getElementById("underInput").innerHtml = '<span style="color:blue;">'+msg+'</span>';
setTimeout('process()',1000);
}
else
{
alert("Something is wrong!!");
}
}
}
I just started with AJAX and this is my first code. I have even free hosted it. Here is the url:- Chuff Bucket
I have no idea what is wrong with the code. I have done the same as shown in the tutorial.
This isn't doing what you think:
xmlHttp.onreadystatechange = handleServerResponse();
This is invoking the handleServerResponse function immediately (which doesn't do anything, because xmlHttp.readyState isn't 4 at that time), and setting the result of that function to the onreadystatechange callback. Since that function doesn't return anything, that result is undefined.
Don't invoke the function, just set it like a variable as the callback:
mlHttp.onreadystatechange = handleServerResponse;
There is javascript framework offering a simplified way to use Ajax request like jQuery Ajax.
Using this kind of framework is a good way to simplify your code and to not repeat yourself DRY.
A jQuery version :
<script>
$(document).on('keyup', '#userInput', function(){
var food = $(this).val(); // # <= means ID
$.get('foodstore.php', 'food='+food, function(response){
$('#underInput').html(response);
});
});
</script>
So I am trying to pass back a couple values to a PHP page like this.
function showAccountInfo(obj){
var value = obj.value;
var content = obj.querySelector("option:checked").textContent;
alert("value: " + value + " content: " + content);
if(obj == ""){
return;
}
else {
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) {
document.getElementById("facilities").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getinfo.php?=q"+value+"&c="+content, true);
xmlhttp.send();
}
}
When the alert goes off it shows me the correct values for each variable. However when I pass off that value to getinfo.php and use the variable value to complete a query and echo it out to the page it shows me it as empty.
$q = ($_GET['q']);
$sql = "SELECT *, account.account_name FROM facility "
. "INNER JOIN account ON account.account_id = facility.account_id "
. "WHERE facility.account_id = '".$q."'";
echo $sql;
Result: SELECT *, account.account_name FROM facility INNER JOIN account ON account.account_id = facility.account_id WHERE facility.account_id = ''
I had everything functioning properly prior my previous question.
Your url is incorrectly formatted
Change
xmlhttp.open("GET","getinfo.php?=q"+value+"&c="+content, true);
^
To
xmlhttp.open("GET","getinfo.php?q="+value+"&c="+content, true);
^
Note change of first =
I have a form that is supposed to display a feedback message from the server once it is submitted in <div id="resposta"></div>
I can't use JQuery on my page because it is also using Mootools and it's really a mess to avoid the conflicts with those two (I tried all sorts of things I don't to bother you with). Therefore, I must use pure JavaScript here.
Once the form is submitted (after validation) it calls the function getResposta below:
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
};
function getResposta(){
var resposta = document.getElementById("resposta");
var request = getXmlHttp();
request.open("POST", "thanks.php", true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if (request.readyState != 4) return;
if (request.status == 200) {
resposta.innerHTML = '<p>' + request.responseText + '</p>';
} else {
alert("Erro: "+request.statusText);
}
};
}
}
thanks.php:
<?php
echo "thank you";
?>
It seems that thanks.php isn't being called, although the form is correctly filled in and sent to the server.
I've tried typing in the absolute path to the file but it didn't work. So, what is wrong with this code?
Thanks for any help!
I am changing my question What is missing or wrong in this code When user type something in the textboxt onother texbox supposed to get server time But nothing happens.I am so inexperience with programming.Can you plase help
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
Response.Write(DateTime.Now.ToShortTimeString());
Response.End();
}
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("user").value = xmlHttp.responseText;
}
else {
document.getElementById("label").innerHTML = "wait";
}
xmlHttp.open("GET", "Default.aspx", true);
xmlHttp.send(null);
}
}
</script>
<title></title>
</head>
<body>
<input id="user" type="text" onkeyup="ajaxFunction()"/>
<p>
<input id="time" type="text" /></p>
<div id="label">
</div>
<p>
</p>
</body>
</html>
You misplaced the call to actually start the request
function ajaxFunction() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("user").value = xmlHttp.responseText;
} // closes the if
else {
document.getElementById("label").innerHTML = "wait";
} // closes the else
} // closes the function() for onreadystatechange
// call the stuff
xmlHttp.open("GET", "Default.aspx", true);
xmlHttp.send(null);
}
I am trying to build up an autosuggestion search field similar to Google Suggestion (or Autosuggestion?).
I am using pure javaScript/AJAX and 2 files: index.php and ajax-submit.php (is the file where I will actually query the database). But for moment I am simply echo a text for debugging.
There are a few issues:
Issue 1: The issue is the firebug outputs: xmlhttp is not defined as soon as I type something in the search input [solved, see below].
Issue2: I would like also to echo the content of the search input something like this:
echo $_GET['search_text'];
or
if(isset($_GET['search_text'])) {
echo $search_text = $_GET['search_text'];
}
but I get the following error: *Undefined index: search_text in ajax-submit.php*
So here is my function suggest call:
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
And here is my function suggest():
<script type="text/javascript">
//function does not needs params because is unique to the input search_text
function suggest() {
//browser object check
if(window.xmlHttpRequest) {
xmlhttp = new xmlHttpRequest();
}
else if (window.ActiveXObject) {
//console.log("error");
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//when the onreadystatechange event occurs
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByID('results').innerHTML = xmlhttp.responseText;
}
}//end onready
xmlhttp.open('GET', 'ajax-submit.php', true);
xmlhttp.send();
}//end suggest
</script>
and here is my php ajax-submit file:
<?php
echo 'Something';
?>
Can someone help me debug? It might be a scope issue but I have no clue.
The second question would be how would you normally debug an Ajax request in Firebug?
Thanks
Actually, it is
XMLHttpRequest()
not
xmlHttpRequest()
To have a true cross-browser compliant XHR object creation, go with this:
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
var xhr = ( function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
Use:
new XMLHttpRequest
not
new xmlHttpRequest
I wrote a better implementation: cross-browser/more readable code, function splits. Below is the code. Unfortunately tough reads php echo text it won't read the variable search_text, I don't know why:
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
}
</script>
and HTML code:
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and ajax-submit.php:
<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>