Reload XML data without reload page - javascript

I get xml data from Mysql.. And change anything save again to mysql.
Now i want to see changed data without reload page. How can i do it ?
I get data like that:
downloadUrl("gxml.php", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
i`v tried to do it calling function like that. but didnt work..
function reloaddata()
{
downloadUrl("gxml.php", function(doc));
}
Thanks..

Maybe try using ajax. Pass some values from php to ajax via javascript. And then in ajax retrieve xml data do what ever you want with it. and give a response. Then use
success: function(){
//append it to your html.
}

your code is OK, the problem is about when it is invoked. You will need to pull the data as a response of a timer event, or some other event more related to your logic.
setInterval("downloadMarkers()", 10000); // 10 seconds per call.
function downloadMarkers() {
downloadUrl("gxml.php", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
});
}

Related

Opening the result of GET-request with data in a new tab

I am struggling to find a way in Ajax and JQuery to make a GET-request with data parameters, and to render the response in a new tab in the browser. Something like this:
$('#test-button').on('click', function(e){
var data = {'some_param': [1,2,55,44,3]}
$.get('/test_url/', data, function(html_response) {
// render the HTML contained in html_response in a new tab
});
});
You can do it with:
var newWindow = window.open();
newWindow.document.write(html_response);
But the browser will show a popup alert and you will need to allow it manually.
Working Example:
https://jsfiddle.net/hc3b38bu/

Pass javascript variable to external php file

Yes, there are lots of questions to similar stuff but I can't figure it out, sorry.
I have a file with some javascript variables, depending on user input (but no form) and a normal HTML link to my php file.
<script>
function doStuff() {
var a = 'foo';
var b = 'bar';
window.location = 'newfile.php?a=' + a + '&b=' + b;
}
</script>
go to new php file
That works fine, I can access the data in newfile.php with $_GET.
newfile.php:
<?php
$a= $_GET['a'];
$b= $_GET['b'];
echo($a,$b); // works
?>
But I'd like to use POST. I guess I have to use ajax for that but how exactly?
jQuery is included btw so I could use $.ajax()
Any help is highly appreciated :)
EDIT:
Thanks for the quick response guys!
The JSON parsing doesn't work, I can't really figure out why - after clicking on the button the browser window disappears for a split second and I'm on the same page again which is unresponsive now :(
I went with the following code:
jQuery.post('newfile.php',{'a': a, 'b': b}); //curious: with or without ''?
setTimeout(function () {
window.location = 'newfile.php';
}, 5000); //this will redirct to somefile.php after 5 seconds
newfile.php:
$a= $_POST['a'];
$b= $_POST['b'];
echo('Testing: '.$a);
Right after clicking I can see the correct output in Firebug (Testing: foo) but of course after redirecting to the site the values are lost and I'm left with "Testing: "
What can I do?
You can use ajax to achieve this. Following is the code which works on a button click or anchor click.
HTML
<button type="button" id="button1">Click me </button>
Ajax
$('#button1').click(function() {
var a = $('#IDofYourFormelement').val();
var b = $('#IDofYourFormSecondElement').val();
$.post('/somefile.php', {'somevariable': a, 'variableB': b}, function(data) {
var parsed = JSON.parse(data);
if (parsed == 'success') {
setTimeout(function () {
window.location = '/somefile.php';
}, 3000);//this will redirct to somefile.php after 3 seconds
}
else
{
alert ('Invalid details');
}
});
});
and then in your somefile.php you can access it as
$a = $_POST['somevariable'];
$b = $_POST['variableB'];
//do some stuff and return json_encoded success/failure message
You can use the new with HTML5 FormData();
Code snippet from https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects see also https://developer.mozilla.org/en/docs/Web/API/FormData and http://caniuse.com/#feat=xhr2 for browser support
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
I guess you are trying to post the variables using javascript and display the page post executing your post variables. Found a similar question and an answer in here - JavaScript post request like a form submit.
EDIT
The window.location will call another instance of you page and then will assign or replace the current doc, hence your previous post parameters are lost. If you want the page with your post parameters passed you need to do a form submit to your php page with method=POST also with the post parameters. That's what is written in the above stackoverflow link I shared.

How to get content from another page

I have struggled with this problem for 2 days now. I've found MANY tutorials on similar topics but none have helped me solve my issue yet.
On a Volusion shopping cart I am trying to remotely grab content from the product page and save it's information in a variable for use on the shopping cart. I am unable to use php (not supported by Volusion) and am forced to do this by using javascript (as far as I know). The following code searches the cart items for a certain brand name "Palliser". If that name is present, it grabs the link, uses ajax to send a request to the page associated with the link, and grabs the info I need. It GETS the info I need, but in the process my page turns white and it leaves behind the year, 2013... I have NO idea why this is happening. This is my first time working with ajax so could someone PLEASE help!?!?
$(window).load(function(){
var seat_count = 0;
var i = 0;
var prodLinks = [];
var numSeats = '';
$('b.cart-item-name:contains("Palliser")').filter(function(index) {
prodLinks[i] = 'http://xepwk.cjvgn.servertrust.com/'+$(this).parent('a').attr('href');
$.ajax({
url:prodLinks[i],
//data:string,
async:false,
success: function(result){
var html = jQuery('<div>').html(result);
var prodInfoArray = html.find('span.PageText_L660n').parent('b').parent('td').html().split('<br>');
var numSeats = prodInfoArray[1];
alert(numSeats);
}
});
i+=1;
});
Here is a link to the info that helped me get as far as I did: Get the content of another page's div with jQuery Ajax
You can start ajax requests when DOM ready event fired. Because you don't need images and other staffs to begin ajax requests. Also async:true must be help in your situation.
var seat_count = 0;
var i = 0;
var prodLinks = [];
var numSeats = '';
$(document).ready(function() {
$('b.cart-item-name:contains("Palliser")').filter(function(index) {
prodLinks[i] = 'http://xepwk.cjvgn.servertrust.com/'+
$(this).parent('a').attr('href');
$.ajax({
url:prodLinks[i++],
//data:string,
async:true,
success: function(result){
var html = jQuery('<div>').html(result);
var prodInfoArray = html.find('span.PageText_L660n')
.parent('b').parent('td').html().split('<br>');
var numSeats = prodInfoArray[1];
alert(numSeats);
}
});
});
});
Just a thought, Having:
async:false
Loads your ajax-request synchronously and the request has to complete before you can do anything else. Try to change it to true or remove it (it is true by default).

KDE plasmoid ind autorefresh

I'm trying to write KDE4 plasmoid in JavaScript, but have not success.
So, I need to get some data via HTTP and display it in Label. That's working well, but I need regular refresh (once in 10 seconds), it's not working.
My code:
inLabel = new Label();
var timer= new QTimer();
var job=0;
var fileContent="";
function onData(job, data){
if(data.length > 0){
var content = new String(data.valueOf());
fileContent += content;
}
}
function onFinished(job) {
inLabel.text=fileContent;
}
plasmoid.sizeChanged=function()
{
plasmoid.update();
}
timer.timeout.connect(getData);
timer.singleShot=false;
getData();
timer.start(10000);
function getData()
{
fileContent="";
job = plasmoid.getUrl("http://192.168.0.10/script.cgi");
job.data.connect(onData);
job.finished.connect(onFinished);
plasmoid.update();
}
It gets script once and does not refresh it after 10 seconds. Where is my mistake?
It is working just fine in here at least (running a recent build from git master), getData() is being called as expected. Can you see any errors in the console?
EDIT: The problem was that getUrl() explicitly sets NoReload for KIO::get() which causes it load data from cache instead of forcing a reload from the server. Solution was to add a query parameter to the URL in order to make it force reload it.

internet explorer 9 & javascript variable scoping issue

this code works in Chrome & Firefox but not in IE9 ... need some hints ...
var obj = {
data: [],
json: function() {
var self = this;
$.getJSON("highscore.json", function(resp) {
self.data = resp.splice(0);
});
}
};
Update:
thx for your help ...
it was an issue from the ie9,
ie has thrown the error code "c00ce56e" - it's an issue with charset.
i'll try another header in the php scripts ...
thx # all
Your code looks fine to me, other than that data won't be populated until the json request is done, which is NOT instant because ajax is asynchronous.
obj.json();
alert(obj.data); // []
setTimeout(function(){
alert(obj.data); // ["foo","bar","foobar"]
},5000);
Update
I suggest adding a property to your object called request, and store the $.getJSON request in it. At that point it doesn't make sense to store the data directly on the object because you can always get it from the request.
var obj = {
request: {done:$.noop,fail:$.noop,always:$.noop},
json: function() {
this.request = $.getJSON("highscore.json");
}
};
obj.json();
// you can run the following as many times as you need to use the data.
obj.request.done(function(data){
alert(data.splice(0));
});
just note that in it's current form you must call .json() before you can add callbacks to the request.

Categories