Replace PHP script for jQuery to live AJAX feed - javascript

I have an AJAX script powered by PHP backend which parses/gathers data from an XML file. I am trying to eliminate the PHP script and replace it with a JavaScript solution with jQuery. Here is my current JS script which is binded with a PHP script:
function showUser(str) {
if (str == "") {
document.getElementById("loadMe").innerHTML = "";
return;
}
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("loadMe").innerHTML = xmlhttp.responseText;
}
}
//xmlhttp.open("GET","lib/getuser.php?q="+str,true);
//xmlhttp.send();
};
Here is the PHP script (getuser.php)
<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("../Administration/data/people.xml");
$x=$xmlDoc->getElementsByTagName('fullName');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
{
if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
{
$y=($x->item($i)->parentNode);
}
}
}
$user =($y->childNodes);
for ($i=0;$i<$user->length;$i++)
{
//Process only element nodes
if ($user->item($i)->nodeType==1)
{
if($i != 1 && $i != 0) {
echo("<b>" . $i . $user->item($i)->nodeName . ":</b> ");
echo($user->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
}
?>
The above PHP works fine but... its PHP and its not written to live feed. I have a working jQuery solution below but I can't seem to implement it correctly with the first JS script above. As you can see right now the above JS script is triggering a GET request and expecting a feed from the PHP file. Here is my jQuery AJAX script:
setInterval(updateMe2,500);
function updateMe2(){
$.ajax({
type: "GET",
url: "../Administration/data/people.xml"
}).done(function (xml) {
$("#txtHint").empty();
$(xml).find('person').each(function() {
var firstName = $(xml).find('firstName').text();
var lastName = $(xml).find('lastName').text();
var age = $(xml).find('age').text();
var hometown = $(xml).find('hometown').text();
var job = $(xml).find('job').text();
$('<b></b>').html(firstName).appendTo('#loadMe');
$('<b></b>').html(lastName).appendTo('#loadMe');
$('<b></b>').html(age).appendTo('#loadMe');
$('<b></b>').html(hometown).appendTo('#loadMe');
$('<b></b>').html(job).appendTo('#loadMe');
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
};
How can I change the first JS snippet to work with this, above jQuery snippet instead of the above PHP file? NOTE: both the PHP file and the jQuery script both spit out the same markup, the PHP file is just written much differently. Thanks a ton in advance!

I created a solution if anyone is interested:
setInterval(itemMenu,1500);
function itemMenu() {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$("#loadMe").empty();
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" onclick="itemContent(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
//setInterval(itemContent,1500);
function itemContent(q) {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
if(q==fullName) {
$("#toadMe").empty();
firstName = $(this).siblings('firstName');
lastName = $(this).siblings('lastName');
age = $(this).siblings('age');
hometown = $(this).siblings('hometown');
job = $(this).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};

Related

How get steam nickname via javascript

Hello i now using this php code for get steam nicknames
function EchoPlayerName($steamid){
$xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xml
if(!empty($xml)) {
$username = $xml->steamID;
echo $username;
}
}
or
$steam = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64", true);
$steamarray = json_decode($steam, true);
$name = $steamarray['response']['players'][0]['personaname'];
but i this using for listing players and loading page is slow
so i want this data load via javascript after full load page
any ideas?
API example
{"response":{"players":[{"steamid":"76561197964477177","communityvisibilitystate":3,"profilestate":1,"personaname":"The [G]amerX #π—™π—¨π—‘π—£π—Ÿπ—”π—¬.𝗽𝗿𝗼","lastlogoff":1558765863,"commentpermission":1,"profileurl":"https://steamcommunity.com/id/gamerxcz/","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013.jpg","avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_medium.jpg","avatarfull":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_full.jpg","personastate":0,"realname":"Community Owner","primaryclanid":"103582791433644720","timecreated":1076786008,"personastateflags":0,"loccountrycode":"CZ"}]}}
First, you should get Data using ajax of pure javascript or jquery. Then you should target an HTML element that you want to fill it using this retrieved data. Imagine element with ID target.
jQuery:
$(document).ready(function () {
$.ajax({
url: "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64",
}).done(function (data) {
var json = JSON.parse(data);
$('#target').text(json['response']['players'][0]['personaname']);
});
});
pure javascript:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64');
xhr.onload = function () {
if (xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
document.getElementById('target').innerHTML = json['response']['players'][0]['personaname'];
} else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Remember to place these scripts at the end of your document.

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>

Mysql update with JQUERY

I'm having a bit of trouble understanding how to get this to work. I'm loading a page with data from mysql db table using jquery. I'd like to be able to do mysql updates on individual records without refresh. Here's the code I've tried, but can't get the update to work.
index.php
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","data_ajax.php?q="+str,true);
xmlhttp.send();
}
}
Here I have a drop-down in a while loop to retrieve the desired records and post it into a <div id="txtHint"></div>. So far, so good.
Now, I'm putting the following in data_ajax.php to do the mysql update.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".update_button").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "update_ajax.php",
data: dataString,
cache: false,
});
return false;
});
});
</script>
Where I have a text link <a href='#' id='".$row['id']."' class='update_button'>".$label."</a> that should call the action above to do the update. All this does it jumps the page to the top and nothing happens. The update_ajax.php doesn't seem to get called when link is clicked. I know it's something simple I'm missing. Any help would be appreciated.
What I would suggest is including jQuery directly in index.php, which would then allow you to use event delegation to handle most of the work.
With jQuery being included in index.php, you can use jQuery to do the showUser ajax request too.
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "update_ajax.php",
data: dataString
});
return false;
});
});
Update your version of jQuery. Your example shows you using version 1.4.2.
The $.ajax shorthand code was introduced after version 1.5.

Flag Query PHP to JavaScript

I have that
JavaScript
flagQuery = session.reponseText;
alert(flagQuery);
flagQuery = JSON.parse(flagQuery);
contentElt.innerHTML = "valeur FLAG" + flagQuery;
My javascript must receive a flag sent from php.
The code above is the treatment of flag when it is received.
In my php I declare the variable flag to true.
I want to treat this with Ajax, if it's possible.
I don't know what to add in the PHP to get the flag in JavaScript?
I should prefer not to have to overload my code with a jQuery bookshop that I will use it for half a score line of code.
I assume want to access php value through ajax request. And you can do that liek below;
PHP: flag.php
<?php
$flag = "Your flag value";
echo $flag;
JS:
$.ajax({
url: "flag.php",
type: "get",
success: function(data){
alert("Flag value is: " + data);
},
error:function(){
alert("Error occured!");
}
});
Pure JS:
<script>
function getFlagValue() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState==4 && xmlHttp.status==200) {
alert(xmlHttp.responseText);
}
}
xmlHttp.open("GET","flag.php",true);
xmlHttp.send();
}
</script>
Hello. Try this and see if it's you need.
//PHP File
<?php
echo json_encode(array("one","two"));
?>
//Js File
$.get("page.php", function(data){
alert(data)
})

Transform this function completely to jQuery

I need this function as jQuery.
There is a part jQuery but I am finding a tough time to write the code!
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("drop_em").innerHTML = xmlhttp.responseText;
$('#scrollbar3').tinyscrollbar();
}
}
xmlhttp.open("GET", "list_playlist_popup.php?qq=" + str, true);
xmlhttp.send();
}
What have you tried? Where are you stuck? (Because this is the most basic form of AJAX call in jQuery)
$.get(
"list_playlist_popup.php",
{ qq: str },
function success(data) {
$('#drop_em').html(data);
$('#scrollbar3').tinyscrollbar();
});
Use jQuery Ajax :
$.ajax({
url:'list_playlist_popup.php',
type:'POST',
data:{
variable : value
},
success:function(data){
alert('success');
}
})
Just copy paste this over the existing function.
function showUser( str ) {
$.ajax({
url: 'list_playlist_popup.php',
data: {
'qq': str
}
}).done(function( data ) {
$('#drop_em').html(data);
$('#scrollbar3').tinyscrollbar();
});
}
function showUser(str) {
$.get('list_playlist_popup.php',{qq:str},function(response) {
$('#drop_em').html(response);
$('#scrollbar').tinyscrollbar();
});
};
This is your jQuery equivalent.

Categories

Resources