Display PHP output in Ajax Popup - javascript

Hi All! So I'm a noob, and most of my code was done by a programmer for me. I can't get him to help me now.
I have a calculator that displays results (produced by calc.php) without relaoding the page. Demo is here: http://www.roofingcalculator.org/popup/popup.htm
Now I added Ajax popup (contact form) from here: http://dimsemenov.com/plugins/magnific-popup/ and it works.
What I want is to display the results of calc.php inside the Popop, but it does not work.
Details:
When user clicks "Calculate" button, the form sends info to CALC.JS using POST, which then sends info to CALC.PHP and diplays results back on the page with this tag:
<span id="CalcSum">Results:</span>
When I add the SPAN tag to popup, it does not display the result of PHP.
QUESTION How do I display results in AJAX Popup??
Please help - I really appreciate any help - Cheers!
Calc.js content:
var XmlHttp;
function GetXmlHttpObject() {
var XmlHttp = null;
try {
XmlHttp = new XMLHttpRequest();
} catch (e) {
try {
XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return XmlHttp;
}
function StateChanged() {
if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
}
}
function ShowSum(url, params) {
XmlHttp = GetXmlHttpObject();
if (XmlHttp == null)
return;
XmlHttp.onreadystatechange = StateChanged;
XmlHttp.open('POST', url, true);
XmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XmlHttp.setRequestHeader("Content-length", params.length);
XmlHttp.setRequestHeader("Connection", "close");
XmlHttp.send(params);
}
function GetInfo() {var str =
"size1=" + escape(encodeURI(document.getElementById("size1").value)) +
"&size2=" + escape(encodeURI(document.getElementById("size2").value));
ShowSum('http://www.website.com/calc.php', str);
}
calc.php
<?php
$size1_val = empty($_POST['size1']) ? '0' : $_POST['size1'];
$size2_val = empty($_POST['size2']) ? '0' : $_POST['size2'];
$total_size = $size1_val * $size2_val;
print "Result: ". round($total_size). "";
?>
HTML Form:
<table>
<script type="text/javascript" src="calc.js"></script>
<form id="formcalc" action="javascript:GetInfo();" accept-charset="UNKNOWN"
enctype="application/x-www-form-urlencoded" method="post">
<tr>
<td height="24" ><strong>Sizes:</strong>
</td>
<td height="24" valign="top" width="50%">
<input id="size2"/> x <input id="size1" s/> ft.
</td>
</tr>
<tr>
<td COLSPAN="2">
<input name="calc" type="submit" value="Calculate" />
<span id="CalcSum">Results:</span>
</form>
</td>
</tr>
</table>

Add $('.popup-with-form').magnificPopup('open'); to your stateChanged function as below. Works for me on your example. Changed both results spans and opens the pop up.
function StateChanged() {
if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
$('.popup-with-form').magnificPopup('open');
document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
}
}
Update: more documentation here http://dimsemenov.com/plugins/magnific-popup/documentation.html if you need it.

Is the html for the Ajax popup on the same page as the form? If so, add
<span id="CalcSumPopup">Results:</span>
to the popup where you want the result to go and add
document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
after document.getElementById("CalcSum").innerHTML = XmlHttp.responseText; in Calc.js.
If it is not on the same page this will not work.
EDIT:
This works because id's are meant to be unique. getElementById will find the first occurrence of the specified id and then stop, so if you want multiple places to be changed you need to give them unique id's.

Related

$_POST not returning a value

I've been searching for an answer to this for several days now, but if I missed the answer in another post, let me know.
I'm trying to get into Ajax, so I have a very simple form in my index.php, with separate php and javascript files:
index.php
<div id="ajax-test">
<form action="ajax/ajax.php" method="POST">
<textarea name="someText" id="some-text" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
main.js:
function getXMLHttpRequestObject() {
var temp = null;
if(window.XMLHttpRequest)
temp = new XMLHttpRequest();
else if(window.ActiveXObject) // used for older versions of IE
temp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
return temp;
}// end getXMLHttpRequestObject()
function loadDoc() {
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
};
ajax.open("POST", "ajax/ajax.php", true);
ajax.send();
}
ajax.php:
<?php
print_r('\'' . $_POST['someText'] . '\' is what you wrote');
?>
Whenever I try to print, it prints: " '' is what you wrote " - what am I missing/not doing/doing incorrectly that isn't allowing me to access the content of someText? I've changed my naming convention, swapped from single quote to double quote, tried GET instead of POST, but nothing worked.
You can try to set a header request and also put the data inside the send. Here an example as like as-
ajax.open("POST", "ajax/ajax.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send("someText="+document.getElementById('some-text').value);
This is probably beacuse of the error
Undefined index: someText in C:\xampp\htdocs\ssms\sandbox\ajax\ajax.php on line 3
You had a couple of issues with your code which i don't have time to list out now. This should work fine, plus i used the onkeyup() function to display the text live without even clicking on the submit button.
The Index File
<div id="ajax-test">
<form method="POST" onsubmit="return false;">
<textarea onkeyup="loadDoc()" name="someText" id="someText" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
<script type="text/javascript" src="main.js"></script>
The Main Javascript file
function _(x) {
return document.getElementById(x);
}
function ajaxObj ( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function loadDoc() {
var someText = _("someText").value;
var ajax = ajaxObj("POST", "ajax/ajax.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
}
ajax.send("someText="+someText);
}
The PHP AJAX File
if(isset($_POST['someText'])){
$someText = $_POST['someText'];
echo "\"$someText\"" . ' is what you wrote';
exit();
} else {
echo "An error occured";
exit();
}

Submitting a form using AJAX

I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>

auto Submit form on max length, - add a java script code for existing one

i am trying to auto submit form when the input reaches 7 characters. i have tried few java script codes, but it is spoiling my script functioning.
can any one please help me in this.....
<script type="text/javascript">
var url = "GetCustomerData.php?id="; // The server-side script
function handleHttpResponse() {
if (http.readyState == 4) {
if(http.status==200) {
var results=http.responseText;
document.getElementById('divCustomerInfo').innerHTML = results;
}
}
}
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
http.open("GET", url + escape(sId), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
<form id="form_home">
<p>Enter customer ID number to retrieve information:</p>
<p>Customer ID: <input type="text" maxlength="7" id="txtCustomerId" value="" /></p>
<p><input type="submit" value="Submit" onclick="requestCustomerInfo()" /></p>
</form>
<div id="divCustomerInfo"></div>
Here is the code that will submit the form when the text box reaches 7 chars:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
document.getElementById('form_home').submit();
}
});
Here is a demo of it working:
http://jsfiddle.net/TuVN2/1/
Looking at your markup, I guess you want to run requestCustomerInfo() and not submit. If you submit the response will never be handled. To do this you would move the function call into the keyup handler:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
requestCustomerInfo();
}
});
I would also not recommend hand rolling your ajax handler. Consider using a library like jQuery.

why statement xmlhttp.onreadystatechange cause this program work once only?

i make a simple REST web service consumer using HTML and javascript. here's the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="javascript">
var xmlhttp;
function getdetails() {
var empno = document.getElementById("empno");
var url = "http://localhost:8080/TestWS1/rest/hello/" + empno.value;
xmlhttp = new XMLHttpRequest(); //#slaks: i put it here
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
var empname = document.getElementById("empname");
var age = document.getElementById("age");
if (xmlhttp.readyState == 4) {
//alert(xmlhttp.status);
if ( xmlhttp.status == 200) {
var det = eval( "(" + xmlhttp.responseText + ")");
if (det.age > 0 ) {
empname.value = det.name;
age.value = det.age;
}
else {
empname.value = "";
age.value ="";
alert("Invalid Employee ID");
}
}
else
alert("Error ->" + xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
<h1>Call Employee Service </h1>
<table>
<tr>
<td>Enter Employee ID : </td>
<td><input type="text" id="empno" size="10"/> <input type="button" value="Get Details" onclick="getdetails()"/>
</tr>
<tr>
<td>Enter Name : </td>
<td><input type="text" readonly="true" id="empname" size="20"/> </td>
</tr>
<tr>
<td>Employee Age : </td>
<td><input type="text" readonly="true" id="age" size="10"/> </td>
</tr>
</table>
</body>
</html>
that code only show an employee name and age from the REST web service on the HTML textbox when a getDetail button is pressed. the parameter is employee number (empNo).
the main problem is, why this code only works once??
for example, if i put 1 on the empNo textbox and i pressed getDetail button, for the first time only, it will display the name and the age of the employee based on employee number that i was entered before. but for the second or third i press the getDetail button, it not works anymore. i've tried to give some alert to help me for debugging that code but the result is xmlhttp.onreadystatechange = function() only works once on the first time i pressed the getDetail button.
has anyone know how to solve this problem?? really stuck in here.. thanks a lot for helping me..
FYI: here's my web service code:
package com.webservices.TestWS1;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
//#Path("/hello")
#Path("/hello/{empno}")
public class Hello {
#GET // this method process GET request from client
#Produces("application/json") // sends JSON
public String getJson( #PathParam("empno") int empno) { // empno represents the empno sent from client
switch(empno) {
case 1 :
return "{'name':'George Koch', 'age':58}";
case 2:
return "{'name':'Peter Norton', 'age':50}";
default:
return "{'name':'unknown', 'age':-1}";
} // end of switch
} // end of
}
You can't re-use XMLHttpRequests.
You need to create a new XMLHttpRequest for each request.
Get rid of your init() function.
Put this between the script tag
function getdetails() {
xmlhttp = new XMLHttpRequest();
var empno = document.getElementById("empno");
var url = "http://localhost:8080/TestWS1/rest/hello/" + empno.value;
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
var empname = document.getElementById("empname");
var age = document.getElementById("age");
if (xmlhttp.readyState == 4) {
//alert(xmlhttp.status);
if ( xmlhttp.status == 200) {
var det = eval( "(" + xmlhttp.responseText + ")");
if (det.age > 0 ) {
empname.value = det.name;
age.value = det.age;
}
else {
empname.value = "";
age.value ="";
alert("Invalid Employee ID");
}
}
else
alert("Error ->" + xmlhttp.responseText);
}
}
}
A bit late this answer, but to whom it may concern ...
One need to to assign the callback function before one send the request.
So it should be likes this
var url = "http://localhost:8080/TestWS1/rest/hello/" + empno.value;
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange = function() {
... some code here
}
xmlhttp.send(null);

There is a long suffering, but I can not do cross- site request

What now is:
A page on localhost, which sends a request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script language="javascript" type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', 'http://www.3dfind.ru/site/js.js');
document.getElementsByTagName('head')[0].appendChild(script);
</script>
</head>
<body>
<form method="get">
<div id='searchform'>
<table>
<td>
<input name='q' id='searchinput' type='text' value=''>
</td>
<td>
<select name='type' id='searchselect'>
<option value='1'>Val 1</option>
</select>
</td>
<td>
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
</td>
</table>
</form>
<div id='ResponseDiv'>
</div>
</body>
</html>
Then there js script on the server, which receives the request:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
var params = 'q=' + encodeURIComponent(q) + '&type=' + encodeURIComponent(type) + '&search=' + encodeURIComponent(s)
xmlHttp.open("GET", '/result.php?'+params, true)
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
If the file result.php search on the server, you get a url:
http://3dfind.ru/site/result.php?q=%E4%F4%E4%E4%F4%E4&type=1&search=%CF%EE%E8%F1%EA%21
Also in result.php I accept the GET- request :
$var = #$_GET['q'] ;
$s = $_GET['s'] ;
$typefile = $_GET['type'];
What am I doing wrong ?
Alright my man, I think you're a bit confused. Your HTML contains
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
And your Javascript contains
function MakeRequest()
but you say "Then there js script on the server, which receives the request:"
The Javascript should be on the client and sends the request.
Then I'm not even sure what you're trying to do and what's going wrong. Are you getting errors? Is it supposed to do something that it isn't?
Back to basics: use Firefox and install Firebug. Enable the "console". Open your page and do what you're trying to do. If you have Javascript errors, they'll show in the console. You can open every ajax request in the console as well so you can see if you're getting a server side error.
Yeah, I'm a bit confused what you're asking, here is a reference you may look into for cross-site xmlhttprequests here. There is another good reference to cross-site requests here also
From your other question ("cross-site request") I think I understand what you're trying to do. I think you're trying to get the results from "results.php" which is hosted in a different server.
What you need to do is change your MakeRequest() function. Instead of
xmlHttp.open("GET", '/result.php?'+params, true)
it should be
xmlHttp.open("GET", 'http://URL_OF_OTHER_SERVER/result.php?'+params, true);
Hope this helps.

Categories

Resources