I am fetching live value i.e. ftse from yahoo finance, using ajax and php.
I want to store all value in an array format and want to compare last 2 recently updated values.
following is my javascript:
<script>
function loadXMLDoc()
{
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ftse.php",true);
xmlhttp.send();
}
setInterval(loadXMLDoc,1000);
</script>
following is my php code.
<div id="myDiv">
<?php
// Setup Variables
$stockList = "^ftse";
$f = "l1";
$host = "http://finance.yahoo.com/d/quotes.csv";
$requestUrl = $host."?s=".$stockList."&f=".$f."&e=.csv";
// Pull data (download CSV as file)
$filesize=2000;
$handle = fopen($requestUrl, "r");
$raw = fread($handle, $filesize);
fclose($handle);
// Split results, trim way the extra line break at the end
$quotes = explode("\n\n",trim($raw));
foreach($quotes as $quoteraw) {
$quoteraw = str_replace(", I", " I", $quoteraw);
$quote = explode(",", $quoteraw);
// output the first element of the array, the Company Name
}
echo "<br><center><font size='30' color='green'>".$raw."<br>";
?>
</div>
following is my ftse.php code.
<?php
// Setup Variables
$stockList = "^ftse";
$f = "l1";
$host = "http://finance.yahoo.com/d/quotes.csv";
$requestUrl = $host."?s=".$stockList."&f=".$f."&e=.csv";
// Pull data (download CSV as file)
$filesize=2000;
$handle = fopen($requestUrl, "r");
$raw = fread($handle, $filesize);
fclose($handle);
// Split results, trim way the extra line break at the end
$quotes = explode("\n\n",trim($raw));
foreach($quotes as $quoteraw) {
$quoteraw = str_replace(", I", " I", $quoteraw);
$quote = explode(",", $quoteraw);
// output the first element of the array, the Company Name
}
echo "<br><center><font size='30' color='green'>".$raw."<br>";
?>
Problem is if the value is smaller then should be printed in red and if greater then in green color.
There's no property color on the element. You want to set a style to set the color to green, so you would write:
echo "<br><center><font size='30' style='color=green'>".$raw."<br>";
Ideally you wouldn't do this because it just pollutes the DOM. Annotate with a class:
echo "<br><center><font size='30' class='up'>".$raw."<br>";
echo "<br><center><font size='30' class='down'>".$raw."<br>";
Then in your CSS file you just have:
.up {
color: green
}
.down {
color: red
}
While you are at it, also move the font size and other style decorations to the CSS.
I hope this helps.
Related
I am trying to figure out if a current page's php $var can be passed through to the XMLHttpRequest2. The file that is being called is located outside of the views(where the current php page is located) folder in the /assets/js directory. I am using CodeIgniter as well. Trying to pass the $user_id along to use in a SQL query in side the XMLHttpRequest2 requested file.
publication_call.php (current file)
<form>
<input type="hidden" id="someid" value="<?= $idz ?>"/>
<?php
echo form_label('Validation: (Enter Publication keywords, Matches will appear in Dropdown > )');
echo form_label('Matching<br>Publications:');
?>
<select name="matched_pub" id="matched_pub"></select>
</form>
<script>
jQuery(function($){
//still want to bind the change event
$('#matched_pub').bind('change', function(){
$('#title').val($('#matched_pub option:selected').text());
});
$('#validation').keyup(function() {
showKeywords( $('#validation').val() );
document.getElementById('matched_pub').style.display='block';
});
});
</script>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
<?php
$user = 'root';
$pass = 'root';
$db = 'hey_there';
$host = 'localhost';
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
//trying to display special chars
mysql_query("set names 'utf8'");
if(!$db_selected) {
echo 'broke';
}
//echo 'db connected';
$q = $_GET["b"];
//explode and parse $q into all the fragments separated by spaces and do full text search +word1 +word2 +word3, this will ignore HTML tags as it ignores word order, will also solve the middle initial problem [db setup is not compatible with full text search, but can do likes per word, less efficient, but how it must be done]
$queryWords = explode(' ', $q);
//for services query, explode the query into words and search for each separately
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = 103 <-- $var will go here
";
$queryServicesLoop = '';
$queryServicesEnd = ' ORDER BY pub_title ASC';
//loop through all words in string
foreach($queryWords as $queryWord) {
$queryServicesLoop .= " AND (keywords LIKE '%{$queryWord}%')";
}
$queryServices = $queryServices.$queryServicesLoop;
$queryServices = $queryServices.$queryServicesEnd;
$resultServices = mysql_query($queryServices);
$services ='';
if(mysql_num_rows($resultServices) > 0){
while($rowServices = mysql_fetch_assoc($resultServices)) {
$services .= '<option value="' . $rowServices['pub_title'] . '">' . $rowServices['pub_title'] . '</option>';
}
}
if( mysql_num_rows($resultServices) == 0 )
{
echo '<option value="">Your search failed to find any matching results.</option>';
}
else
{
echo '' . $services . '';
}
/* ==============================
Edited Code
============================== */
publication_call.php (current file)
<input type="hidden" id="someid" value="<?= $user_id ?>"/>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("someid");
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid'), true);
// xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
$usr = $_GET["user_id"];
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = ".$usr."
";
You can put $user_id inside of a hidden input field, and using Javascript, read the value of it to use in your Ajax request
You can do it like this:
<input type="hidden" id="someid" value="<?= $user_id ?>
And then after you've done that, you can get the value by doing this:
document.getElementById('someid'); using plain Javascript or $('#someid').value(); if you use jquery
This will get you the user ID value which you can then use in the request.
Like so:
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid').value, true);
Replace your current xmlhttp2.open with the one above
Now you can access the value of user ID in $_GET['user_id'] in the requested file.
I have posted the code below.
there are two files..
getvendorname.php
sales.htm (containing the javascript function)
Here what i am did is when blur i need to retrieve the values without page reload from getvendorname.php and show the vendor name and id in the different textbox.
Here i have to store the values into different textbox retrieved from database with the use of xmlhttprequest object.Here the values are retrieved,but i can't store into the different textbox.Its working,but it shows like this
o/p:201anne.I need to display vendor id and vendor name on different textbox.please help me
sales.htm
<script type='text/javascript'>
function getname()
{
var vendorID = document.getElementById("idvid").value;
var xmlhttp;
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("iddiv1").innerHTML=xmlhttp.responseText;
document.getElementById("iddiv2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getvendorname.php?vendorid="+vendorID,true);
xmlhttp.send();
}
</script>
<html>
<head><title>vendor info</title> </head>
<body>
<td>Vendor Primary ID:</td>
<td><input type="text" id="idvid" name="vendor_primary_number" onblur="getname()">
</td>
<td> <div id="iddiv1"> </div></td>
<td> <div id="iddiv2"> </div></td>
</body>
</html>
getvendorname.php
<?php
$vid = $_GET['vendorid'];
$connection = mysql_connect('localhost','root','root');
mysql_select_db('bgm_score', $connection);
$r ="select vendorid,vendorname from vendor_info where vendorid ='$vid'";
$result = mysql_query($r, $connection);
$row = mysql_fetch_assoc($result);
echo $row["vendorid"];
echo $row["vendorname"];
?>
I made a few corrections to your code to make it work. First, replace this line:
document.getElementById("iddiv1").innerHTML=xmlhttp.responseText;
with:
document.getElementById("iddiv1").innerHTML=vendorID;
The reason is you don't need to retrieve the vendor ID from the database since that's the data you're sending. Just use the variable you have. That also means you need to change your PHP code.
Remove the vendorid field from your query:
$r ="select vendorid,vendorname from vendor_info where vendorid ='$vid'";
Now it looks like this:
$r ="select vendorname from vendor_info where vendorid ='$vid'";
Also remove this line since it's not needed:
echo $row["vendorid"];
I am following the guide from http://www.w3schools.com/php/php_ajax_database.asp, and I get the basic concept of how this works.
My code:
PHP:
<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<select class="navbar-inverse" placeholder="PM Name" name="PMName"onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?>
</select>
<div id="txtHint"><b></b></div>
JavaScript:
<script>
function showUser(str) {
if (str !==".PM") {
alert(str);
if (str=="") {
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
and the getuser.php page:
<?php
$q = intval($_GET['q']);
include('./db.php');
$sqlPM= "SELECT * FROM report WHERE PMName = '".$q."'";
$result = mysqli_query($con, $sqlPM);
?>
<table>
<?php
echo $q ;
?>
</table>
I have read through about 12 posts here and tried to make sense of the fact that most of these use some form of $.post('getuser.php'to send the variable over to the new PHP page, but the example from w3schools does not do this. On the initial page, my dropdown is populating fine from my database, and the value I select is being passed into the JavaScript function. I check this with alert(str);, but from there, it doesn't ever seem to get to the second PHP page. I tried testing that it came over using echo $q ;, but that comes up as empty.
What am I doing wrong that is causing the variable that the JavaScript function captures to not be passed over to the second PHP page?
From what I can see, I am following the instructions on the tutorial just fine.
$.post('getuser.php' This syntax is exclusive to a javascript library called jQuery. Furthermore, $q is not an integer it is a string considering the DB query you perform initially, so why are you wrapping $_GET['q'] with intval()?
I'm having problem on my joomla article which i customize the code with Sourcerer.
Here is some of my example code for the ajax javascript:
<script type="text/javascript">
function showBox1(element) {
document.getElementById('hideBox1').style.display = "";
if (element == "")
{
document.getElementById("txtHint").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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "home/matedis/public_html/joomla/Add_Edit_Intake/getuser.php?q=" + element, true);
xmlhttp.send();
}
</script>
The code for passing the value to the function is here:
<?php
// Get default database object
$db = JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
// Build the query
$query->select($db->quoteName('campusid'));
$query->from($db->quoteName('campus'));
$query->where($db->quoteName('collegeid') . '=' . $db->quote('1'));
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if ($results) {
foreach ($results as $result) {
echo "<label class='option block spacer-t10'>";
echo "<input type='radio' id ='campusID' name='campusID' value='$result->campusid' onChange='showBox1(this.value)'><span class='radio'></span>";
echo $result->campusid;
echo '</label>';
}
} else {
echo 'Error';
}
?>
Here is my getuser.php code:
<?php
$q = intval($_GET['q']);
define( 'JPATH_BASE', $_SERVER[ 'DOCUMENT_ROOT' ] ); // define JPATH_BASE on the external file
require_once( JPATH_BASE . DS . 'libraries' . DS . 'import.php' ); // framework
require_once( JPATH_BASE . DS . 'configuration.php' ); // config file
$db = JFactory::getDBO();
$sql="SELECT courseid FROM course WHERE campusid = '".$q."'";
// Build the query
$query->select($db->quoteName('courseid'));
$query->from($db->quoteName('course'));
$query->where($db->quoteName('campusid').'='. $db->quote($q)); //This later must change to retrieve id from current user
// Set the query for the DB oject to execute
$db->setQuery($query);// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($results){
foreach($results as $result)
{
echo $result->courseid;
}
}
else{ echo 'Error';}
?>
Is there any mistake i had made? Because it does not show up the output i want which i refer the code from here http://www.w3schools.com/php/php_ajax_database.asp. Sorry if any inconvenience cause because i still new to joomla and php ajax.
xmlhttp.open("GET","home/matedis/public_html/joomla/Add_Edit_Intake/getuser.php?q="+element,true);
This is real path of public_html? No..
When I am building 2 dropdowns filling them from the database, the second dropdown is created when a value is picked from the first dropdown. But then, when I select an option in the second, my ajax is being executed. But when I have only one value in the second dropdown, it won't work. Even if I call the javascript function manualy.
The 2nd dropdown:
<?
include ('../dbconnect.php');
$query = "CALL get_projects(".$userid.",".$q.")";
$result = mysql_query($query);
$countprojects = mysql_num_rows($result);
if ($countprojects != 0){
echo '<select class="form-control" onchange="showContent(this.value)">'."\n";
if ($countprojects > 1){
echo "<option value='none' selected>Select project</option>";
}
while($rowprojecten = mysql_fetch_assoc($result)){
echo '<option value='.$rowprojecten['projectID'].'>'.$rowprojecten['projectname'].'</option>';
$lastvalue = $rowprojecten['projectID']; // see below why i did this
}
echo '</select>';
?>
the javascript function I wrote/copied:
function showContent(str)
{
if (str=="")
{
document.getElementById("project").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("project").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","./includes/ajax/getcontent.php?q="+str,true);
xmlhttp.send();
}
The phpfile what is called from this javascript:
<?
$q = intval($_GET['q']);
include ('../dbconnect.php');
$query = "CALL get_project(".$userid.",".$q.")";
$return = '<div id="project">';
$return .= $query;
$return .= '</div>';
echo $return;
mysql_close($con);
?>
Why do I see the div 'project' change when I select one, but does'nt it change when it is created?
I tried to call the function manualy with adding this to the first php file. But it also doesn't work.
if ($countprojects == 1){
echo '<script type="text/javascript">
showContent('.$lastvalue.')
</script>';
}
sorry for my bad english, I hope you can help me solve this.
This is because there is only one option in your second drop down list. you cannot fire change event if there is only on or zero options in drop down list. what you can do is add this code where your first Ajax call get fired when selection changes. and place your second Ajax call in inside below code.
if ($('#selectproject').children().length == 1) {
// make sure you have imported latest jquery. if not add this inside HTMl head : <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
var selectedProject = $('#selectproject').children()[0].value;
showContent(selectedProject); // i hope this is the function you are calling when executing. if not please replace your function call here.
}