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

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();

Related

JS: HTML is not dynamically changing

I am building an web that allows user to like a post when they click a button. CreateLike function calls API and creates a like object however, I would like to have the number of likes updated right away without reloading. I built another API that returns the number of likes for a post. Function LikeCount should put the number of likes into the p tag. It works initially when I load the page however, the value does not change when I click the button even though I can see that the API is called. (After reloading the page the number changes as expected) What am I doing wrong?
I have this HTML:
<p class="like-count" id={{post.id}}></p>
<script>LikeCount({{post.id}});</script>
<button type="button" class="btn-like" onclick="CreateLike({{user.id}},{{post.id}})"></button>
with JS functions:
function CreateLike (userid,postid) {
xhr = new XMLHttpRequest();
var url = "{% url 'likes' %}";
var csrftoken = getCookie('csrftoken')
xhr.open("POST", url, true);
xhr.setRequestHeader("X-CSRFToken",'{{ csrf_token }}')
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({csrfmiddlewaretoken:csrftoken,"user":userid,"post":postid});
xhr.send(data);
LikeCount(postid);
}
function LikeCount(postid) {
var xmlhttp = new XMLHttpRequest();
var url = "{% url 'likecount' id=112233 %}".replace("112233", postid);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = arr.like_count;
document.getElementById(postid).innerHTML = out;
}
}
Like count API looks like this:
{
"like_count": 1
}
if(xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
LikeCount(); //Put your get like count here
} else {
// Handle Errors
}
}
Call LikeCount only after receiving the response of your POST request. Right now you're immediately sending a GET request without ensuring if the previous POST request got completed.
Added
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 201) {
var myArr = JSON.parse(this.responseText);
LikeCount(myArr.post);
}
};
before
xhr.send(data);
and it fixed the issue.

JSON data to HTML using AJAX

I am trying to input the value of the currency using the Value="AUD" as a starter. I am very new to JSON and AJAX. I cannot work out why there is an 404 error linked to JSON.parse and XMLHttpRequest, any advise of where I am going wrong would be much appreciated. Thanks in advance.
`enter code here`
<html lang="en">
<head>
</head>
<body>
<div id ="forex-info">
<p id="currencyList" class="currencyList" value ="AUD">Australia</p>
<p id="rateList" class="event"></p>
</div
<script type="text/javascript">
var tableContainer = document.getElementById("forex-info");
var ourRequest = new XMLHttpRequest();
var myData = "http://api.fixer.io/latest".rates;
ourRequest.open('GET', myData, true);
ourRequest.onload = function loading() {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
function renderHTML(data) {
var output = "";
for (var key in data)
{
output += "<p>" + key + output + "</p>"
}
}
};
</script>
</body>
The main issue is how your calling the api "http://api.fixer.io/latest".rates
You call rest endpoints by there address params or with query params.
Please see example below calling your specified endpoint. That should get you started
var myData = 'https://api.fixer.io/latest'
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let res = JSON.parse(xhttp.responseText)
Object.keys(res.rates).forEach((e)=>{
console.log(`${e}: ${res.rates[e]}`)
//Add your stuff here
})
}
};
xhttp.open("GET", myData, true);
xhttp.send();

how to create radio buttons by JS.

i have some problrm creating the radio buttons dynamically. in my problem i am requesting data from server in json formate than i check if it contains options i have to create the radio buttons otherwise simply creates the txt area of field to submit the answer. than again i parse it in json formate and send to the server and if my question is write i get new url for next question and so on...
my question is how can i create the radio buttons and read the data from it and than parse that data like {"answer": "something"}.my code is bellow:
enter code herefunction loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
var data = JSON.parse(this.responseText);
document.getElementById("my_test").innerHTML = data.question;
// Send the answer to next URL
if(data.alternatives !== null){
createRadioElement(div,);
}
var answerJSON = JSON.stringify({"answer":"2"});
sendAnswer(data.nextURL, answerJSON)
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function sendAnswer(url, data) {
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(this.responseText);
console.log(this.responseText);
loadDoc(data.nextURL);
}
}
// var data = JSON.stringify({"email":"hey#mail.com","password":"101010"});
xhr.send(data);
}
function createRadioElement(name, checked) {
var radioHtml = '<input type = "radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
I'm only guessing since you have some things in your posted code that won't even run, but createRadioElement returns a detached node which you never actually inject into your document.
E.g.,
document.body.appendChild(createRadioElement());

$_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();
}

Fetch result from database when link clicked

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

Categories

Resources