This is going to be about the same issue as my previous question (Loading a php file into cross domain page with dynamic element height) but now with trying to use a new method.
I found a way to load my script into an ajax div locally but there still remains the issue of cross domain security not allowing the xmlhttprequest to call to my other server.
The issues here is still that on Site A, which is my web server that I have full access to and is hosting my scripting files, I can do whatever I want with the script and make it work. On Site B, which is the on Enjin server, I have no access to host scripts. I can place .js scripts there and run those, but I can't use php from their servers which creates my issue. To get around this right now, I am using an iframe, which is inefficient to say the least. It can't load a dynamic height from the contents being generated by the php file it is calling from Site A. I planned on fixing this with loading this into a div via AJAX but I am having a few issues with that.
My AJAX script is this:
<pre><code>function Ajax(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("No AJAX!?");
return false;
}
}
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById('ReloadThis').innerHTML=xmlHttp.responseText;
setTimeout('Ajax()',10000);
}
}
xmlHttp.open("GET","http://sitea.com/twitch_api/stream_header.php",true);
xmlHttp.send(null);
}
window.onload=function(){
setTimeout('Ajax()',10000);
}
</code></pre>
then obviously the div is following the script.
the script that this is calling is this:
http://pastebin.com/mC8kakKJ
Sorry, can't get all the code to parse correctly in the code block but i made a pastebin copy of the script
My questions here become. What does my script need to look like for use with easyXDM? I have no experience with a library like this or cors, so an example markup would be awesome.
I am also not all that versed in javascript/ajax which leads to my second question. I my ajax code listed above, how would i go about having that div populate with the desired file immediately then update every 300000ms (5 minutes).
Any help is appreciated. Have a post on the Enjin forums but not too many there have experience going to this depth.
You could use $.getJSON(), Enjin pages use jQuery. Just make sure your server response is wrapped in a callback function so the cross site request is allowed.
Related
I am able to call javascript functions from a JS file without any issues. When I move AJAX functions into the same file then the functions cannot be called. Do AJAX functions require that they are in the same file that they're called from?
Home.html
<button onclick=scale(id)>scale</button>
<button onclick=save(id)>Save</button>
Javascript.js
function scale(id){
//scales the element with the given id
//works
}
function save(id){
//Does not work unless in Home.html file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "SaveValue.php?id="+id, true);
xmlhttp.send();
SaveValue.php
//Sends value to mysql db
-Update-
When I moved the AJAX function into a different JS file by itself, and linked it in the html file, everything worked.
JavaScript functions which perform Ajax options are no different from any other function as far as loading them is concerned.
There is no requirement to include the function inline in the HTML document.
You do, of course, still, need a <script> element to load them (or resort to things like fetching the script data with XMLHttpRequest and running it through eval — which is not recommended!).
If you have a problem, then it is most likely due to the <script> element failing to load the file. The most common reasons for this are revealed by the developer tools in your browser:
The URL is wrong (the Network tab will tell you that you aren't getting a 200 OK response)
The Content-Type is not application/javascript (or the legacy text/javascript). The Console will report an error and the Network tab will show the Content-Type.
The HTML for the <script> element is wrong or in the wrong place (this will often be picked up by the use of a Markup Validator).
I am developing a magento webstore where there is a page where customer can pick the route where he/she wants to pick up the order. The selection is twofold and at the moment two different set of buttons so no checkbox or radio buttons. First the user picks the date then then the place.
Right now i am calling a javascript function which loads a cookie on button press then reloads the page and returns user to an anchor link so the user doesn't get confused where he was when making the first selection. When the page reloads the sidebar contains php which reads the contents of the cookies. This doesn't feel very intuitive and I am sure there is a much better way to do this. The choices user has made should be displayed on the sidebar shopping cart which is a .phtml file. Just a simple "you have chosen the route x" is enough, right now I have an echo but the page has to reload first.
So in short when user makes a choice the sidebar should update with information about the choice, without the page reloading itself and returning to position with the help of anchor-links. The notification should preferably be in the left sidebar. I don't think I want to use popups or temporary notifications but they could be an additional feature.
I am pretty sure this is a very simple question but for some reason I cant seem to find the right keywords and then there is magento itself.
OK This is the best one I have come up so far. I still consider it only partially solved and I think I could get more help from a magento community but for now it works well enough.
Include this script to the custom.phtml header:
<script type="text/javascript">
function AJAX(){
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
}
// Timestamp for preventing IE caching the GET request (common function)
function fetch_unix_timestamp()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
// Reload div with php
function refreshdiv_timediv(){
var seconds = '3';
var divid = "ajax";
var url = "routes/customer_needs_to_see_this.php";
var xmlHttp_one = AJAX();
// No cache
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp_one.onreadystatechange=function(){
if(xmlHttp_one.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp_one.responseText;
setTimeout('refreshdiv_timediv()',seconds*1000);
}
}
xmlHttp_one.open("GET",nocacheurl,true);
xmlHttp_one.send(null);
}
// Start the refreshing process
window.onload = function startrefresh(){
setTimeout('refreshdiv_timediv()',seconds*1000);
}
</script>
Then I place customer_needs_to_see_this.php to folder routes in the www root directory. The script above will automatically refresh the div "ajax" and inside the ajax-div there is a php include routes/user_needs_to_see_this.php. The div with include is located in cart_sidebar.phtml
I had to place the file outside of magento's template files because I couldn't do includes like ../template/checkout/customer_needs_to_see_this.php. Includes work when they are in the same folder as the view (phtml-file) file but otherwise it doesnt seem to work. Also I couldn't get the script to fetch the user_needs_to_see_this.php from magento's template files.
Right now it updates itself every 3 seconds when customer is on the custom.phtml page. I think its ok because its just reading and making cookies so its not anything heavy. I might change it to onclick in the future.
I got the code here.
There are plenty other examples like that but the above example seems to cover most of the bases.
Ok, this is my second post, and PLEASE accept that I am a complete newbie, willing to learn, spending many hours trauling various sites for answers, and I've almost got to where I need to be (at least for this bit).
I have a web page which has a nubmer of javascript functions that work together to generate a Google Map with various lines etc. using the google maps API.
I also have a MySQL Database with some information in.
I have created a PHP script to dynamically generate a dropdown box with information from the database. (and that bit seems to work fine) - http://www.bournvilleconservatives.com/temp/select.php
What I now need to do is get that dropdown box to appear in the HTML / Javascript page that I already have, so that when a user selects something from the list, it calls a javascript function with the value selected.
I'm told I need to use AJAX to pull the box in, and use innerhtml to display it, but I really have no idea how, and could do with an example of something similar to help me on my way.
I would put the PHP in the html page, but that page is actually wrapped up in a Joomla! wrapper, so its all rather complicated.
Thanks in advance.
jQuery solution
If you are willing to use jQuery, it will help you a lot with accessing the DOM, making Ajax calls and stuff. Let me give you a solution in jQuery:
First, put a div into HTML (this will store your select box):
<div id="i_want_my_select_here"></div>
Then put this code in the end of you HTML before </body>.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#i_want_my_select_here').load('/temp/select.php');
});
</script>
In the first script tag, we include the jQuery library from Google's CDN. In the second, we write our Javascript/jQuery code. The .load() function makes it easy to make an Ajax call and load the response into an HTML element.
You can see this is much easier than all that code in my other answer :).
If you're using prototype, you can use either Ajax.Request or Ajax.Updater, tho you should have a parent div with either to replace/insert into.
Example w/ Request:
new Ajax.Request('select.php', {
method: 'post',
onSuccess: function(r) {
var select = r.responseText;
$('parent_div').update(select);
}
});
Example w/ Updater:
new Ajax.Request('parent_div', 'select.php', { method: 'post' });
First, the Ajax example (taken from tizag.com and modified), Javascript code comes:
var ajaxRequest; // The variable that we will put an XMLHTTPRequest object in
//We try to create an XMLHTTPRequest object,
//it is the object that lets us use Ajax
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
// and do stuff with it (this function will only run,
// when the data arrives back from the server!)
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){ //if request is successful
//HERE COMES THE DOM INSERTION
}
}
//We call the PHP file
ajaxRequest.open("GET", "/temp/select.php", true);
ajaxRequest.send(null);
What basically happened is that through XMLHTTPRequest we called your PHP file. When the response (PHP file's output) comes, ajaxRequest.onreadystatechange will run instantly. So whatever we want to do with the data received, we have to do it in the place I've written //HERE COMES THE DOM INSERTION.
We want to insert the output into the HTML. To take the easiest route, first create a div/span in your HTML at the exact place you want your select to appear (it's very important to define the ID).
<div id="i_want_my_select_here"></div>
Then again, here comes the Javascript that replaces //HERE COMES THE DOM INSERTION.
//use the id to get Javascript access to the DIV
var div=document.getElementById('i_want_my_select_here');
//put the output of PHP into the div
div.innerHTML=ajaxRequest.responseText;
I have checked the suggestions that came up before posting, hope I didn't miss anything now.
I have a piece of code that I use to get txt-files for my website but now I need to redo the code so it gets both txt and php-files, but it just won't read the php-script. I'm a bit afraid to mess up the code at this moment so I'm walking on the safe side of the road and ask here if anyone knows a good add to the code. It's quite embarrasing that I still have codes for IE 5&6 in it, so if you wish to remove that at the same time, go ahead. I won't hate you for it, I promise.
UPDATE:
I have four files:
html - Calling the .js-file with the ajax-script.
js - With all my javascript(and simular)-codes.
php - That contains... Well, you get the point.
I have to call the php-code somehow, like I call my txt-files, but of course so the php works as it should. I am very new to AJAX, so I don't dare to mess around with this code at the moment, but I figured that I might be able to add some kind of if-statement that calles the php-file as it is intended to be.
But I have no clue what that code might be and where to put it for things to work accordingly. Any help would be appritiated and credited in the code, of course.
Heres the AJAX-code that is contained within the .js-file:
/*Load the link.*/
function loadXMLDoc(url)
{
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("leftCol").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
/*Highly unnecessary, but I wanted to see if it worked and it looks better on the .html-page.*/
function get_link(url)
{
loadXMLDoc(url);
}
As the above commenter said, it is best to use a 3rd party tool for such things - if for no other reason than to greatly increase cross-browser compatibility.
if you were to use jQuery, the code would be reduced to.
function get_link(url)
{
$.ajax({url: url, success: success:function(result){
//the code / resulting string will be in the result variable.
}});
}
jQuery CDN Hosted: http://code.jquery.com/jquery-1.5.min.js
Let me ask this... if you change your code to
function get_link(url)
{
window.location=url;
}
Does your web browser successfully navigate to the page you are trying to retrieve via AJAX? If not, there is likely a problem with your PHP syntax.
it just won't read the php-script
It's a rather vague statement, but here are few pointers that could be the solution :
PHP file are interpreted on the server so when you do an Ajax call to that page what you receive on the client side is the result of that php script, not his content.
You are assigning the result of the query directly in the HTML, if the result contains data that does not render anything, you won't see anything. For example the content <script>Text here bla bla bla</script> will just show nothing.
If you want to make sure you get some data back from a file, you can just alert the content when you receive it.
Make sure your path to your PHP page is correct. To detect if the file is not giving a 404 error code or any other error code, you can use this :
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
document.getElementById("leftCol").innerHTML = xmlhttp.responseText;
} else {
alert("Error " + xmlhttp.status);
}
}
}
I am creating a web game for learning new words aimed at children.
I have a set of four links each displaying a specific word retrieved from my database and a clue, I need to check that the word which has been selected matches the correct word for that clue.
I know that I need to use javascript because of the onClick function and I can successfully check whether the word selected matches the correct word. However, I then need to update a score held in the database if the word is matched correctly, therefore I would need to use php.
From what I can gather this means I must use AJAX but I can't find a good example of anyone using AJAX onClick of a link to then update a database.
I have attempted to do this...but its probably completely wrong as I couldn't get it to work properly:
//This is my link that I need to use in my game.php file where $newarray[0] is that answer I want to check against $newarray[$rand_keys]
<a onClick=originalUpdateScore('$newarray[0]','$newarray[$rand_keys]')>$newarray[0]</a>
//my attempt at ajax in a score.js file
var xmlHttp;
function originalUpdateScore(obj,corr){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
if(corr == obj){
var url="getscore.php";
//url=url+"?q="+str;
//url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
//xmlHttp.open("GET",url,true);
xmlHttp.open(url,true);
xmlHttp.send(null);
alert('Correct');
}
else
{
alert('AHHHHH!!!');
}
window.location.reload(true);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
//attempting to update the database in a getscore.php file
<?php
//$q=$_GET["q"];
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");
$sql= "UPDATE `temp` SET `tempScore`= `tempScore`+1 WHERE (temp.Username='$_SESSION[logname]')";
$showsql = "SELECT `tempScore` FROM `temp` WHERE (temp.Username='$_SESSION[logname]')";
$result = mysqli_query($con, $showsql);
echo "$result";
mysqli_close($con);
?>
I would highly recommend learning AJAX properly - it won't take you ages but will help you understand what you can and can't do with it.
Updating a DB from a web page via AJAX is very common. I would suggest simplifying your JavaScript development using jQuery (a JavaScript library). There is a good introduction to jQuery and AJAX here.
Basically what jQuery will do is write a lot of the boilerplate code for you. What you will end up writing is something like this:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
What you're doing here is sending a POST request to updatescore.php when the answer is correct.
Then, in your updatescore.php, you just need to have PHP code like you already do which will update the score in the database.
You can obviously do many more complicate things than this, but hopefully that will be enough to get you started.
I noticed you have "window.location.reload(true);" in your code. Why? That seems like it would make things not work.
You should try to analyze your program to find out where the problem is happening. Then you will be able to ask us a very specific question like "why does Firefox not fire the onClick handler when I click on this link" instead of just posting three pages of code. When you paste so much code, it's pretty hard for us to find your bug.
So here are the questions you should ask:
Is my HTML being parsed correctly? To me, it looks like it might not be parsed correctly because you did not put quotes around the value of onClick. You should use quotes, like: onClick="..." To find out if your HTML is being parsed nicely, you can use Firefox's View->Source feature and look at the colors it prints.
Is my onClick handler getting called? It looks like you are using alert()'s effectively so that's good.
Does the request actually get sent to my server? To determine this, you should use Firefox, and install the Firebug extension. In the "Net" panel, it will show you all the AJAX requests that are being made by your page, and it will show you the results that were returned from the server.
Is the script on my server doing the right thing? So on the server side, you can now add lines like "echo 'hello world';" and you will see that output in the Firebug Net panel, which will help you debug the behavior of your server-side script.
Is my stateChanged function getting called? Once again, use alert() statements, or write to Firebug's debug console.
Once you've narrowed your problem down, try to reduce your code to the simplest possible code that still fails. Then show us the code and tell us exactly what the symptoms of the error are.
On another note, I recommend getting this book: Javascript: The Deinitive Guide, 5th Edition by O'Reilly. It covers lots of cool stuff like AJAX and closures. It costs $50 but it's definitely a good investment because it explains things in a much more coherent way then you'll ever get from free websites.