ajax call can't retrieve data from database - javascript

i am new to ajax.Here i am trying to retrieve data from mysql database.But all i am getting here is an empty array and a notice saying undefined index q on line 2 .Can't figure out what might be the problem behind this.Any help will be appreciated.Here i am using a database which has three column to each row(id,name,age).
i am having an error .saying i am sending a request to getuser.php.Though my page name is callajax.php.From where this getuser.php coming from?It gives me desired output when i changed the file name to getuser.php.I don't understand.why callajax.php wouldn't work?
html:
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","callajax.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">al zami rahman</option>
<option value="4">junayed hasan</option>
<option value="5">tapos alam</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
callajax.php page:
$m=$_GET['q'];
$pdo=new PDO("mysql:host=localhost;dbname=ajax",'root','');
$conn=$pdo->prepare('SELECT age FROM people WHERE id=?');
$conn->bindValue(1,$m);
if($conn->execute()){
$result=$conn->fetchAll();
print_r($result);
}

Related

How to make Ajax request from database periodic

I got this code from w3schools. I have edited it and it is connected to a php file which displays all messages whenever a person is selected. The problem is when i change add a new message to the database, it isnt shown unless i change the person, or select the same person again. I wanted to add a periodic function that automatically sends request to db.php after every second and displays all updated messages. But as i dont have much knowledge of AJAX, here i am. can anyone edit the code and do it. Thanks
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","db.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
Add an id to the select element.
<select name="users" id="users" onchange="showUser(this.value)">
Add the following code just before the body closing tag:
<script>
setInterval(function(){
var e = document.getElementById("users");
var selectedId = e.options[e.selectedIndex].value;
showUser(selectedId);
}, 3000);
</script>
It will send the request after every 3 seconds and will update the content.
What you want to achieve is called polling via AJAX - a better way to go would be Web-Realtime. Technologies in this context are WebSockets or Server-Sent-Events which got introduced in 2014 with HTML5.
A polling javascript module based on Jquery for your needs could look like:
var Polling = (function ($scope) {
var doPoll;
var _callback = function (res) {
console.log(res);
};
var start = function start(url, params, cb, period) {
period = period || 5000;
doPoll = true;
if (cb && typeof cb == 'function') {
_callback = cb;
}
_poll(url, params, period);
};
var stop = function () {
doPoll = false;
};
function _poll(url, params, period) {
Object.assign(params, {polling: true});
$.post(url, params)
.done(function (res) {
_callback(res);
if (!doPoll) return;
setTimeout(function () {
_poll(url, params, period)
}, period);
});
}
return {
start: start,
stop: stop
}
})();
After including jquery and the above script to start polling behaviour (sending a post request every 5th second) simply do:
Polling.start("path-to-your-php-file.php",
{"your": "param"},
function (response) {
// handle the response here
console.log(response);
}
);
To stop it do:
Polling.stop();
Try it out here:
I added a userChanged() function to handle the onchange event of the <select> element. In the function I check to see if the repeating interval has been set and if it is then clear it and set a new one. The interval is set to go off every 1 second, and it passes the variable str into the function showUser(str).
Here is the code:
<html>
<head>
<script>
var timer = false;
function userChanged(str)
{
// if timer is not false it means it is set
if(timer)
{
clearInterval(timer);
timer = false;
}
// When str is '' that means the user has selected 'Select a person:'
if(str != '')
{
timer = setInterval(showUser, 1000, str);
}
else document.getElementById("txtHint").innerHTML = "";
}
function showUser(str)
{
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 (this.readyState == 4 && this.status == 200)
{
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","db.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="userChanged(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>

Why does my table appear onload but not my chart?

So I have 2 functions, 1 to draw a chart, another to draw a table.
I did a
<body onload="getchart();gettable();">
but only the table gets drawn out onload!
So, I did a
<body onload="gettable();getchart();">
but oppositely, only the chart gets drawn out onload!
May I know how to draw both chart and table onload? Thank you~
My Codes down below (I did not include the server side php to mysql codes here) :
<script type="text/javascript">
function gettable(string,strings)
{
var a=string;
var b=strings;
if(a == null && b == null)
{
a = new Date().getFullYear();
b = "";
}
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("inputtable").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","GetTableData.php?q="+a+"&v="+b,true);
xmlhttp.send();
}
function getchart(str)
{
var b=str;
if(b == "")
{
b = new Date().getFullYear();
}
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("inputchart").innerHTML = xmlhttp.responseText;
var a=JSON.parse(xmlhttp.responseText);
ab=a[1];
cd=a[2];
ef=a[3];
gh=a[4];
//google.setOnLoadCallback(drawMouseoverVisualization());
drawMouseoverVisualization();
}
};
xmlhttp.open("GET","getData.php?q="+b,true);
xmlhttp.send();
}
function drawMouseoverVisualization() {
var barsVisualization;
var data = new google.visualization.DataTable();
data.addColumn('number', 'Quarter');
data.addColumn('number', 'Frequency');
data.addRows([[1,ab],[2,cd],[3,ef],[4,gh]]);
var options={
hAxis: {title: 'Quarter'},
vAxis: {title: 'Frequency'},
trendlines: {0: {type: 'exponential', //type: 'polynomial',type: 'linear'
degree:3,
color: 'red'
}}
};
barsVisualization = new google.visualization.ScatterChart(document.getElementById('chart'));
barsVisualization.draw(data, options);
};
google.load('visualization', '1.0', {'packages':['corechart']});
</script>
</head>
<body onload="getchart();gettable();">
<div id="inputchart" style="visibility: hidden"></div>
<form>
<select name="years" id="years" onchange="getchart(this.value)">
<?php
echo "<option>Select year</option>";
for ($i=2016;$i<date("Y")+10;$i++){
echo "<option value='$i'>$i</option>";
}
?>
</select>
</form>
<div id="chart"></div>
<form>
<input type="text" name="search" id="search" onkeyup="gettable(year.value,this.value)">
<select name="year" id="year" onchange="gettable(this.value,search.value)">
<?php
echo "<option value=2016>Select year</option>";
for ($i=2016;$i<date("Y")+10;$i++){
echo "<option value='$i'>$i</option>";}
?>
</select>
</form>
<div id="inputtable"></div>
</body>
You are using xmlhttp as a global variable.
Whichever function you run second overwrites the first value you assigned to it.
Avoid globals. Use local variables. Add var.
Perhaps you need a space in between the calling of the two functions.
http://www.htmlgoodies.com/beyond/javascript/article.php/3724571/Using-Multiple-JavaScript-Onload-Functions.htm
Otherwise you could create a function in your js that reads something like this:
function start () {func1(); func2();}
And just call start() when body is loaded.

AJAX magnific Popup not initialising after xmlhttprequest

I have a page containing a list of events, generated by a DB query, that the user can, for each event, click a button to register for the event. This fires a registration form (contained on event-registration.php) which is displayed via AJAX Magnific popup.
On normal pageload, the popup fires as expected as an AJAX type with the form embedded within the popup.
<a href='event-registration.php?eid=".$myrow['EID']."' class='ajax-popup-link' title='".$myrow['Tooltip']."' ><button type='button' class='".$myrow['StatusCSS']." buttonWrap'>".$myrow['StatusName']."</button></a>
$(document).ready(function() {
$('.ajax-popup-link').magnificPopup({
type: 'ajax',
cursor: 'mfp-ajax-cur',
closeOnContentClick: false
});
});
However, the results also have a couple of filters that can be applied, based on type of event, location etc. These are handled by XMLHTTP requests to dynamically filter the search results without having to reload the whole page.
<select id="EventLocation" onchange="filterEventsLocation(this.value)" class="filter">
<option value="">Filter by Event Location</option>
<option value="1">Scotland</option>
<option value="2">North of England</option>
<option value="3">Midlands</option>
<option value='4'>London & South East</option>
<option value='5'>South West</option>
<option value="reset">Reset (Show All)</option>
</select>
function filterEventsLocation(str) {
if (str == "" || str == "reset") {
document.getElementById("EventsList").innerHTML = xmlhttp.responseText;
xmlhttp.open("GET", "prt.getEvents.php", true);
xmlhttp.send();
/*document.getElementById("EventsList").innerHTML = "";
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("EventsList").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","prt.getEvents.php?l="+str,true);
xmlhttp.send();
}
prt.getEvents.php contains the SQL query code as well as a div 'EventsList' which then displays the query results.
However, once a filter is applied, the popup box no longer works, instead when the user clicks the button they're just taken straight to the event-registration.php file with no sign of magnific popup at all.
Does anyone have any ideas why the popup isn't initialising once the filter has been applied to the list of events?
UPDATED JAVASCRIPT ADDING EVENT LISTENER:
function filterEventsType(str) {
if (str == "" || str == "reset") {
document.getElementById("EventsList").innerHTML = xmlhttp.responseText;
xmlhttp.open("GET", "prt.getEvents.php", true);
xmlhttp.send();
/*document.getElementById("EventsList").innerHTML = "";
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("EventsList").innerHTML = xmlhttp.responseText;
document.getElementById("RegisterBox").addEventListener("onclick", openPopup);
function openPopup() {
$('.open-popup-link').magnificPopup({
type: 'inline',
midClick: true })
}
}
};
xmlhttp.open("GET","prt.getEvents.php?t="+str,true);
xmlhttp.send();
}
}

how to execute the javascript returned by AJAX response in the webpage (response = html+javascript)

my buyresult.php page is working properly when i give give the url as buyresult.php?q=Mysore
but the in response i get after ajax call(both html and javascript is response).. the javascript is not working... how to solve it.. I'm new to web programming. Please HELP..
I've googled and got the result as to use
new Ajax.Updater(divID,URL,{asynchronous:true,evalScripts: true});
but i don't know where to put this function
my index.php file is as follows :
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","buyresult.php?q="+str,true);
xmlhttp.send();
}
}
</script></head>
<body>
<label for="city">Enter City :</label><input class="w-input" id="city" type="text" placeholder="Enter the city name (required)" name="city" data-name="city" required="required" onchange="showUser(this.value)">
<div id="txtHint"><b>Results will be displayed Here...</b></div>
</body>

PHP Ajax passing two values - 1 dropdown menu 2 buttons

i have got following code working well for dropdown menu but as you can see second value (next_val=250f3) is static. i want to make is dynamic should change on click.
<script type="text/javascript">
function showUser(str)
{
if (str == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "productlistajax.php?q=" + str + "&next_val=250f3", true);
xmlhttp.send();
}
</script>
here is the drop down menu code.
<select id="maxDaysSinceAdded" name="shorting" onchange="showUser(this.value)">
<option selected='selected' value="1">Most Recent</option>
<option value="2">Lowest Price</option>
<option value="3">Highst Price</option>
</select>
how to use button to pass value live above drop down menu
<button type="button" name="buttonpassvalue" onclick="">Value</button>
thanks
You are calling showUser() on the change event of select tag. So in this case, you will have to read the value from the script itself before sending the ajax request.
You can modify your code as
var buttonValue = document.getElementsByName('buttonpassvalue').item(0).value;
xmlhttp.open("GET", "productlistajax.php?q=" + str + "&next_val=" + buttonValue, true);

Categories