This is my first time using AJAX, and I'm trying to send JS variables to a PHP script. I've got an XMLHttpRequest but it doesn't seem complete - what am I missing?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
else {
document.write("Geolocation is required for this page.");
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// document.write("<a href='http://api.geonames.org/findNearbyPlaceNameJSON?lat="+lat+"&lng="+lng+"&username=sebastiano'>my town</a>");
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.open("GET","location.php?lat=position.coords.latitude",true);
xmlhttp.send();
// SOMETHING MISSING HERE?
}
function errorFunction(position) {
document.write("Error");
}
It appears that you're not passing the contents of your variable to the open command.
xmlhttp.open("GET","location.php?lat=position.coords.latitude",true);
in this example your lat will contain a string with contents "position.coords.latitude"
instead try
xmlhttp.open("GET","location.php?lat="+position.coords.latitude,true);
Or better yet, use the variables you created at the top of the function and pass both long and lat in.
xmlhttp.open("GET","location.php?lat=" + lat + "&long=" + lng,true);
you are sending it with "position.coords.latitude" as value...
try xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);
Also, take a look at jQuery
Try this:
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){
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);
xmlhttp.send();
Related
I made a chat website. And it has a div with id=chatlogs. I want it to get chatlogs from logs.php every 2 seconds. How can I do that? I want to use ajax with it and avoid using jquery.
You can do smoething like this:
<script>
setInterval(refresh_logs(), 2000); // 2000 = 2 Seconds
function refresh_logs()
{
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("logs_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","get_logs.php",true);
xmlhttp.send();
}
</script>
I'm running the following javascript that check with serverside (keep.php)
if user has a session.
The script is running onload of every page: handler.js
var server = location.host;
var url = "http://" + server + "/MyHome2/php/";
var page = "keep.php";
document.onload = checkAuth();
function checkAuth()
{
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)
{
var response = xmlhttp.responseText;
if (response != "")
{
document.getElementById("linkSign").innerHTML = response + "|" ;
}
else
document.getElementById("linkSign").innerHTML = "Sign-in|" ;
}
}
xmlhttp.open("POST",url + page,true);
xmlhttp.send();}
My server-side keep.php which echo back session is:
<?php
session_start();
if (isset($_SESSION['name']))
{
echo $_SESSION['name'];
}
?>
This script is running in the begging of each html page to check if user has a session and if it does it grrets him.
The problem that this script is messing with my other scripts! that used to work and are working without this handler.js
For example my login script which log-in a user is not working when user try to submit his credentials, noting happens!
var server = location.host;
var url = "http://" + server + "/MyHome2/php/";
var urlmain = "http://" + server + "/MyHome2/index.html";
var page = "authentication.php";
function loginUser(){
var str = "usr=" + encodeURIComponent(document.getElementById("user").value) + "&pwd=" + encodeURIComponent(document.getElementById("password").value);
checkUserExistance(str,str.length);}
function checkUserExistance(data,size){
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)
{
var response = xmlhttp.responseText;
responseHandler(response);
}
}
xmlhttp.open("POST",url + page,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length",size);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(data);}
Why is the simple session check onload of each page is preventing mt other script from executing?!
Okay I've found my mistake :)
Apparently the scripts are considered as a same scope although they are on different files.
I have global variables with the same name and this is no no if I reference those scripts from the same html page.
This will load the content to the page and change the URL. The problem is that the back button and the forward won't load the content agin. They only change the URL. How can I make them load the function?
<a onclick="load_content('p1');" >Page1</a>
<a onclick="load_content('p2');" >Page2</a>
function load_content(name)
{
window.history.pushState(null, null, "/?page=" + name + "");
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("response").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","load_content.php?name=" + name + "",true);
xmlhttp.send();
}
In the history.pushState, save all relevant data that is dynamic and then listen to the popState event and replace all elements just like you would do with AJAX.
Well, i have an select list in my php page and i want to refresh only that with new data from my database.Idone it using ajax but on android or other mobiles OSes this messes up the layout.Is there a problem with protable OSes and ajax?Can you give me any hints to solve this problem?
Edited
/*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)
{
var sel1 = document.getElementById("select1");
var selectedI = sel1.selectedIndex;
var i=0;
var excode = excur[selectedI];
var val = sel1.options[selectedI];
excursioncode=excode;
excindex = selectedI;
val.innerHTML = xmlhttp.responseText;
//alert(xmlhttp.responseText);
//setTimeout("loadXMLDoc();",10000);
}
}
xmlhttp.open("POST","<?php echo SITE_ROOT;?>ajaxphp/ajax_get_seats.php?excode="+excursioncode+"&date="+selected_date,true);
xmlhttp.send();
}
function timedRefresh(timeoutPeriod) {
tm=setTimeout("loadXMLDoc();",timeoutPeriod);
}
*/
This is some code that is doing the job.On a regular pc is working but on a mobile browser brings up problems.Anyu ideas
If the problem were with the AJAX, it would not be causing layout issues. Instead the problem is most likely with your implementation of using the data retrieved by AJAX. However, I can't provide any more insights because I have no clue what you're working on and have never experienced such a problem.
Whats wrong with this code or what might be causing this problem? It's not alerting "hello", but it is filling the div with The Hello and Bye World tables. I want it to alert "hello". Also I don't know jquery. Thank You
FILE1
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){
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = xmlhttp.responseText.replace(reScript, function(m,m1) {
eval(m1);
return "";
});
document.getElementById("div").innerHTML=response;
}
}
xmlhttp.open('GET','file2.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send();
FILE2
<table><tr><td>Hello World</td></tr></table>
<script type="text/javascript">
alert('hello');
</script>
<table><tr><td>Bye World</td></tr></table>
Try without the eval():
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){
/*var reScript = /\<script.*?>(.*)<\/script>/mg;
response = xmlhttp.responseText.replace(reScript, function(m,m1) {
eval(m1);
return "";
});*/
document.getElementById("div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','file2.php',true);
//xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //unnecessary for GET calls
xmlhttp.send(null);
Evaluing your code inside the <script...></script> is unnecessary, the javascript code will be executed as soon as it's added to the DOM.
New edit:
You have to eliminate the linebreaks \n\r in your reponseText in order for your script to be evaluated properly. Also, there was an extra \ escape character before the first < which was breaking your code. Try:
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){
var reScript = /<script.*?>(.*)<\/script>/mg;
response = xmlhttp.responseText.replace(/\n|\r/g, " ").replace(reScript, function(m,m1) {
eval(m1);
return "";
});
document.getElementById("div").innerHTML=response;
}
}
xmlhttp.open('GET','file2.php',true);
//xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(null);
I've added a .replace(/\n|\r/g, " ") to replace all line breaks by an white space in your responseText, which will allow for your JS to be evaluated properly and cause no visible change to the end-user. You may also replace the white space " " by an empty string "" if all of your JS is properly semi-colon'd.
The above should work fine for simple scripts, now if you'd include the JQuery lib in your page's head:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Your AJAX call would be as simple as:
<script type="text/javascript">
$(document).ready(function(){
$('#div').load('file2.php');
});
</script>
JQuery automatically parses scripts from your responseText, as noted in your linked answer.
Give this a try:
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var reScript = /<script.*?\>(.*)<\/script\>/mg.exec(xmlhttp.responseText)[1];
var scriptElement = document.createElement('script');
scriptElement.innerHTML = reScript;
document.body.appendChild(scriptElement);
}
}
Placing the code into a script element, and then appending that element to the body should cause it to execute.