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;
Related
i am submitting a form using Ajax and storing the data in the database. It is storing the data in the database and without reloading the page it is giving alert box showing that that content has been added.
The same page is showing the content of the database, i need that part to refresh automatically without reloading the page so that it can also fetch the just added information.
<script type="text/javascript">
function GetXmlHttpObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if(window.ActiveXobject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function submitformwithajax()
{
var myAjaxPostrequest=new GetXmlHttpObject();
var coursename=document.getElementsByName('cvalue')[0].value;
var parameter="cvalue="+coursename;
myAjaxPostrequest.open("POST", "process/do_course.php", true);
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameter);
myAjaxPostrequest.onreadystatechange=function(){
if(myAjaxPostrequest.readyState==4){
if(myAjaxPostrequest.status==200){
if(myAjaxPostrequest.responseText=="true")
{
alert("Course Has Been Successfully Added To The Curiculum !");
var container = document.getElementById('c');
var refreshContent = container.innerHTML;
container.innerHTML = refreshContent;
}
}
else
document.getElementById("submitcourse").innerHTML="An error has occured making the request";
}
}
}
</script>
'c' is the ID of the div tag which has to be reloded.
Thanks
This seems a bit nonsense:
var refreshContent = container.innerHTML;
container.innerHTML = refreshContent;
That way you're not refreshing, the content is exactly the same.
I don't know exactly what do you mean by "DB content", assuming coursename is what you want to add to your DIV then you have to do something like:
container.innerHTML += '<p>'+ coursename +'</p>';
jQuery would benefit your work a lot, your current code via jQuery would look like
function submitformwithajax() {
var coursename = $("[name=cvalue]").val();
$.post("process/do_course.php", {cvalue: coursename}, function(response) {
if (response === "true")
{
alert("Course Has Been Successfully Added To The Curiculum !");
var container = $("#c");
// Not sure why you're setting the container to the container here
container.html(container.html());
}
else
$("#submitcourse").text("An error has occured making the request");
}, "text");
}
I don't know why you set the text of the container to the text in the container but that may be an issue you are having. If your server response returns the data that needs to be displayed in th area you can use jQuery (or if you really prefer, the DOM) to update the fields or elements (or add as needed) on the fly. If you need to refresh that section based off a GET request, then just make a GET request for the data in the success statement.
I would also recommend using JSON for the return type from the server instead of plain text. A {"success": true} will allow you to check if (response.success) instead of using string comparison there.
Also, as a final side note, in Javascript you should always prefer === over == as === verifies that value and type both match, the downside to this is that in Javascript 1 == "1" but 1 === "1" is not true.
EDIT
In response to your comment, should you not persue the jQuery route, you can still implement all of that which I have explained here however you'll have to manually parse the response:
var resposne = JSON.parse(myAjaxPostRequest.responseText);
From there you can still check if (response.success).
I, personally, recommend showing the students how to do it this long and complex way, and then teaching them how to do it with jQuery. Should any of them pursue a web development career then they will either use jQuery or something very similar in function to it and it's best they learn about these things early on instead of after they get hired. I also suggest JSON returns from the server because it's a more expressive way to return data, instead of just "true" (what is true?) you say {"success": true} so you can see the request was successful.
The easiest way to do this is going to be return the contents of the "c" element from the ajax call, and then replace the old contents of "c" with the content returned by the ajax call.
After seeing your code: You are not filling that table with AJAX. I can only give you this advice. Fill that table dynamically with Javascript.
Create function which will find div#c.
If div#c has some children, destroy them.
Create a new element table.
Fill that table with new rows.
This is how you can make a table dynamically with data from the server which is provided by Ajax. So after sending data from the form you can call this function and your table will be recreated.
I have a webpage that retrieves data (via ajax/php) and shows it in an html div (id='parent'). I'd like to add a print feature, which will take the contents of parent and show it in another page.
I've never made a dynamic webpage before. All the information I show is just pulled onto the main page via ajax. So I don't know where to begin really. I assume it has something to do with those long character strings I see in the urls of lots of internet sites, but I don't know! do I just use the url character string to store information about the current state of the page so the user can go back to what they were looking at with the back button. will the back button automatically work, or do i have to listen for it and reload the page based on what i pull from that string?
Very appreciative if someone can point me to some good articles or work out a little pattern of what steps I should take to
pull data from the page
put it on another page (or is it another page? do I just clear the page i'm on and re-fill it with other data??)
enable the back button to go back to the first page.
Thank you so much!
Those long character strings you are talking about sound like SessionIDs. The idea is that you store all the data you need to share between website requests on the server and identify the user by this ID to retreive the correct dataset when she requests the next website.
PHP already supports this out-of-the-box. The documentation of the PHP session handling functionality can be found here:
http://www.php.net/manual/en/book.session.php
To take data from ajax into another tag you can do something like this
<script>
var page_request = false;
function ajax_request(url)
{
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject)
{ // if IE
try
{
page_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
page_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
else
return false
page_request.open('GET', url);
page_request.send(null);
return page_request.responseText;
}
function ChangeDiv(id, url)
{
document.getElementById(id).innerHTML = ajax_request(url);
}
</script>
then just call ChangeDiv with the url you want (e.g 'http://website.com/page.php?params=1')
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.
As the title states, I am looking for a flag script, explained below:
It should be like any video site flag script: click the small grey flag once, it becomes colored and you cannot click it again. It should be done in ajax as I don't want my user to have his page reloaded (and all activity restarted) just because he made the mistake of flagging an item on my site.
The php behind should not add multiple flags from the same user - i though it would be a good idea if it checked for a cookie, if not set -> increment field in MySQL and set cookie, if set ->ignore.
This is really urgent, as I am a total noob at ajax and Javascript and I need it done by Tuesday...
The reason I need this is that I really want to know how it's done because a project that we are studying at school has something similar and my homework is to think of a solution that would accomplish the same thing, without looking at the initial source code. I thought of a solution but don't have the time to implement it because this week as well as the next one, I have a ton of exams and I really don't want to miss any...
Thanks in advance for any help you give me!
Cheers!
Make an ajaxrequest, and let that do you php handling, when its done you send the return to your page.
I made you a template. I guess you can do the PHP yourself?
function setFlag(state){
var ajaxRequest; // The variable that makes Ajax possible!
//Set AjaxRequest for all Major browsers, nothing to do here, this is standard
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 is lame!");
return false;
}
}
}
// When the Ajax Request waits for php you get some status codes, everything is done when it reaches 4. Add your javascript events etc here...
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState < 4){
//document.getElementById('ajaxCatchbox').innerHTML = "Load...";
}
if(ajaxRequest.readyState == 4){
// Some Javascript to change your flag colour image
}
}
// this is here your php happens without page reload. (In the php file)
var queryString = "?state=" + state;
ajaxRequest.open("GET", "ThePhpFileThatDoesYourDatabaseHandling.php" + queryString, true);
ajaxRequest.send(null);
}
The PhP does your database and sets the right var on 1 so you'll know which flag is clicked. Every time you refresh the page you use this var to display which flag is clicked. Just when there is no flag clicked yet, you'll add this function and in the Javascript change it on the fly because on that moment you havent reloaded yet.
i added something like state to the function coz I thought you might want to know which flag is clicked but ofc you can add ID our flagnumber etc... and you can send that to php using the querystring...
Gr
I have a set of links dynamically generated in a table. Each of the rows has a unique "id" property on it's tag. The goal is to get XMLHTTPRequest to tell the page 'deletepost.php' which record to remove from an outside database.
It changes a hidden input value to the value of the row (a number), and then submits that form
<script type="text/javascript">
var http = false ;
// instance the request object!!!!
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
/////////////////////////////////////////////////
function rdel(num) {
document.getElementById("pid_to_del").value = num;
//this element is a hidden <input> tag. this line changes the value.
http.open("POST", "deletepost.php", true); //this _SHOULD_ post the form
http.onreadystatechange = function() {
if(http.readyState == 4) {
$("tr#r" + num).fadeOut("slow"); // jquery fadeout animation
alert(http.responseText); // this alerts whatever deletepost.php says
}
}
http.send(null);
}
</script>
This function rdel() is called by one of the links, which looks like this:
delete
This is what deletepost.php looks like:
<?php
print_r($_POST);
?>
The page that makes the request alerts:
Array
(
)
An empty array. :( Why?!
Two things here, the first is that you actually have to put your post string (very similar to a query string) into the
http.send(null);
call. So you would do:
http.send('field1=value1')
Secondly, in order for to actually notify the server that there are values being posted, you must set the content type for your request using:
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Hope that helps
EDIT:
I see now that you are trying to use this request to sent a serialized copy of an html form to the server asynchronously. Javascript does not contain the functionality to do this, but certain libraries and plugins (such as JQuery and AjaxForm) do.
For your example, however, you should be able to accomplish this using:
http.send('pid_to_del=' + pid);
The quickest fix would be:
where you open the XMLHttpRequest object:
http.open("POST", "deletepost.php", true)
change the url to be "deletepost.php?number="+num
then in you php page change the POST to a GET.
$number = $_GET['number']
POST allows you to send large amounts of parameters/options around but unless your numbers are going to be more than 140 characters long, this will make no difference. There appears to be a common mis-conception that POST is more secure than GET, simply because it seems more obvious how to get a browser to manipulate the post variable. However, it is a very very small stretch to do the same thing with POST variables so security should not depend on POSTing rather than GETting. There's nothing wrong with using POST except that you don't seem to be able to get it to work easily. I would never do this directly in javascript. I would always use something like jquery. You could replace the whole script with the following and it would work in most browsers:
function rdel(num) {
$.post("/webroot/deletepost.php", {number: num},
function(dat){
$("tr#r" + num).fadeOut("slow"); // jquery fadeout animation
alert(dat.responseText); // this alerts whatever deletepost.php
});
}
by the way, in your selector $('tr#r'+num), the tr is unnecessary since the id's on a page are unique so the result will be the same as $('#r'+num) but would take longer to calculate the selector. Reference by id is the fastest, the former finds all tr tags and then finds the id within that collection, rather than using the 'native' getElementById function by just using id in the selector. In short, don't make jquery do anything you don't need it to do ;)