Fetch result from database when link clicked - javascript

I'm using this HTML code;
if ($forum['type'] != 'c' && !$forum['linkto'] && $forum['posts'])
{
$forum['collapsed_image'] = '
<div class="expcolimage">
<a id="forum_name" fid="'.$fid.'">
<img src="images/collapse_collapsed.gif" id="ann_'.$forum['fid'].'_img" class="expander" alt="[-]" title="[-]" />
</a>
</div>';
}
else
{
$forum['collapsed_image'] = '';
}
What I want to do is to make it so when this link is clicked then an sql query should be run on a PHP page which fetches a result from database show that result in a <div> on an HTML page (or to show that result just under that link on the same page)
Due to limited knowledge in javascript I'm unable to code a javascript function which do that process, can you please provide me an example? I'll be very thankful to you.
Thank you!
PLEASE NOTE: I only want to use javascript and not jQuery

This is how you can do this:
test.php - the entire script is to be placed on this single script.
<?php
// Handle GET Request
if (isset($_GET['loadData']) && isset($_GET['id']))
{
// Dummy Response
// you should query the database here
exit("hello #". $_GET['id']);
}
?>
<script type="text/javascript">
function ajaxCall(url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function loadData(id)
{
ajaxCall('test.php?loadData&id='+ id, function(result) {
document.getElementById('result').innerHTML = result;
});
}
</script>
Click any of these links: <br>
Result: <div style="display: inline;" id="result"></div>
<br><br>
<?php
// this is your initial database query result with links
for ($i = 1; $i <= 3; $i++)
{
echo "• Hello, I am #$i. <a href='#' onclick='loadData($i);'>Click here<a> to load data.<br>";
}
?>
Demo:

The problem here is the way you're creating your html object. By doing it in one line you can't attach a listener for the click event.
I suggest to create elements in the javascript style:
var container = document.createElement("div");
container.className = "expcolimage";
var link = document.createElement("a");
link.setAttribute("fid", $fid);
var img = document.createElement("img");
img.src = "images/collapse_collapsed.gif";
img.id = "ann_" + $forum['fid'] + "_img";
img.className = "expander";
link.appendChild(img);
container.appendChild(link);
$forum['collapsed_image'] = container;
link.click(function(event){
event.preventDefault();
//AJAX code
});
Then I suggest you to look at these examples for choosing the best for you:
http://www.w3schools.com/ajax/ajax_examples.asp

Related

DOM selector giving null in Vanilla JavaScript but working in jquery

I am selecting an id using vanilla JS but ("qty").value; is giving me null answer but using the same code through jQuery is working fine
after else my jQuery code line
function manage_cart(pid, type) {
if (type == 'update') {
var qty = document.getElementById(pid + "qty").value;
} else {
var qty = jQuery("#qty").val();
}
var ajax = new XMLHttpRequest();
ajax.open("post", "manage_cart.php", true);
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = this.responseText;
if (type == 'update' || type == 'remove') {
window.location.href = 'cart.php';
}
document.querySelector('.cart-a span').innerHTML = response;
}
};
var data = new URLSearchParams({
pid,
qty,
type
});
ajax.send(data);
}
This is my vanilla JS code
function manage_cart(pid, type) {
if (type == 'update') {
var qty = document.getElementById(pid + "qty").value;
} else {
var qty = document.getElementById('qty').value;
}
var ajax = new XMLHttpRequest();
ajax.open("post", "manage_cart.php", true);
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = this.responseText;
if (type == 'update' || type == 'remove') {
window.location.href = 'cart.php';
}
document.querySelector('.cart-a span').innerHTML = response;
}
};
var data = new URLSearchParams({
pid,
qty,
type
});
ajax.send(data);
}
My html and php code looks like this in which the id is different for each product but remove does need pid in the selector.
<div class="basket-product-c">
<?php
if(isset($_SESSION['cart'])){
foreach($_SESSION['cart'] as $key=>$val){
$productArr=get_product($con,'','',$key);
$price=$productArr[0]['price'];
$qty=$val['qty'];
?>
<div class="price-c"><?php echo $price?></div>
<div class="quantity-c">
<input type="number" class="quantity-field-c" id="<?php echo $key?>qty" value="<?php echo $qty?>"/>
<br/>update
</div>
<div class="subtotal-c"><?php echo $qty*$price?></div>
<div class="remove-c">
Remove
</div>
<?php } } ?>
If you log var qty to the console, are you getting null, or is it picking up the element? The only reason I can think of as to why the vanilla js version is not working, is that the jquery id selector fires slower than a getElementById(). Ideally, there would be no difference, since jquery('#element') uses document.getElementById() under the hood.
Maybe do as #Elikill58 suggested and delay the selection by wrapping that line in a setTimeout() function.
Also, getElementById().value will return undefined if there's no value attribute, or blank if there is a value attribute present for that tag, but there is no value set.
If the element is not being picked up at all by the selector, you'll get null as a response.
Try this and see if it works:
function manage_cart(pid, type) {
if (type == 'update') {
var qty = document.getElementById(pid + "qty").value;
} else {
setTimeout(() => {
var qty = document.getElementById('qty').value;
}, 200)
}
You can play around with the delay timing to find one which is ideal for you.

Why is this Ajax not working with my php and not making an alert happen?

I am very new in programming websites I created a website already but am now attempting to add in a database. I have that all set up but ajax isnt working and I'm not sure what I'm doing wrong.
Here is my javascript code :
<script>
var ajax = new XMLHttpRequest();
var method = "Get";
var url = "data.php";
var asynch = true;
ajax.open(method, url, asynch);
ajax.send();
//recive ajax
ajax.onreadystatechange = function()
{
if(this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
}
}
/*
function chbg(color, name) {
document.getElementById(name).style.backgroundColor = color;
document.getElementById(name + 'Chore').style.backgroundColor = color;
document.getElementById(name+ 'Bathroom').style.backgroundColor = color;
}
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
*/
</script>
Here's the php all I'm trying to do right now is get the 2 to connect.
<?php
echo "Hello World";
?>
I didn't understand what you're exactly trying to do but your php file just echo something and he does not return something so your responseText property is empty.

JavaScript Not Returning Data But No Error Either

I am calling a php file that queries my database and returns a result. I have verified that the php file accurately returns the data as needed, but my calling page is not updated from the JavaScript.
What do I need to alter in my syntax below so that the returned value is returned on page?
<script type="text/javascript">
function boostion()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("data").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
EDIT
I have also opened Developer Options in Chrome and checked the Console and there are no errors or issues displayed, everything is a success!
Edit 2
I tried to use the JQuery approach below and used this syntax - but I get the error
Uncaught TypeError: $(...).load is not a function
Syntax:
<script src="https://code.jquery.com/jquery-3.1.1.slim.js"
integrity="sha256-5i/mQ300M779N2OVDrl16lbohwXNUdzL/R2aVUXyXWA="
crossorigin="anonymous" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
document.getElementById("data").innerHTML = data;
});
});
</script>
Edit 3
This is my php syntax that runs the sql syntax and echo result that I want to have returned from the javascript
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'host';
$option['user'] = 'user';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance( $option );
$result = $db->getQuery(true);
$result->select($db->quoteName(array('trackandfieldresults')));
$result->from($db->quoteName('[TrackData]'));
$db->setQuery($result);
$row = $db->loadRowList();
echo $row['0']
?>
Use xhr.send();
If it is a GET request, you have to apply the query string in in xhr.open and you dont have to set Content-type:application/x-www-form-urlencoded
first, the scripts should be inside the HTML before the ending body tag. then you open another file and write your code in it. JQUERY does not have script tag. Sp you are creating an external javascript file for the script. No script tag needed. Now use this format.
$(window).on('load', function(e){
e.preventDefault();
var dat = //the content you are trying to load
$.get('middleware.php', dat, function(data){
$('#selector').html(data)
});
})
I have a faster approach using JQuery.
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
//Do whatever you want here
});
});
This should do the Job. Your approach is old and kind of complicated to debug
Try this
function boostion(){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.send();
xhr.onreadystatechange = function(){
console.log(xhr);
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("data").innerHTML = xhr.responseText;
}
}
}
<div id="data"></div>
<button onclick="boostion();">Load</button>

Fetching data from php file and using javascript to print selected data

I have 2 divs in my html page. Using AJAX, JavaScript, I send my query parameters to a php file, which returns combined results for the 2 divs. I want to know how to separate the result in JavaScript and display in their respective divs.
<script>
function fetchData() {
var yr = document.getElementById('entry').value;
if (yr.length==0) {
document.getElementById("result1").innerHTML="";
document.getElementById("result2").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var content = xmlhttp.responseText;
if (content == "%<searchword>%")
document.getElementById("result1").innerHTML = content;
else
document.getElementById("result2").innerHTML = content;
}
}
xmlhttp.open("GET","db.php?q="+ yr ,true);
xmlhttp.send();
}
</script>
<body>
<form>
Enter year: <input type="text" id="entry" />
<input type="button" value="check here" onclick="fetchData()" />
</form>
<div id="result1">result 1 here</div>
<div id="result2"> result 2 here</div>
</body>
Return json as PHP output, that is best for Javascript (do not forget json php headers, use json_encode), like this:
{
"div1": "Content for div 1",
"div2": "DIV 2 content"
}
Easy with jQuery getJSON method, or jQuery $.ajax:
$.ajax({
dataType: "json",
url: urlToPHPFile,
data: dataToSend,
success: function( jsonResponse ) {
$('#result1').html( jsonResponse.div1 );
$('#result2').html( jsonResponse.div2 );
}
});
To send request with pure Javascript take a look at this article.
To parse JSON just read this article.
So, with pure Javascript you get something like this:
function alertContents(httpRequest){
if (httpRequest.readyState == 4){
// everything is good, the response is received
if ((httpRequest.status == 200) || (httpRequest.status == 0)){
var obj = JSON.parse(httpRequest.responseText);
var div1 = getElementById('result1');
var div2 = getElementById('result2');
div1.innerHTML = obj.div1;
div2.innerHTML = obj.div2;
}else{
alert('There was a problem with the request. ' + httpRequest.status + httpRequest.responseText);
}
}
};
function send_with_ajax( the_url ){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open("GET", the_url, true);
httpRequest.send(null);
};
function fetchData() {
var yr = document.getElementById('entry').value;
if (yr.length == 0) {
document.getElementById("result1").innerHTML = "";
document.getElementById("result2").innerHTML = "";
return;
}
send_with_ajax( "db.php?q=" + yr );
};
fetchData();

javascript with XMLHttpRequest not working

I have tried everything suggested in questions of similar nature but this very basic code is just not working. I just want to receive the message from the php code in the same file using XMLHttpRequest.
<!DOCTYPE html>
<head></head>
<body>
<div id="qwer" style="height:50px;width:40px"></div>
<script type="text/javascript">
function check() {
var ualias=document.getElementById('ualias').value;
var resu=document.getElementById("qwer");
var params="username="+ualias;
var hm = new XMLHttpRequest();
var url = "http://'my-domain-name'/try.php";
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
hm.send(null);
resu.innerHTML="CHECKING...";
}
}
</script>
<?php if(isset($_GET['username'])) {
$u=$_GET['username'];
echo $u;
exit();
} ?>
<input id='ualias' type='text' onblur=''>
<button type='button' onclick="check()">Go!</button>
</body>
</html>
The browser (Google Chrome) isn't showing anything for the onclick event.
It finally worked. I made the following edits.
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function check()
{
var ualias=document.getElementById('ualias').value;
var resu=document.getElementById("qwer");
var params="username="+ualias;
var hm = new XMLHttpRequest();
var url = "http://www.websamaj.in/try.php";
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200)
{
var return_data = hm.responseText;
resu.innerHTML=return_data;
}
}
hm.send(null);
resu.innerHTML="wait...";
}
</script>
<?php
if(isset($_GET['username']))
{
$u=$_GET['username'];
echo $u.",you are finally here!:)";
exit();
}
?>
<input id='ualias' type='text' onblur=''>
<button type='button' onclick="check()">Go!</button>
<div id="qwer" style="height:50px;width:100px;background-color:#CCC;"></div>
</body>
</html>
Apparently, the else condition there in onreadystatechange function was causing a problem. I would love it if anybody could tell me why exactly was that creating a problem. As far as i know, onreadystatechange event is called each time the state changes. So in my previous code, "error" should be overwritten thrice on the div and then, when the state changes to 4 and 200, the responseText should be overwritten, since i didnt use append. So, an explanation would be highly acknowledged. Thank you!
In your original code, hm.send(null) and resu.innerHTML="CHECKING" lines are actually INSIDE the onreadystatechange callback:
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
hm.send(null); // <-- wrong place!
resu.innerHTML="CHECKING...";
}
In your edited version, you moved them out of there (fixed indention):
hm.open("GET", url+"?"+params, true);
hm.onreadystatechange = function(){
if(hm.readyState == 4 && hm.status == 200) {
var return_data = hm.responseText;
resu.innerHTML=return_data;
} else {
resu.innerHTML="error";
}
}
hm.send(null);
resu.innerHTML="wait...";
The reason you didn't notice this is because in your edited version, you didn't indent your blocks correctly. Recommend always keeping your code formatted consistently, even when hacking around, so you can see the code blocks.

Categories

Resources