not getting ajax response from server side file - php

as u can see below I am trying to change part o f my page without reload all page using ajax but I am not gettign any response
I am working on local host xampp and both files are in same directory
I also tired to palce files on host and nothing happen
i did not get even an error while connecting to the database in the accdata.php file when I place them on server while there is no database
I trid a lost to change the way of ponting the url part of xmlhttp.open
like file:///C:/xml/dineshkani.xml
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
</head>
<body align="left">
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
<script>
function SendForm()
{
alert("Hello! SendForm start");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
alert("Hello! going to send ajax");
xmlhttp.open("POST","AccData.php", true);
xmlhttp.send(document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
alert(document.getElementById("AccNum").value);
alert("Hello! SendForm end");
}
</script>
</body>
</html>
accdata.php
<?php
alert("Hello! php start processing");
echo "start";
$AccountNumber = $_POST['AccNum'];
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
alert("Hello! connected to oracle");
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:AccNum';
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':AccNum', $AccountNumber); // binds the parameter
oci_execute($stid); // executes the query
echo $AccountNumber;
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>

The ajax function is only sending a value rather than a post variable with associated value. Try along these lines - tidied it up a little but the important bit is the name=value in the parameters send via ajax and setting the Content-Type header often helps with stubborn xhr requests.
The javascript needn't be in the body - hence I moved that to the head section of the document.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
<script>
function SendForm(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open( "POST", "AccData.php", true );
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send( 'AccNum='+document.getElementById("AccNum").value );
}
</script>
</head>
<body>
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
</body>
</html>
A basic ajax function which can be re-used merely changing the parameters when it gets called.
function ajax(method,url,parameters,callback){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response );
};
var params=[];
for( var n in parameters )params.push( n+'='+parameters[n] );
switch( method.toLowerCase() ){
case 'post':
var p=params.join('&');
break;
case 'get':
url+='?'+params.join('&');
var p=null;
break;
}
xhr.open( method.toUpperCase(), url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
function cbaccdata(r){ document.getElementById('AccNum').innerHTML=r; }
function sendForm(){
ajax.call( this, 'post','accdata.php',{ 'AccNum':document.getElementById("AccNum").value },cbaccdata );
}

Related

How to change Background color of HTML DOC using AJAX Post Request:

I am trying to create an HTML document that contains a button “Request color”. Whenever a user clicks on “Request color”, the page performs an Ajax POST request to the URL color-service.php. The color-service.php file handles the POST request and returns a JSON containing a random color, for example: { color: "red" }. The Ajax response is then used to change the background of the color.html page accordingly.
Current HTML:
<!Doctype HTML>
<html>
<head>
<title>Random Color Changer</title>
</head>
<body style="<? echo $color?>">
<h1>Random Color Generator</h1>
<p id="color"></p>
<button type="button" onclick="changeColor()">Request Color</button>
<script>
function changecolor() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById.color = this.responseText;
}
}
};
xhttp.open("GET", "color-service.php", true);
xhttp.send();
}
</script>
</body>
</html>
Current PHP:
<?php
$list = array('red', 'blue', 'yellow', 'pink', 'green');
$i = array_rand($list);
$color = $list[$i];
?>
<body style="background-color:<? echo $color?>">
Make sure you're using background-color otherwise the browser won't know what you want coloured and in order for $color to do anything, you need to define it before you use it in your HTML.
echo $color = $list[$i];
And make sure color-serivce.php actually returns the random colour using echo, otherwise it will just be a blank page.
document.body.style.backgroundColor = this.responseText;
The JavaScript attribute you need to use is .style.backgroundColor and you need to use otherwise the browser doesn't know what you want coloured. Just color on it's own won't work for what you want it to (it will set the colour of the text).
Also you've give your function two different names; in one case it says changeColor() and in another it doesn't have the capital 'C'.
There are several problems here, but what you want is this:
HTML
<!Doctype HTML>
<html>
<head>
<title>Random Color Changer</title>
</head>
<body id="fillme">
<h1>Random Color Generator</h1>
<p id="color"></p>
<script>
function changecolor() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "color-service.php", true);
xhttp.onload = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('fillme').style.backgroundColor = this.responseText;
}
};
xhttp.send();
}
changecolor();
</script>
<button type="button" onclick="changecolor();">Request Color</button>
</body>
</html>
PHP
<?php
$list = array('red', 'blue', 'yellow', 'pink', 'green');
$i = array_rand($list);
$color = $list[$i];
echo $color;
?>

Render TeeChart for PHP in another page

I am a newbie on TeeChart for PHP.
All examples I have found are rendering the chart on the same php file where it has been created.
I would like to build the chart using a PHP script, which receives some parameters via AJAX, and render the chart on the page which has generated the AJAX call.
Is that possible? Any example on that?
Best regards.
Jayme Jeffman
Here a simple example:
getchart.php:
<?php
// get the q parameter from URL
$q = $_REQUEST["q"];
//Includes
include "../../sources/TChart.php";
$chart1 = new TChart(600,450);
$chart1->getChart()->getHeader()->setText($q);
$chart1->getAspect()->setView3D(false);
$line1 = new Line($chart1->getChart());
$line1->setColor(Color::RED());
$chart1->addSeries($line1);
// Speed optimization
$chart1->getChart()->setAutoRepaint(false);
for($t = 0; $t <= 10; ++$t) {
$line1->addXY($t, (10 + $t), Color::RED());
}
$chart1->getChart()->setAutoRepaint(true);
$chart1->render("chart1.png");
$rand=rand();
echo "chart1.png?rand=".$rand;
?>
Test.html:
<!DOCTYPE html>
<html>
<head>
<script>
function showChart(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var image = document.getElementById("get_img");
image.src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getchart.php?q="+str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>Enter the chart title below:</b></p>
<form>
Chart title: <input type="text" onkeyup="showChart(this.value)">
</form>
<p><img id="get_img" /></p>
</body>
</html>

AJAX document.getElementById not working when pass through parameters

I'm writing an AJAX code that gets input from the users, and outputs the results, and it works when I'm setting the variable called text inside the function, but when I'm passing it through it doesn't work. Please take a look, I've taken all the irrelevant codes out, so it's short.
Code when I'm not passing it through the parameter:
<script type = "text/javascript">
function process(){
text = 'userInput';
food = encodeURIComponent(document.getElementById(text).value);
}
</script>
<html>
<body onload="process()">
</body>
</html>
Code when I'm passing it through the parameter:
<script type = "text/javascript">
function process(text){
food = encodeURIComponent(document.getElementById(text).value);
}
</script>
<html>
<body onload="process('userInput')">
</body>
</html>
I did document.write both times to make sure that the variable is really 'userInput', and both times, whether I'm passing it through or setting it inside the function, it printed out fine, so I'm not sure what the problem is. If you know what's wrong, please let me know. Thank you.
The whole code:
functions.js:
var xmlHttp = createXmlHttpRequestObject();
//****************************************************************AJAX
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("Not xmlHttp!")else
return xmlHttp;
}
//****************************************************************AJAX
function process(IDName, passTo, output) {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
get = encodeURIComponent(document.getElementById(IDName).value);
xmlHttp.open("GET", passTo + get, true);
xmlHttp.onreadystatechange = handleServerResponse(output);
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
//****************************************************************AJAX
function handleServerResponse(output) {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById(output).innerHTML = message;
setTimeout('process()', 1000);
} else {
alert('xmlHttp.status does not equal 200!');
}
}
}
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','beef','ham');
if(in_array($food,$foodArray))
echo 'We do have '.$food.'!';
elseif ($food=='')
echo 'Enter a food';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
test5.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<body onload="process('userInput','foodstore.php?food=','underInput')">
<h3>The Chuff Bucker</h3>
Enter the food you would like to order:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
</html>
I just ran this test on your (modified) code and it worked as expected.
<script type = "text/javascript">
function process(text){
alert(text);
food = encodeURIComponent(document.getElementById(text).value);
alert(food);
}
</script>
<html>
<body onload="process('userInput')">
<input id="userInput" value="yummy" />
</body>
</html>
You're performing handleServerResponse(output); when you assign the onreadystatechange handler, not when the event occurs. You need to delay calling the function until the event occurs:
xmlHttp.onreadystatechange = function() {
handleServerResponse(output);
};

unable to pass variable to other page using ajax

I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>

PHP $_GET with Ajax/Jquery Request

I am trying to set a variable $id=$_GET["categoryID"]. I cannot get it to work. I believe it has to do with the the Ajax request. But I don't know how I have to format it so that it will work in conjunction with that request. I need the variable for a mysql query. Any help is greatly appreciated. This is over my head and have been struggling with it for days. I have tried both GET and POST. Thanks.
I have distilled the page down to this...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test $_GET</title>
</head>
<body>
<?php
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$id = $_GET["categoryID"];
//$id=3;
}
?>
print_r($_GET) = <?php print_r($_GET); ?>
<br />
print_r($id) = <?php print_r($id); ?>
</body>
</html>
Here is the resulting page....
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test $_GET</title>
</head>
<body>
print_r($_GET) = Array
(
[categoryID] => 1001
)
<br />
print_r($id) =
</body>
</html>
Here is the whole page....
<?php
if (#$_REQUEST['ajax']) {
$link = $nm33;
if ($link == false)
trigger_error('Connect failed - ' . mysql_error(), E_USER_ERROR);
$connected = mysql_select_db('nm', $link);
if ($connected) {
//How do I set $id = $_GET["categoryID"] It fails to set the variable.
$id =$_GET["categoryID"];
// $id=1;
// It will work as $id=1
$results = mysql_query('select * from selectMenu where categoryID= \'' . $id . '\' AND category="' . strtolower(mysql_real_escape_string(strip_tags($_REQUEST['category']))) . '"');
//////////
$json = array();
while (is_resource($results) && $row = mysql_fetch_object($results)) {
//$json[] = '{"id" : "' . $row->id . '", "label" : "' . $row->label . '"}';
$json[] = '"' . $row->label . '"';
}
echo '[' . implode(',', $json) . ']';
die(); // filthy exit, but does fine for our example.
} else {
user_error("Failed to select the database");
}
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="js/select-chain.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
<!--
$(function () {
var cat = $('#categorySelect');
var el = $('#elementSelect');
var attr = $('#attributeSelect');
el.selectChain({
target: attr,
url: 'select-menu.php',
data: { ajax: true, anotherval: "anotherAction" }
});
// note that we're assigning in reverse order
// to allow the chaining change trigger to work
cat.selectChain({
target: el,
url: 'select-menu.php',
data: { ajax: true }
}).trigger('change');
});
//-->
</script>
<link href="selectMenu.css" rel="stylesheet" type="text/css" />
<form action="performance-models.php" method="get">
<select name="category" class="dropdown" id="categorySelect">
<option selected="selected">Select Your Vehicle</option>
<?php do { ?>
<option> <?php echo $row_rsMake['make']; ?></option>
<?php } while ($row_rsMake = mysql_fetch_assoc($rsMake)); ?>
</select>
<select name="model" class="dropdown" id="elementSelect">
<option selected="selected">Select Model</option>
<option>[none selected]</option>
</select>
<select name="appYear" class="dropdown" id="attributeSelect" >
<option selected="selected"> </option>
<option>[none selected]</option>
</select>
<input type="submit" value="Go">
</form>
<p><br />
<br />
print_r($_GET) = <?php print_r($_GET); ?> <br />
print_r($_REQUEST) = <?php print_r($_REQUEST); ?><br />
echo $_REQUEST['categoryID'] <?php echo $_REQUEST['categoryID'];?>
</p>
Here is select-chain.js
(function ($) {
$.fn.selectChain = function (options) {
var defaults = {
key: "id",
value: "label"
};
var settings = $.extend({}, defaults, options);
if (!(settings.target instanceof $)) settings.target = $(settings.target);
return this.each(function () {
var $$ = $(this);
$$.change(function () {
var data = null;
if (typeof settings.data == 'string') {
data = settings.data + '&' + this.name + '=' + $$.val();
} else if (typeof settings.data == 'object') {
data = settings.data;
data['category'] = $$.val();
data['model'] = $$.val();
data['year'] = $$.val();
}
settings.target.empty();
$.ajax({
url: settings.url,
data: data,
type: (settings.type || 'get'),
dataType: 'json',
success: function (j) {
var options = [], i = 0, o = null;
for (i = 0; i < j.length; i++) {
// required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
o = document.createElement("OPTION");
o.value = typeof j[i] == 'object' ? j[i][settings.key] : j[i];
o.text = typeof j[i] == 'object' ? j[i][settings.value] : j[i];
settings.target.get(0).options[i] = o;
}
// hand control back to browser for a moment
setTimeout(function () {
settings.target
.find('option:first')
.attr('selected', 'selected')
.parent('select')
.trigger('change');
}, 0);
},
error: function (xhr, desc, er) {
// add whatever debug you want here.
alert("an error occurred here");
}
});
});
});
};
})(jQuery);
A $_GET parameter is passed in the URL so for this;
http://www.google.com/?q=search
The parameter $_GET['q'] would be equal to 'search'
So when you perform your AJAX request you need to specify the parameters in the URL.
EDIT:
Try getting rid of your HTTP_X_REQUESTED_WITH statements. The request is probably safe enough without those kind of checks. Just simplify it to:
if ( isset( $_GET["categoryID"] ) ) {
$id = $_GET["categoryID"];
}
There is no need for:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
You can just use:
$id = isset($_GET["categoryID"]) ? intval($_GET["categoryID"]) : 0;
Which is the same as (but shorter...):
if (isset($_GET["categoryID"]))
{
$id = intval($_GET["categoryID"]);
}
else
{
$id = 0;
}
If you want to check if a request was made via ajax, you would have to rewrite your script as the whole header section would not be needed. Instead you could call this script from your page, set a variable in the page itself and if that variable is not set in the script, it's an ajax call. Obviously this is just a simple example.
Edit: The plugin does not mention what the default type of the request is, but that could very well be POST so you could try to add type: "post" to the options of selectChain.
And to make sure that your response is well-formed json (when you get there...) I would also recommend you use json_encode, so:
echo json_encode($json);
die(); // filthy exit, but does fine for our example.
Edit 2: I just noticed another problem: Nowhere is the categoryID being added to the data section in the ajax:
You are requesting / posting to (???) : select-menu.php (notice, no query string!)
The data you are sending is: { ajax: true, anotherval: "anotherAction" } or { ajax: true}
So there is no way that categoryID is ever going to show up in select-menu.php.
The most logical thing to do, would be to add the selected category to the data section:
data: { "ajax": true, "anotherval": "anotherAction", "categoryID": cat }
and:
data: { "ajax": true, "categoryID": cat }
With jQuery you can use jQuery.get() or add a type='GET' parameter to jQuery.ajax(). Some example:
jQuery(function($) {
$.ajax({
url : 'your-page.php',
type : 'GET',
data : {
'paramName' => 'paramValue',
'foo' => 'bar'
},
success : function(data) {
// do something in the callback function
}
});
});
You need to pass the value in the jQuery.get():
$.get('yourphppage.php', { categoryID : 1234 }, function(data) {
alert(data);
});
In your php just echo right back your cateogryId to see if it is working
<?php echo $_GET['categorID'] ?>

Categories