I am creating a weather widget using javascript . In this widget the user can select the town they wish to see and the widget will display outlook , min and max temperature without refreshing using ajax . I have stored the city information in a database and had written PHP script to retrieve the data and pass it to js as JSON object
<?php
/**************************
* code to connect to your database here
*/
$con = mysqli_connect("localhost", "user", "pass");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:".mysqli_connect_error();
}
mysqli_select_db("weather", $con);
$town = $_GET['town'];
/***************************
*
* Query the DB for weather information for the given town.
*
* A PHP array object containing the weather data.
* Return a JSON encoded version of the array to the browser.
*
*/
$sql = "SELECT * from weather where town = $town";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$arr = array(
"town" => $row[town],
"outlook" => $row[outlook],
"min_temp" => $row[min_temp],
"max_temp" => $row[max_temp]
);
}
echo json_encode($arr);
mysqli_close();
?>
And in js i want to show the weather only for selected town . How to parse the JSON object to get only the information of the town selected by the user . Like
if(jsondata == "sydney")
return "sydney information";
I did this using DOJO as
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
// The method that handles the request's successful result
// Handle the response any way you'd like!
load: function(result) {
data = result;
}
});
return data;
}
However , i dont want to use dojo . how do i do that . Any suggestions ?
Suppose you have a select tag with id "town".
<select id="town" onchange="handler(this)"></select>
Now, for the Javascript part. You need to use XMLHttpRequest to make an ajax call.
function handler(elem){
var tname = elem.value;
var request_url = "PHP/weather.php?town=" + tname;
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Some error occured");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
//Update your page here
}
}
http_request.open("GET", request_url);
http_request.send();
}
<body>
<div id="townInfo">
<div id="town"></div>
<div id="outlook"></div>
<div id="min_temp"></div>
<div id="max_temp"></div>
</div>
<script>
var town = document.getElementById('town');
var outlook = document.getElementById('outlook');
var min_temp = document.getElementById('min_temp');
var max_temp = document.getElementById('max_temp');
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
load: function(result) {
data = result;
town.innerHtml = data['town'];
outlook.innerHtml = data['outlook'];
min_temp.innerHtml = data['min_temp'];
max_temp.innerHtml = data['max_temp'];
}
});
</script>
</body>
warning: not tested
Related
I'm a fairly inexperienced coder, and am seeking help on why I'm not receiving a response to my $.post command.
From the output, (i think) the post is correctly submitting the PHP page, and the PHP correctly creates a JSON file with the values I expect. The issue is that my callback never seems to fire.
I never receive a log message of "Function Response", therefore, I don't think the post is ever entering the callback.
I've read lots and lots, and attempted a bunch of solutions, including some AJAX. But after about 10 hours, I'm stumped. My $.post is based on the this guide: Save JavaScript variables to PHP/MySQL DataBase Securely with Ajax Post
Thanks for any help you can shed on this.
I'm testing the code on a Windows most recent WAMP Server.
index.php (relevant bit)
$('#radarDropdown').change(function () {
currentRadarId = $('#radarDropdown').val();
var radSel = document.getElementById('radarDropdown');
var currentRadarName = radSel.options[radSel.selectedIndex].text;
document.getElementById('radarSelectedLabel').innerHTML = currentRadarId;
document.getElementById('radarSelectedName').innerHTML = currentRadarName;
getBacks(currentRadarName, processResponse);
// getBackground(currentRadarName);
console.log('Start request');
// document.getElementById('returnBackground2').innerHTML = back1;
// get background image filename for this radar.
});
function getBacks(currentRadarId, callbackFn) {
console.log('Enter getBacks');
$.post(
"getBackgrounds.php",
{radarBOMId: currentRadarId},
function(response) {
console.log('function response');
processResponse(response);
},'json');
};
function processResponse(response){
console.log('Entered processResponse');
console.log(response);
var backgroundFile = response.background;
var locationsFile = response.locations;
var roadsFile = response.roads;
var riversFile = response.riverBasins;
var railFile = response.rail;
var rangeFile = response.range;
var topoFile = response.topography;
var catchFile = response.catchments;
var wthrDistrictsFile = response.wthrDistricts;
var waterwaysFile = response.waterways;
document.getElementById('returnBackground2').innerHTML = backgroundFile;
};
});
getBackrounds.php:
<?php
header('Content-type: application/json');
require_once('dbconnect.php');
$typesArray = array(
'background',
'catchments',
'locations',
'rail',
'range',
'riverBasins',
'roads',
'topography',
'waterways',
'wthrDistricts',
);
$idval = mysqli_real_escape_string($connection, $_POST['radarBOMId']);
foreach ($typesArray as $i => $value) {
$sql = 'SELECT backfilename, backtype FROM InUseRadarsBackgroundsView WHERE productidbom ="'. $idval. '" and backtype = "'.$value.'"';
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$value] = $row["backfilename"];
//console.log('Processed row ' & $i);
}
echo json_encode($response);
} else {
echo " 0 results";
}
}
?>
POST response:
{"background":"IDR503.background.png"}{"catchments":"IDR503.catchments.png"}{"locations":"IDR503.locations.png"}{"rail":"IDR503.rail.png"}{"range":"IDR503.range.png"}{"riverBasins":"IDR503.riverBasins.png"}{"roads":"IDR503.roads.png"}{"topography":"IDR503.topography.png"}{"waterways":"IDR503.waterways.png"}{"wthrDistricts":"IDR503.wthrDistricts.png"}
This is not the complete answer, but try to add other callbacks (e.g. fail callback) to check if some errors occur when you make this POST. Here is an example of how this can be done :
$.post( "example.php", function(data) {
alert( "success" );
})
.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
})
.always(function() {
alert( "finished" );
});
On click button, it suppose to execute a query in the php file either update or delete depending on the button clicked. But I think there's no value passed to the variable $status inside php file when buttons are clicked, thus not executing sql queries.
PHP
<?php
$status = $_GET["status"];
if ($status == "update") {
$conn = mysqli_connect('localhost', 'root','root', 'realestate');
$id=$_GET["id"];
$first=$_GET["firstname"];
$mid=$_GET["middlename"];
$last=$_GET["lastname"];
$add=$_GET["address"];
$gend=$_GET["gender"];
$cont=$_GET["contact"];
$first=trim($first);
$mid=trim($mid);
$last=trim($last);
$add=trim($add);
$gend=trim($gend);
$cont=trim($cont);
$result=mysqli_query($conn, "UPDATE agents SET firstname='$first', middlename='$mid', lastname='$last', address='$add', gender='$gend', contact='$cont' WHERE id=$id");
}
if ($status == "delete") {
$conn = mysqli_connect('localhost', 'root','root', 'realestate');
$id=$_GET["id"];
$result=mysqli_query($conn, "DELETE FROM agents WHERE id=$id");
}
?>
JavaScript
<script type="text/javascript">
data();
function data() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","update.php?status=disp", false);
xmlhttp.send(null);
document.getElementById("data").innerHTML = xmlhttp.responseText;
}
function bb(b) {
var firstid="txtfirst"+b;
var firstname = document.getElementById(firstid).value;
var midid="txtmid"+b;
var middlename = document.getElementById(midid).value;
var lastid="txtlast"+b;
var lastname = document.getElementById(lastid).value;
var addid="txtadd"+b;
var address = document.getElementById(addid).value;
var gendid="txtgend"+b;
var gender = document.getElementById(gendid).value;
var contid="txtcont"+b;
var contact = document.getElementById(contid).value;
update_value(b,firstname,middlename,lastname,address,gender,contact);
document.getElementById(b).style.visibility="visible";
document.getElementById("update"+b).style.visibility="hidden";
document.getElementById("firstname"+b).innerHTML=firstname;
document.getElementById("middlename"+b).innerHTML=middlename;
document.getElementById("lastname"+b).innerHTML=lastname;
document.getElementById("address"+b).innerHTML=address;
document.getElementById("gender"+b).innerHTML=gender;
document.getElementById("contact"+b).innerHTML=contact;
}
function update_value(id,firstname,middlename,lastname,address,gender,contact) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","update.php?id="+id+"&firstname="+firstname+"&middlename="+middlename+"&lastname="+lastname+"&address="+address+"&gender="+gender+"&contact="+contact+"&status=update",false);
xmlhttp.send(null);
}
function delete1(id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","update.php?id="+id+"&status=delete", false);
xmlhttp.send(null);
data();
}
</script>
You have a few issues here. First, I would advise you look into the DRY principle to help you avoid easy to miss problems like not including a status variable in your request.
If you look at your JavaScript you will notice that you are making several requests to the same page, and using copy-paste code to do so. This is a great place to further abstract your code. I would probably use something similar to the following.
Secondly, your PHP script is vulnerable to SQL Injection. How to combat this is well explained here. I can't say for sure that this is your problem, but if you are using a name like O'Reilly it would prevent your script from working. I don't see any other obvious place where your script would go wrong. If anything shows up in your PHP error log, I might be able to help more.
<script>
//Type isn't needed, browsers assume javascript
function httpRequest(method, url, parameters) {
// Build a query string, this could be improved but it works for your current use case.
// It assumes that parameters is an object and does not work for arrays
var query = "";
Object.keys(parameters).forEach(function(key) {
query += encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]) + "&";
});
var xmlhttp = new XMLHttpRequest();
//If possible you should switch to async requests as well.
xmlhttp.open(method, url + "?" + query, false);
xmlhttp.send(); //No need to pass null
return xmlhttp.responseText;
}
function updateRequest(parameters) {
return httpRequest("GET", "update.php", parameters);
}
function data() {
document.getElementById("data").innerHTML = updateRequest({status: "disp"});
}
//bb function removed as it isn't relevant to my point here
function update_value(id,firstname,middlename,lastname,address,gender,contact) {
updateRequest({
status: "update",
id: id, //If you are using a recent browser this can be changed to just id, firstname, ...
firstname: firstname,
middlename: middlename,
lastname: lastname,
address: address,
gender: gender,
contact: contact,
});
}
function delete1(id) {
updateRequest({
status: "delete",
id: id,
});
data();
}
</script>
I want to display a form with a script I adapted from this question. The script is in a file I wrote called queries.js, and its purpose is to print the content of a php form called "dbMinAlert.php" in a div like this <div id="recentExits" name="recentExits"></div> located in my project's index, I tried invoking getNewData(); in my index.php file using this tag <body onLoad="getNewData()"> but it doesn't seem to do anything at all.
var data_array = ''; // this is a global variable
function getNewData() {
$.ajax({
url: "dbMinAlert.php",
})
.done(function(res) {
data_array = res; // the global variable is updated here and accessible elsewhere
getNewDataSuccess();
})
.fail(function() {
// handle errors here
})
.always(function() {
// we've completed the call and updated the global variable, so set a timeout to make the call again
setTimeout(getNewData, 2000);
});
}
function getNewDataSuccess() {
//console.log(data_array);
document.getElementById("recentExits").innerHTML=data_array;
}
getNewData();`
---This php code works and it actually does what I expect it to do. The real problem is the javascript, for all I care the next php form could print a "Hello world" message, but I want it displayed inside the div I placed in my index, without having to post a thing to dbMinAlert.php.
define("HOST", "localhost");
define("DBUSER", "root");
define("PASS", "password");
define("DB", "mydb");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM outputs, products
WHERE products.idProduct=outputs.idProduct
ORDER BY Date DESC, Time DESC limit 5
");
echo '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
echo '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';
}
echo '</ul>';
You have to execute the function for the first time.
getNewData();
It could be the way you are returning the result from php. Instead of doing multiple echo, could you first assign your result in single php variable and finally do single echo.
$result = '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
$result = $result + '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';}
$result = $result + '</ul>';
echo $result;
I found a solution in this question and my code ended up Like this.
I just had to invoke the function in my index by typing <body onload="return getOutput();">
JavaScript
//Min-Max Alerts
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'dbMinAlert.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('recentExits');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('recentExits');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
I am testing whether i could read a item in a .json file into javascript JSON object and display the contents. I need to store the BIDs in the variable R1 array and display it
Code is as follows
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script type="application/javascript">
function loadJSON()
{
var data_file = "data1.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
var R1 = new Array();
for(var i= 0 ; i< jsonObj.length; i++){
R1.push(jsonObj[i].BID);
document.write(R1);
}
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</body>
</html>
AND my data1.json is as follows
[ { "BID" : "4569749", }, { "BID" : "466759", }, { "BID" : "4561149", }, ]
Yes we can load Json objects, As I did in one of my JSP project. here is the code so that you can easily understand.It is calling a servlet which prepare JSON file from the DB.
$('document').ready(function(){
$.ajax({
type: 'POST',
url: 'getCities',
success: function(data) {
var response = JSON.parse(data);
var products = response['city'];
var product_html = '';
$(products).each(function(index, value){
product_html += ""+value['name']+"";
});
product_html += "";
$("#citylist").html(product_html);
}
});
});
here 'getCities' is a servlet which prepare JSON file from Data fetched from Database. It is actually populating the dropdownlist related to particular counties.
One more thing I believe the json file is incorrect. Please check the format with some json validator.
i'm usig this script below, and works perfectly on chrome, and firefox, but on ie, i can't get the response from webservice. I need open/redirect to anothers sites if success or error! Why can read response from webservice on IE, and how resolve this?
function sendInfo(userId, Code) {
// text with all info to send to controller
var values = {
"token": Code,
"code": userId
}
// POST THE CHANGE HERE TO THE DATABASE
var url = "WSFacebook.asmx/saveToken";
$.post(url, values, function(data) {
if (window.ActiveXObject) {
return data.xml;
}
var xmlString = new XMLSerializer().serializeToString(data);
var xml = xmlString,
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc),
$title = $xml.find("string");
var texto = $title.text();
if ($title.text() == "Success") {
window.location = '<%=ConfigurationManager.AppSettings["successUrl"].ToString() %>';
} else {
window.location = '<%=ConfigurationManager.AppSettings["errorUrl"].ToString() %>';
}
});
}