I have 3 files, one HTML, PHP and JS. I have a button in HTML and I want to trigger the PHP file when it's clicked, through Javascript. I tried the following code, but for some reason it gives me the error message every time:
JavaScript
function getOutput() {
getRequest(
'create_json.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('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
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;
}
<button id="submit" onclick="getOutput()">Submit</button>
<div id="output">waiting for action</div>
<?php
function get_data(){
$connect=mysqli_connect("localhost", "root", "root", "openingpage");
$query="SELECT * FROM created_list ";
$result=mysqli_query($connect, $query);
$list_data=array();
while($row=mysqli_fetch_array($result)){
$list_data[]=array(
'ModelID' => $row["ModelID"],
'ImageID' => $row["ImageID"],
'ListID' => $row["ListID"]
);
}
return json_encode($list_data);
}
$file_name=date('d-m-Y').'.json';
if(file_put_contents($file_name,get_data())){
echo $file_name.' file created';
}
else{
echo 'There is some error';
}
?>
I'm always getting the "Bummer: there was an error!" message. Why can't I get it . I checked the code more than 100x times but can't find whats going wrong in this code.
Thanks in advance.
Related
I have created a js file to fetch data from a txt file and display it on html but it does not seem to work properly.
//Event Handling
document.addEventListener("DOMContentLoaded",
function (event){
console.log("Inside DOMContentLoaded");
document.getElementById('but').addEventListener("click", function (){
console.log("inside first");
$ajaxUtils.sendGetRequest("/Data/name.txt", function(res){
console.log("inside getRequest");
console.log(request.responseText);
});
});
});
console.log("HELLO");
And here is the code for sendGetRequest.
(function (global){
var ajaxUtils = {};
//Returns an Http Request Object
function getRequest()
{
if(window.XMLHttpRequest){
return (new XMLHttpRequest());
}
else {
global.alert("Ajax is not supported");
return (null);
}
}
//Makes an AJAX request to 'requestURL'
ajaxUtils.sendGetRequest = function(requestURL, responseHandler, isJsonResponse) {
var request = getRequest();
request.onreadystatechange = function() {
handleResponse(request,responseHandler,isJsonResponse);
}
request.open("GET", requestURL, true);
request.send(null); //For POST only
}
//Only calls user provided 'responseHandler'
//function if response is ready
//and not an error
function handleResponse(request,responseHandler,isJsonResponse)
{
if((request.readyState == 4) && request.status == 200){
if(isJsonResponse == undefined)
isJsonResponse = true;
if(isJsonResponse === true)
responseHandler(JSON.parse(request.responseText));
else {
responseHandler(request.responseText);
}
}
}
global.$ajaxUtils = ajaxUtils;
})(window);
Location of js file: /js/ajax-utils.js and /js/script.js and Location of data file: /Data/name.txt
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;
}
Here is the code. I am fairly new to JavaScript and I'm learning more every day. This code is from an example from a textbook. Thank you for your responses. Another question I'd like to ask is how can I display the returned text in an unordered list? Would that be something to include in the html side of things or can it be done within the JavaScript file?
window.addEventListener("load",initAll,false);
var xhr = false;
function initAll() {
document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);
document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);
}
function getNewFile(evt) {
makeRequest(this.href);
evt.preventDefault();
}
function makeRequest(url) {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (xhr) {
xhr.addEventListener("readystatechange",showContents,false);
xhr.open("GET", url, true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);
}
else {
var outMsg = xhr.responseText;
}
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
function getText(inVal) {
if (inVal.textContent) {
return inVal.textContent;
}
return inVal.text;
}
}
By the looks of it, you are making an AJAX request and are receiving XML.
In this case, I would:
Open up a new page with window.open()(returns a new Window object)
And then change the document.body.innerHTML of that new page to the XML you have
If you had a webpage that held the XML(maybe the server you are requesting to has one), you can just do:
window.open("page.xml");
I'm not sure if this is related to an ajax call or not. I'm very new to Ajax, and so I suspect it is the cause.
I run the following javascript:
function GetXmlHttpObject() {
"use strict";
var objXMLHttp = null;
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
objXMLHttp = new window.ActiveXObject("Microsoft.XMLHTTP");
}
return objXMLHttp;
}
function delete_director(i) {
"use strict";
var r, url;
r = window.confirm("Are you sure you want to disable this director");
url = "ajax.php?task=director&event=delete&UserId=" + i;
if (r === true) {
mdata = new GetXmlHttpObject();
if (mdata === null) {
alert("Browser does not support HTTP Request");
return;
}
mdata.open("GET", url, true);
mdata.send(null);
}
}
And that calls into the following php function:
function deletedirector()
{
$UserId=mysql_real_escape_string($_GET['UserId']);
$query = "update tbl_users set IsDisabled='1' where UserId=".$UserId;
$result = mysql_query($query) OR die('Cannot perform query!');
if ($result) {
error_log("a");
?><script type="text/javascript">window.location='index.php?task=director&success=Director Successfully Deleted.'</script><?
} else {
error_log("b");
?><script type="text/javascript">window.location='index.php?task=director&error=Director Deletion Failed.'</script><?
}
}
The db shows that the director was deleted, and "a" prints in the error log, but the window.location never fires.
The user experience is that the browser prompts for confirmation, and after that - nothing. A javascript console shows now error.
Any ideas?
You already return new object (of XMLHttpRequest API) with function, so you don't need new here
...
if (r === true) {
mdata = GetXmlHttpObject();
...
and try to use onreadystatechange like this
mdata.onreadystatechange = function(){
if (mdata.readyState === 4) {
alert("some text");
} else {
alert(mdata.status);
}
};
I am querying a PostGIS database based on where a user clicks on a google map. I am then parsing the JSON response into a googleMaps infoWindow. This has been working great but I'd now like to query multiple urls and use those responses to fill in the infoWindow. Below is an example of the functions I've used that work great. Note: please disregard the url provided as I just made it up for this example.
var clickLoc;
function queryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var loUrl = 'http://www.myspatialdataset.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = clickResponse;
try {
req.open("GET", loUrl, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = clickResponse;
req.open("GET", loUrl, true);
req.send();
}
}
}
function clickResponse(){
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
var clickPingBack = JSON.parse(req.responseText);
var loResponse = clickPingBack;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
fillWithClicked(loResponseParsed);
}
else
{
var loResponseParsed=' other';
fillWithClicked(loResponseParsed);
}
}
}
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(loResponseParsed){
infowindow.setContent(loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
How could I now do this for multiple url requests and pass those responses to the same, fillWithClicked function that fills in the infoWindow?
The code below is obviously wrong but may better explain what I am trying to do i.e. multiple URLS and filling the infoWindow with the response from two url requests. This sometimes works but is totally wrong
var clickLoc;
function distQueryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var distUrl = 'http://www.myspatialdataset.com/sql/?q=select%20district%20from%20mt_elk%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
distReq = new XMLHttpRequest();
distReq.onreadystatechange = loQueryAct(clickLoc);
try {
distReq.open("GET", distUrl, true);
} catch (e) {
alert(e);
}
distReq.send(null);
} else if (window.ActiveXObject) { // IE
distReq = new ActiveXObject("Microsoft.XMLHTTP");
if (distReq) {
distReq.onreadystatechange = loQueryAct(clickLoc);
distReq.open("GET", distUrl, true);
distReq.send();
}
}
}
function loQueryAct(clickLoc){
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var loUrl = 'http://www.myspatialdataset.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
loReq = new XMLHttpRequest();
loReq.onreadystatechange = distClickResponse;
try {
loReq.open("GET", loUrl, true);
} catch (e) {
alert(e);
}
loReq.send(null);
} else if (window.ActiveXObject) { // IE
loReq = new ActiveXObject("Microsoft.XMLHTTP");
if (loReq) {
loReq.onreadystatechange = distClickResponse;
loReq.open("GET", loUrl, true);
loReq.send();
}
}
}
function distClickResponse(){
if (distReq.readyState == 4 && loReq.readyState == 4) { // Complete
if (distReq.status == 200 && loReq.status == 200) { // OK response
var distPingBack = JSON.parse(distReq.responseText);
var distResponse = distPingBack;
var loPingBack = JSON.parse(loReq.responseText);
var loResponse = loPingBack;
if (distResponse.rows.length>0)
{
var distResponseParsed=distResponse.rows[0].district;
}
else
{
var distResponseParsed=' other';
}
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
}
distFillWithClicked(loResponseParsed,distResponseParsed);
}
}
var infowindow = new google.maps.InfoWindow;
function distFillWithClicked(distResponseParsed,loResponseParsed){
infowindow.setContent(distResponseParsed+loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
I figured it out. Using getJSON instead of XMLHttpRequest was the key. I know this could be cleaner but it does work.
var clickLoc;
function queryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var toFillArray=Array();
var loUrl='http://www.mypostgis.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
var distUrl='http://www.mypostgis.com/sql/?q=select%20district%20from%20mt_elk%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
$.getJSON(loUrl,function(tmpLoDat){
if (tmpLoDat.rows.length>0)
{
var tempCat=tmpLoDat.rows[0].ownercateg;
toFillArray.push(tempCat);
}
else
{
var tempCat='other';
toFillArray.push(tempCat);
}
otherFunction(toFillArray,distUrl);
})
}
function otherFunction(toFillArray,distUrl){
$.getJSON(distUrl,function(tmpDistDat){
if (tmpDistDat.rows.length>0)
{
var tempDist=tmpDistDat.rows[0].district;
toFillArray.push(tempDist);
}
else
{
var tempDist='Other';
toFillArray.push(tempDist);
}
fillWithClicked(toFillArray);
})
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(toFillArray){
infowindow.setContent(toFillArray[0]+toFillArray[1]);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
If you want the data to grow your element, let's try something like that :
function fillWithClicked(loResponseParsed){
document.getElementById("regulations").innerHTML += loResponseParsed;
}
If the calls of your function are not in the same page, you'll need to use a cache file and a user_id (session id, cookie id or IP adress...):
// js & jquery for example
function fillWithClicked(loResponseParsed,user_id)
{
$.post('cachecreate.php',{content:loResponseParsed,user_id:user_id},
function()
{
$.get('cachefile_'+user_id+'.html',
function(data)
{
document.getElementById("regulations").innerHTML=data;
});
});
}
// cachecreate.php for example
<?php
$cache = "cachefile_".$_POST['user_id'].".html";
ob_start();
if(file_exists($cache))
{
include($cache);//or readfile(); i forgot...
echo "<hr/>".$_POST['content'];// Strip <hr/> for JSON
}
else
{
echo $_POST['content'];
}
$page_content=ob_get_contents();// if JSON needed : json_encode($page_content);
ob_end_clean();
file_put_contents($cache, $page_content);// PHP 5+ function
?>
I hope that it may help you, or bring you to the solution.
EDIT regarding your new details
Try something like this (I lighten your code...).
With this you can add as multiple urls as you want.
var clickLoc;
function queryAct(event)
{
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var url=Array();
var data=null;
url['loUrl'] ="url1";
url['distUrl'] ="url2";
url['otherUrl'] ="urlx";
for(page in url)
{
data+=getJSON(page);
}
fillWithClicked(data);
}
function getJSON(url)
{
if (window.XMLHttpRequest)
{req = new XMLHttpRequest();}// Non-IE
else if (window.ActiveXObject)
{req = new ActiveXObject("Microsoft.XMLHTTP");}// IE
if(req)
{
req.open("GET", url, true);
req.send(null);
req.onreadystatechange = function() {
if(req.readyState == 4)
{
if (req.status == 200)
{ // OK response
var clickPingBack = JSON.parse(req.responseText);
var loResponse = clickPingBack;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
return loResponseParsed;
}
}
}
}
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(loResponseParsed)
{
infowindow.setContent(loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
EDIT -> External domain files
httpRequest doesn't work with files in another domain.
You can use one of those solutions, I may use the second for me.
PHP Solution
// In your js file, change the urls like this
url['url_x'] ='myphppage.php?url=url_x_to_parse';
// myphpage.php script that displays the content of the external file
<?php
if(isset($_GET['url'])) {
header("Content-type: text/json");
echo file_get_contents(urldecode($_GET['url']));
}
?>
JQUERY solution (better one)
// change the name of getJSON function cause jquery uses the same name...
function getURLcontent(url)
{
$.get(url,function(data){
var clickPingBack = JSON.parse(data.responseText);
var loResponse = clickPingBack;
loResponse=data;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
return loResponseParsed;
});
}
download jquery library http://code.jquery.com/jquery-1.7.1.min.js
include jquery plugin in the head of your page with <script src="jquery-1.7.1.min.js"></script>