I have been looking for getting XML data into my html page for few days now, and I still can't make it work.
I followed many tutorials, but I can't find the simplest way, to just dump xml data in an html page.
My XML data is generated by a php script.
<exemple>
<data> Hello</data>
<data> World</data>
</exemple>
I have seen people using all kind of tech, like angular.js, and long script, but I feel like things are to complicated for just a simple "print".
I know PHP and I would just do an include or an echo do to that.
The easiest script I found (but cannot make it work) was this one :
function showGetResult( )
{
jQuery.ajax({
url: 'localhost/test/test.php',
type: 'get',
dataType: 'text/xml',
success:function(data)
{
alert(data);
document.write(data);
}
});
}
showGetResult();
My question is :
Can I really hope to make work a script as simple as that ?
Angular js would help me if my whole app is getting data from database using php-xml-ajax ?
I'm very new to ajax, so please be indulgent. Thank you very much
Well since stackoverflow is a place where people thumb down a question posted 5 min ago because they think it's dumb. (actually the only forum i know where you are afraid to post dumb question), I asked somewhere else and I managed to make a working script. Here is it.
I load an txt file when you click on the button.
function submitForm1()
{
var req = null;
document.getElementById("dyn1").value="Started...";
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
req.onreadystatechange = function()
{
document.getElementById("dyn1").value="Wait server...";
if(req.readyState == 4)
{
if(req.status == 200)
{
document.getElementById("dyn1").value=req.responseText;
}
else
{
document.getElementById("dyn1").value="Error: returned status code " + req.status + " " + req.statusText;
}
}
};
req.open("GET", "helloworld.txt", true);
req.send(null);
}
</script>
<form name="ajax1" method="POST" action="">
<p><input type="BUTTON" value="Envoyer" onclick="submitForm1()"></p>
<p>Reçu:
<input type="text" id="dyn1" size="32" value=""></p>
</form>
Related
This is to function in a similar way to slack. I need the page to update dynamically, in case the user is typing.
I have index.php, messages.html and newmessage.php
The chat page (index.php) looks like this:
<h1>Chat</h1>
<?php
echo file_get_contents("./messages.html") ;
?>
<br>
<form action="newmessage.php" method="post">
<input type="text" placeholder= "Compose a new message..." name="message" required>
<input type="submit"><br>
with the php looking like this in newmessage.php:
<?php
$message = $_POST["message"];
$timestamp =date('l jS \of F Y h:i:s A');
$text = "<hr>{$message} <br> from: {$_SERVER['PHP_AUTH_USER']} at: {$timestamp} <br><br> \n";
$file = fopen("./messages.html","a+ \n");
fwrite($file, $text);
fclose($file);
?>
<meta http-equiv="refresh" content="0.5;URL='/chat/index.php'"/>
<p>Sending Message...</p>
So messages show up to the user who sent the message, but not others in the chat. I can't use meta refresh in case other users are typing something and I've tried to make just the <?php echo file_get_contents("./messages.html") ; ?> refresh or use AJAX or event listeners. I need that contents to dynamically update once a new message is posted to messages.html.
Any pointers would be appreciated. Thanks in advance.
update because answer edit was rejected
function reloadData()
{
var now = new Date();
url = 'liveData?' + now.getTime();
try {
req = new XMLHttpRequest();
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
alert("No AJAX Support");
return;
}
}
}
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
}
function processReqChange()
{
// If req shows "complete"
if (req.readyState == 4)
{
dataDiv = document.getElementById('currentData');
// If "OK"
if (req.status == 200)
{
// Set current data text
dataDiv.innerHTML = req.responseText;
// Start new timer (1 min)
timeoutID = setTimeout('reloadData()', 60000);
}
else
{
// Flag error
dataDiv.innerHTML = '<p>There was a problem retrieving data: ' + req.statusText + '</p>';
}
}
}
The best way to get the dynamic updating you are looking for would be AJAX, because you don't really want a real refresh all the time. You said, you tried AJAX? How did that approach look like?
My hint would be to get a basic understanding of web architecture. Try to understand the JS-code you found and how AJAX works. Did you work with JS before? If not, learn the basics.
Change the url variable to the url you use on your server to return the data. Yes, you will need that. Than look at the callback function (processReqChange()).
I would give you more than just hints, but in your early stage it is better to do a lot alone with some hints by more experienced developers.
My code works fine when I run the php script without ajax as a GET request. I get prompted to download the rendered pdf and all is well. However, I need to use ajax because I need to send more info from an html page to the php script than can be handled in a GET request.
What do I need to put into my ajax to make this work?
Thanks
js
function makePDF()
{
var x;
if(window.event) // IE8 and earlier
{
x=event.keyCode;
}
else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
{
x=event.which;
}
keychar=String.fromCharCode(x);
alert(keychar);
if (keychar == 'p' || keychar == 'P')
{
var charSheetHTML = characterSheet.innerHTML;
$.ajax({
url: 'pdf.php',
data: {'charactersheet': charSheetHTML,},
type: 'post',
success: function (data) {**WHAT_DO_I_PUT_HERE??**},
error: function (data) { alert("error\n" + data.toString()); }
});
}
}
pdf.php
<?php
include_once( "bxcharacter/PDFChar.php.inc" );
PDFChar();
?>
PDFChar.hph.inc
<?php
require_once('./tcpdf/tcpdf.php');
function PDFChar(){
$pdf = new TCPDF();
$pdf->AddPage('P');
$pdf->writeHTML($_POST['charactersheet']);
$pdf->Output("character.pdf", 'D');
}
?>
This is not an ajax solution, but you can send your data with this way and if no error occurs, your page will not change.
Create a form element with inputs hidden which contains your data you want to send:
example format:
<form id="myForm" method="GET" action="pdf.php">
<input type="hidden" name="data1" type="hidden" value="your JSON.stringify() data">
</form>
js code (call these where your ajax request is):
var myForm = '<form id="myForm" method="GET" action="pdf.php">';
myForm += '<input type="hidden" name="data1" type="hidden" value="JSON.stringify() data">';
myForm += '</form>';
$("body").append(myForm); // temporarily appending
$("#myData-form").submit(); // submitting form with data
$("#myData-form").remove(); // remove form after submit
And as you said, force download will force file to download and page will remain same. However, if an error occurs, your page will change of course.
I don't know whether this is an effective way or not but in my case, this does the trick.
Old question, but I was trying to do something similar with Laravel PDF extension, and stumbled across this question. I did successfully do this asynchronously with the help of a nice blog post
https://nehalist.io/downloading-files-from-post-requests/
https://github.com/nehalist/download-post-requests
The using the form method, like the previous answer works fine too, but maybe this will help anyone else trying to achieve this with AJAX. The author's XMLHttpRequest method worked great for me!
The code that worked for me (almost verbatim from the blog post) ->
document.getElementById('exportpdf').addEventListener('click', function () {
var request = new XMLHttpRequest();
request.open('POST', '/your/post/endpoint/here', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function() {
if(request.status === 200) {
var disposition = request.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
var blob = new Blob([request.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};
I tried to get it to work with jQuery AJAX but failed, so I went with XMLHttpRequest. With jQuery, The download would work, but the content was always empty. I tried to do something like in this post -
https://keyangxiang.com/2017/09/01/HTML5-XHR-download-binary-content-as-Blob/
$.ajax does not support either arraybuffer or blob as its dataType. Thus we need write a beforeSend handler:
//setup ajax
$.ajaxSetup({
beforeSend:function(jqXHR,settings){
if (settings.dataType === 'binary'){
settings.xhr().responseType='arraybuffer';
settings.processData=false;
}
}
})
//use ajax now
$.ajax({
url:url,
dataType:"binary",
success:function(data){
console.log(data); //ArrayBuffer
console.log(new Blob([data])) // Blob
}
})
But never got it to work. Maybe someone smarter can figure out the jQuery method :)
I have a form with x number of fields. When submitted, I want to;
get all input data, $var = $_POST['input']
validate input, (!empty($var) && is_numeric($var))
stick it in an array, array_push($myArray, $var)
generate URLS, $url.=$var
process the URL's without leaving the page
1 - 4 already done in php
Simply, im not familiar with Ajax. Been a decade since ive touched Javascript. Im not sure if i should be using javascript to do the whole process. However, would prefer php to validate, Ajax to do http requests. Any sample code/sites available that passes php var's/array to Ajax to handle http requests?
You'll want to use some kind of format to pass data from the server to the client. I recommend JSON. PHP has a built-in function to encode an array into it, and JavaScript parses it natively.
As for the AJAX part itself, I recommend using a framework like JQuery. Makes it way simpler, and you don't have to deal with the different browsers yourself.
$.ajax({
url: "yourpage.php",
success: function(data){
alert(data);
}
});
I guess something like this-
$urlfield = explode(",", $urls);
You want to pass this array via jQuery AJAX, with this:
<form id="myForm">
<input type="hidden" value="'.$urlfield.'">
<input type="submit" id="processURL" class="Submit" name="ok" value="Send Reply"/>
</form>
And here's your jQuery:
$("#processURL").click(function(event){
event.preventDefault();
var urlUsed = $("#urlfield").val();
$.ajax(
{
type: "POST",
url: urlUsed,
data: ,// you can send some data
beforeSend: function() {
$("#processingURL").show(); //SOME FUNCTION TO SHOW URL PROCESSING
},
success: function() {
alert("Success");
}
});
});
// browser support code
function getXMLHTTP()
{ //fuction to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
// external file to linkup
function secondpage(countryId) {
var strURL = "secondpage.php?country=" + countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('sid').innerHTML = req.responseText;
} else {
document.getElementById('sid').innerHTML = req.responseText;
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
in secondpage.php page ( i will get $_REQUEST['country'];)
I have a working PHP script on my server and a HTML page with JavaScript and AJAX which I would like to call and run the PHP script. However, the AJAX responseText is displaying all the PHP code rather than running it. What do I need to do to only get the results of the PHP? Other examples I looked at used the responseText and it seemed to work out well, but not for me :(
Thanks,
elshae
My AJAX code is below...my PHP works fine, it has been tested :)
function ahah(url) {
//document.getElementById(target).innerHTML = ' Fetching data...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
var div = document.createElement('DIV');
div.innerHTML = req.responseText;
document.getElementById('chicken_contentDiv').appendChild(div);
} else {
" <div> AHAH Error:\n"+ req.status + "\n" +req.statusText + "</div>";
}
}
}
function load(name) {
ahah(name);
return false;
}
<div> + load('./getFiles.php') + </div> //called in a div
Ok here is the new code:
//Some stuff happens here, IMO think it's irrelevant to this issue...
//This is where the AJAX/JQuery calls the php
var info = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost:8080/geoserver/wms',
title: 'Identify features by clicking',
queryVisible: true,
eventListeners: {
getfeatureinfo: function(event){
map.addPopup( new OpenLayers.Popup.AnchoredBubble(
"chicken",
map.getLonLatFromPixel(event.xy),
null,
event.text + '<div> Hello Tibet :)</div>' + $('#chicken_contentDiv').load('http://localhost/mapScripts/getFiles.php'), //have also tried localhost:80, no diff
null,
true
));
}
}
});
map.addControl(info);
info.activate();
});
To your apache config or .htaccess file add this line AddType application/x-httpd-php .html so html files will be parsed with php interpreter.
Are you missing the <?php at the beginning of your getFiles.php file?
If the response contains actual PHP code, then it is not being processed by the PHP interpreter. Where are you running this? It is obvious that the web server is not properly configured to process PHP files.
EDIT:
The line you have:
event.text + '<div> Hello Tibet :)</div>' + $('#chicken_contentDiv').load('http://localhost/mapScripts/getFiles.php'),
is incorrect.. you don't want to append the outcome of the jQuery function. The output would always be an object. You just want to run that script, which would populate a DIV with an ID of chicken_contentDiv. (is that really the right DIV to put the details in?)
It should be at the end, after your var info declaration is closed and done.
I'm trying to begin learning AJAX, and I've already hit a little stump. So I'm starting simple and just trying to get an alert to pop up showing the length of the string the user types into a text field.
The HTML:
<form action="/scripts/addemail_fb.php" method="post">
<input type="text" name="email" value="Enter your email here!" />
<input id="submit" type="submit" name="submit" value="Go!" onClick="check(this.form.email.value);"/>
</form>
The JS:
function check(email) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
email=encodeURIComponent(email);
req.open("POST","/scripts/addemail.php");
req.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8');
req.send(email);
req.onreadystatechange=function() {
if(req.readyState==4) {
result = req.responseText;
alert("The length of the email is:" + result);
}
}
return false;
}
The PHP (addemail.php):
<?php
function check_email($input) {
return strlen($input);
}
$email = urldecode(implode(file('php://input')));
$result = check_email($email);
echo $result;
?>
And yes, I've included the JS in the section. I got this almost directly from a tutorial so I'm not sure what's going on. My testing browser is Safari, but I've also tried FF. Sorry is this is obvious, as this is my very first AJAX attempt. Thanks!
EDIT: Sorry, the problem is that its just going to the file described in action="addemail_fb" instead of the JS.
-iMaster
Change the onclick handler to onsubmit (on the form), like so:
<form onsubmit="return check(this.email.value);"> ... </form>
Also, set your req.onreadystatechange before calling req.send ()
inline javascript is bad practice. this solution may seem a bit more convoluted but if you implement it into the rest of your scripts then you will find this much more elegant.
JS libraries use similar methods, but if you cant use one then do this instead:
onDomReady(function(){
var oForm = document.getElementById("myform");
addListener(oForm,"submit",function(){
removeListener(oForm,"submit",arguments.callee);
// do stuff here
});
});
// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{
bubbling = bubbling || false;
if(window.addEventListener) { // Standard
element.addEventListener(type, expression, bubbling);
return true;
} else if(window.attachEvent) { // IE
element.attachEvent('on' + type, expression);
return true;
} else return false;
}
// Cross-browser implementation of element.removeEventListener()
function removeListener(element, type, expression, bubbling)
{
bubbling = bubbling || false;
if(window.removeEventListener) { // Standard
element.removeEventListener(type, expression, bubbling);
return true;
} else if(window.detachEvent) { // IE
element.detachEvent('on' + type, expression);
return true;
} else return false;
}
function onDomReady(fn) {
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
fn();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
fn();
} else {
setTimeout( arguments.callee, 0 );
return;
}
});
} else {
// A fallback to window.onload, that will always work
addListener(window,"load",fn);
}
}
Here is the problem:
You are doing it wrong.
And jQuery is the Answer.
But seriously. Try using jQuery, as it will make you Javascript life easier than cutting into a piece of pumpkin pie.
AJAX is one of the most annoying subjects in Javascript, and jQuery, along with other libraries have gone and made the problem much easier to deal with. Plus, there are many many other great features of jQuery that just make it so much more wonderful to work with Javascript.
In jQuery, the entire code would look like:
$.post("/scripts/addemail.php", {email_address:email}, function(data){
alert("The length of the email is:"+data);
});
Speaking of pumpkin pie.....
Now that I've finished my public server announcement for jQuery, you will want to check the Javascript console (Ctrl + Shift + J in Firefox), and run the page. It will give you any errors that you are bound to have such as syntax errors or various other things that go wrong.
If you can go there and then give us any error messages that pop-up, we will be more likely to be able to solve your problem.