6 Replies - 640 Views - Last Post: 13 May 2013 - 05:01 PM

#1 WastedPotential  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 21-April 13

I have a bug, but can't find it. Please help.

Posted 13 May 2013 - 12:02 PM

This was for an assignment I did for class, which is now over, but I would like to figure out how to fix it. I'll include my javascript, html, and php. I don't have access to the school server now that class ended, so I can't debug it properly.

I know my actual javascript was alright, but when I tried to make ajax calls is where it stopped working.
//Add Ajax

function parseResult(){
	if (this.readyState == 4 && this.status == 200)
	{
		var results = document.getElementById("myResults");
		results.innerText = this.responseText;
	}

}

function makeAjaxRequest()	{
	var myAjax = new XMLHttpRequest();
	/*
	if window.XMLHttpRequest)
	{
		myAjax = new XMLHttpRequest();
	}else{
		myAjax = new ActiveXObject("Microsoft.XMLHTTP");
	}
	*/
	
	myAjax.onreadystatechange = parseResult;
//	{
//		if (myAjax.readyState==4 && myAjax.status==200)
//		{
//			document.getElementById("myResults").innerHTML=myAjax.responseText;
//		}
//	}
	
	myAjax.open("POST", "Calc.php");
	myAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	myAjax.send(getValues());
}

function getValues(){
	
	/*
	function getAge() {
	
		//alert("Hello");
		var age = document.getElementById("mAge").value;
		//document.getElementById("mAge").value = age;
		document.getElementById("myAge").innerHTML = age;
	
	}
	function getPayment() {
	
		var amount = document.getElementById("mAmount").value;
		//document.getElementById("mAmount").value = amount;
		document.getElementById("myAmount").innerHTML = amount;
	}

	function getRate() {
		var rate = document.getElementById("mRate").value;
		document.getElementById("myRate").innerHTML = amount;
	}
	*/
	
	var age = document.getElementById("mAge").value;
	//document.getElementById("mAge").value = age;
	document.getElementById("myAge").innerHTML = age;
		
	var amount = document.getElementById("mAmount").value;
	//document.getElementById("mAmount").value = amount;
	document.getElementById("myAmount").innerHTML = amount;
		
	var rate = document.getElementById("mRate").value;
	document.getElementById("myRate").innerHTML = rate;
	var values = encodeURI(age) + " & " + encodeURI(amount) + " & " + encodeURI(rate);
	
	return values;
}



Here's my PHP, which i suck at. SO there could be a problem here too that i am missing.
 <?php
	// Get the values from Form when submitted
	if (isset($_POST["SendSubmit"])) {
		$errs = array(); 
		$errs["wrong_rate"] = $rate = ValidateRate($_POST["mRate"]);
		$errs["wrong_age"] = $age = ValidateAge($_POST["mAge"]);
		$errs["wrong_amount"] = $amount = ValidateAmount($_POST["mAmount"]);

		
		if (invalid($errs)) { 
			// Print error message
			errorMessage($errs);
		} else {
			// Calculate
	} else {
		
	}	
	
	function errorMessage($elements) {
		$msgError = '<div id="error_message"><p><span id="err">Error input found!</span> Please review:</p><ul>';
		foreach ($elements as $value) {
			if ($value != "") {
				$msgError .= '<li>';
				$msgError .= $value;
				$msgError .= '</li>';
			}
		}
		$msgError .= '</ul></div>';
		echo $msgError;
	}
	
	function invalid($elements) {
		$isInvalid = false;
		foreach ($elements as $value) {
			if ($value != "") {
				$isInvalid = true;	
			}
		}
		return $isInvalid;
	}
	
	function ValidateRate($rate) {
		$returnMsg = "";
		if ($rate == "") {
			$returnMsg = "Rate is empty";	
		} elseif ($rate < 0) {
			$returnMsg = "Rate cannot be negative number";	
		} elseif (!is_numeric($rate)) {
			$returnMsg = "Rate must be a number";	
		}
		return $returnMsg;
	}
	
	function ValidateAge($age) {
		$returnMsg = "";
		if ($age == "") {
			$returnMsg = "Age is empty";	
		} elseif ($age < 0) {
			$returnMsg = "Age cannot be negative number";	
		} elseif (!is_numeric($age)) {
			$returnMsg = "Age must be a number";	
		}
		return $returnMsg;
	}
	
	function ValidateAmount($amount) {
		$returnMsg = "";
		if ($amount == "") {
			$returnMsg = "Amount is empty";	
		} elseif ($amount < 0) {
			$returnMsg = "Amount cannot be negative number";
		} elseif (!is_numeric($amount)) {
			$returnMsg = "Amount must be a number";	
		}
		return $returnMsg;
	}
	
	?>

// the HTML code starts here
<html>
	<head>
		<meta charset="utf-8">
		<title>Retirment Calculator</title>
		<script type="text/javascript" src="calc.js"></script>
		
	</head>

	<body>
		<h2>The Retirement Calculator</h2>
		<h4>(Retirement Calculator assumes retirement at 65 and living til 100 years old)</h4>
		<form <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "POST" onchange="calculateClick()">
			Age: <input id="mAge" name="age" type="text" value="<?php if (isset($age)) {echo $_POST['mAge'];} ?>" title="Enter age here" onblur="validateAge();"/><br/>
			
			<div style="color:red;" id="ageErrorMsg"></div><br/>
			Payment: <input id="mAmount" name="amt" type="text" value="<?php if (isset($amount)) {echo $_POST['mAmount'];} ?>" title="Enter payment here" onblur="validateAmount();"/><br/>
			
			<div style="color:red;" id="amtErrorMsg"></div><br/>
			Interest: <input id="mRate" name="rate" type="text" value="<?php if (isset($rate)) {echo $_POST['mRate'];} ?>" title="Enter interest rate here" onblur="validateRate();"/><br/>
			
			<div style="color:red;" id="rateErrorMsg"></div><br/>
			
		</form>
		<p>
			Your information:<br/><br/>
			Your age: <span id="myAge">[undefined]</span><br/>
			
			Your amount: <span id="myAmount">[undefined]</span><br/>
			
			Your return: <span id="returnResult">[undefined]</span><br/>
			
			Amount you may withdraw each year: <span id="withdrawnResult">[undefined]</span><br/>
			
			Your interest will be: <span id="myRate">[undefined]</span>
			
			Breakdown by year: <span id="breakdownMsg">[undefined]</span>
            
		</p>
	</body>
</html>



It all looks alright to me, but my professor said that the ajax call didn't work. Im sure its just a novice error, but I'm new to web stuff. Thanks for any help you can give. Im sure you guys will catch it quickly.

Is This A Good Question/Topic? 0
  • +

Replies To: I have a bug, but can't find it. Please help.

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3515
  • View blog
  • Posts: 10,140
  • Joined: 08-June 10

Re: I have a bug, but can't find it. Please help.

Posted 13 May 2013 - 12:25 PM

there are several issues.
- innerText is IE-only
- look carefully at the string you pass to XMLHttpRequest.send()
- because of the former, PHP receives the wrong data
- you need to define functions before you use them
- you must not embed an <html> element inside an already existing HTML page
Was This Post Helpful? 0
  • +
  • -

#3 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3716
  • View blog
  • Posts: 5,976
  • Joined: 08-June 10

Re: I have a bug, but can't find it. Please help.

Posted 13 May 2013 - 01:05 PM

View PostDormilich, on 13 May 2013 - 07:25 PM, said:

- you need to define functions before you use them

That's only partially right, though. At least for PHP.

In PHP, functions only need to be defined in the script file they are called in. If you include a function from another file, it has to happen before it is called, or PHP would have no record of it existing. But if you call a function that is defined in the same file, then PHP will have already parsed that file and knows it will be defined, so that's fine. - The error is a runtime error, not a parse error.

One obvious pitfall in this, though, is that functions must be unconditionally defined for this to work. If they belong to a in if condition, PHP won't make it available until after the statement has been executed. (Even if the condition is a fixed True value.)
Was This Post Helpful? 0
  • +
  • -

#4 WastedPotential  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 21-April 13

Re: I have a bug, but can't find it. Please help.

Posted 13 May 2013 - 01:12 PM

So what can I do to fix the error? I need to change innerTEXT to ineerHTML, I Need to fix where I open the form twice (I just caught that), but I'm not sure what is wrong with the XMLhttprequest.send() method. Could you be more precise? Like I said, Im new to web programming, and I'm not very good at all. Thanks again for the quick replies
Was This Post Helpful? 0
  • +
  • -

#5 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3716
  • View blog
  • Posts: 5,976
  • Joined: 08-June 10

Re: I have a bug, but can't find it. Please help.

Posted 13 May 2013 - 01:23 PM

The first thing I'd suggest is replacing the encodeURI calls in the function that generates your data string with encodeURIComponent. The latter is meant to encode values in query strings, while the former is meant more for whole URIs.

Then I would suggest using Firebug (or the equivalent for your browser) to check out the actual string being passed through the request. See if it's correct. (We can help with that, if you post it here.)
Was This Post Helpful? 0
  • +
  • -

#6 WastedPotential  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 21-April 13

Re: I have a bug, but can't find it. Please help.

Posted 13 May 2013 - 01:51 PM

View PostAtli, on 13 May 2013 - 01:23 PM, said:

The first thing I'd suggest is replacing the encodeURI calls in the function that generates your data string with encodeURIComponent. The latter is meant to encode values in query strings, while the former is meant more for whole URIs.

Then I would suggest using Firebug (or the equivalent for your browser) to check out the actual string being passed through the request. See if it's correct. (We can help with that, if you post it here.)


What exactly do you need me to post? I included most of my javascript and all of my php. I'll change the URI stuff though.
Was This Post Helpful? 0
  • +
  • -

#7 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3716
  • View blog
  • Posts: 5,976
  • Joined: 08-June 10

Re: I have a bug, but can't find it. Please help.

Posted 13 May 2013 - 05:01 PM

The easiest way to see if something is wrong with the query string you are passing to PHP is to actually run the code and use the browsers developer tools to inspect the AJAX request. In Firefox that tool is Firebug. It lets you examine exactly what your browser is sending to PHP.

But, even so, there are a few things about your query string I can tell you from looking at the code. This is what you do:
encodeURI(age) + " & " + encodeURI(amount) + " & " + encodeURI(rate);


However, the format of a query string should be more like this:
key1=value1&key2=value2&key3=value3


Do you see the problem? All you will end up with is something like:
value1 & value2 & value3


PHP won't know what to do with that. It needs both the key and the value, and it isn't expecting the spaces around the ampersand.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1