sassenach Posted March 18, 2009 Share Posted March 18, 2009 hi, I have a gallery, upon clicking a gallery set, the page should open it's photos without refreshing, therefore i use XMLHttpRequest. It works fine if i am display just plain text/images, but im trying to display javascript & html content. I want to display my "smoothgallery" according to gallery set that was chosen. Here is a link to the website: http://www.maestro2007.co.il/index.php?mid=3 Click on an image on the right, it should open the smoothgallery on the left. This is my request page: function getMessageResponse(str){ var xmlHttp; var divelement = document.getElementById('response'); divelement.innerHTML = '<p>Loading, please be patient...</p>'; try{ // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); xmlHttp.overrideMimeType("text/html; charset=windows-1255"); /*TO DISPLAY HEBREW CHARACTERS*/ } catch (e){ // Internet Explorer try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlHttp.setRequestHeader('Content-Type','text/html; charset=windows-1255') } catch (e){ alert("Your browser does not support AJAX!"); return false; } } } xmlHttp.onreadystatechange=function(){ //Used to set the callback function that handles request state changes. //alert(xmlHttp.status+' - '+xmlHttp.readyState); if(xmlHttp.readyState==4){ // 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete divelement.innerHTML=xmlHttp.responseText; //Returns the server response as a string. //alert(xmlHttp.responseText); //document.myform.message.value = ''; } } //url=url+"&message="+str; var url="projects.php?mid=3"; url=url+"&pid="+str; url=url+"&sid="+Math.random(); xmlHttp.open("GET",url,true); //Initializes the request parameters. / or POST data larger than 512 bytes xmlHttp.send(null); //Performs the HTTP request. } Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/ Share on other sites More sharing options...
Floydian Posted March 18, 2009 Share Posted March 18, 2009 It sounds like you are attempting to send javascript through an xmlhttp request. Which, if that's the case would require you to put that *text* into an eval() call. Otherwise, the *text* won't be transformed into executable javascript. And since doing that is bad, you really need to refactor your script so that all you need is in the script from the git go. Then determine what sets of javascript you need to execute based on the result you get from the xmlhttp request. Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-788082 Share on other sites More sharing options...
sassenach Posted March 19, 2009 Author Share Posted March 19, 2009 Hi Floydian, Yes, i am sending javascript, as well as html. What is happening is, clicking on a thumbnail (in index.php), sends the project ID which the thumbnail is located in to the xmlhttp request (ajaxrequest.php), then opens projects.php and suppose to display the full project album according to that ID. This album is obviously done in JS, and like you said, i can't transfer executable JS. Is there a way to send back the project ID to my index.php page, which is where my thumbnail is located, so that i can execute the JS there? I am new at this xmlhttp request, so i am not sure as to how to execute this correctly. Can you please give me a head start so I know follow? thanks Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-788266 Share on other sites More sharing options...
Floydian Posted March 19, 2009 Share Posted March 19, 2009 Just so to make sure we're on the same page, when you say: Is there a way to send back the project ID to my index.php page I'm assuming that your xmlhttp response sends the project ID to the user. The index.php page would be the page that the user initially loaded. I hope I have that right. If all you are sending is a project ID, just have the backend script output the project ID as text and save that in a var for use as a project ID. If you are sending other data back to the user, then you should use JSON encoding. That would basically create an object that could contain a .message property and a .propertyID property. http://www.json.org/ That site has loads of info on JSON. Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-788598 Share on other sites More sharing options...
sassenach Posted March 19, 2009 Author Share Posted March 19, 2009 hi, thanks for the reply. index.php is the initial loaded page. i send the project id from index.php (thumbnail onclick) to the ajax request, which then sends that project id to projects.php that is suppose to connect to the DB and display all the photos within that project (according to the project id), without reloading the page. Is it possible to just send back to index.php the project id without reloading the page? My photo gallery uses javascript for the slide show, therefore clicking on a thumbnail, must refresh the slide show to display the correct photos for that project. Does that mean i need json? Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-788668 Share on other sites More sharing options...
Floydian Posted March 20, 2009 Share Posted March 20, 2009 What specifically does projects.php output as a response? Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-789074 Share on other sites More sharing options...
sassenach Posted March 20, 2009 Author Share Posted March 20, 2009 it connects to the DB, retrieves all the photos content, then i display these photos using a photo gallery slide show by JonDesign SmoothGallery, which obviously has JS in the files. Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-789407 Share on other sites More sharing options...
Floydian Posted March 21, 2009 Share Posted March 21, 2009 Alrighty then, since you're outputting all the images, that begs the question: Are the images output as HTML or javascript or XML or JSON or some other format? If you were outputting them as javascript, then you'd need to convert that to some other format. Most of these javascript image dealies will take HTML markup and convert that to what they need to make the widget work. That means you can output HTML and once you load that HTML into the page, call up some render() method or whatever instantiates your image widget. Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-789968 Share on other sites More sharing options...
sassenach Posted March 21, 2009 Author Share Posted March 21, 2009 I am not sure, because i am using a third party gallery called SmoothGallery. You can have a look at the demo page within my site: http://www.maestro2007.co.il/includes/smoothgallery/demozoom.html You can do a view source on the above demo link to view the HTML, CSS & JS files. I duplicate "<div class="imageElement">" tags, then i call a JS function "startGallery()", then i do a JS "window.addEvent" to start this gallery. Since my photos come dynamically from the DB, this is how i display the gallery. My site: http://www.maestro2007.co.il/index.php?mid=3 I have my index.php page: On each thumbnail photo, i do an onclick onClick="javascript:MyAjaxRequest(\'response\', \'/projects.php?mid='.$mid.'&pid='.$projectsR['pid'].'\');" I also have the "response" id where that should display the gallery: <ul><li class="text2 corner" id="response" name="response"> </li></ul> I put it in a list, because the way i display the css. So now the onclick calls "MyAjaxRequest" which is in ajaxrequest.php: // start ajaxrequest.js // Following is a javascript function that makes a httprequest - AJAX. This is the AJAX bit and all that is needed in that manner. // Only in this one we won't be using XML in our response, we will accept and handle // pure text and html and display this response directly to the user within the // desired <div id> tags. It can even be used to include pure html files as a substitute // solution to the "old" frames method where as no php or other scripting language is nessesary on the server. // but use it with care - it is not a search engine supported method and indexing will fail. Workaround for this is not included here function MyAjaxRequest(target_div,file,check_div){ var MyHttpRequest = false; var MyHttpLoading = '<p>Loading...</p>'; // or use an animated gif instead: var MyHttpLoading = '<img src="loading.gif" border="0" alt="running" />'; var ErrorMSG = 'Sorry - No XMLHTTP support in your browser, buy a newspaper instead'; if(check_div){var check_value = document.getElementById(check_div).value;} else{var check_value = '';} if(window.XMLHttpRequest) // client use Firefox, Opera etc - Non Microsoft product { try{ MyHttpRequest = new XMLHttpRequest(); } catch(e){ MyHttpRequest = false; } } else if(window.ActiveXObject) // client use Internet Explorer { try{ MyHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e){ try{ MyHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ MyHttpRequest = false; } } } else { MyHttpRequest = false; } if(MyHttpRequest) // browser supports httprequest { var random = Math.random() * Date.parse(new Date()); // make a random string to prevent caching var file_array = file.split('.'); // prepare to check if we have a query string or a html/htm file if(file_array[1] == 'php') // no query string, just calling a php file { var query_string = '?rand=' + random; } else if(file_array[1] == 'htm' || file_array[1] == 'html') // calling a htm or html file { var query_string = ''; } else // we have presumable a php file with a query string attached { var query_string = check_value + '&rand=' + random; } MyHttpRequest.open("get", url_encode(file + query_string), true); // <-- run the httprequest using GET // handle the httprequest MyHttpRequest.onreadystatechange = function (){ if(MyHttpRequest.readyState == 4) // done and responded { document.getElementById(target_div).innerHTML = MyHttpRequest.responseText; // display result //alert('responsetext printing: '+document.getElementById(target_div).innerHTML); } else { document.getElementById(target_div).innerHTML = MyHttpLoading; // still working } } MyHttpRequest.send(null); } else { document.getElementById(target_div).innerHTML = ErrorMSG; // the browser was unable to create a httprequest } } // end of "AJAX" function // Here follows a function to urlencode the string we run through our httprequest, it has nothing to do with AJAX itself // If you look carefully in the above httprequest you se that we use this url_encode function around the file and query_string // This is very handy since we are using GET in our httprequest and for instance // any occurrance of the char # (from textboxes etc) will brake the string we are sending to our file - we don't want that to brake! // It will also convert spaces to + function url_encode(string) { var string; var safechars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/-_.&?="; var hex = "0123456789ABCDEF"; var encoded_string = ""; for(var i = 0; i < string.length; i++){ var character = string.charAt(i); if(character == " "){ encoded_string += "+"; } else if(safechars.indexOf(character) != -1){ encoded_string += character; } else { var hexchar = character.charCodeAt(0); if(hexchar > 255){ encoded_string += "+"; } else { encoded_string += "%"; encoded_string += hex.charAt((hexchar >> 4) & 0xF); encoded_string += hex.charAt(hexchar & 0xF); } } } return encoded_string; } // end .js file And in projects.php this is where we display the gallery: <?php //projects header('Content-Type: text/html; charset=WINDOWS-1255'); /* MUST BE HERE TO DISPLAY HEBREW */ header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); require_once ('includes/config.inc.php'); require_once ('includes/functions.inc.php'); require_once ('includes/mysql_connect.php'); if(isset($_GET['pid'])) { $pid = (int) $_GET['pid']; //echo "project id: $pid---"; $projectsQ1 = mysql_query(" SELECT projects.proj_id AS pid, projects.location AS plocation, projects.title AS ptitle, images_to_proj.img_id AS img_id, images_to_proj.caption AS caption, images_to_proj.file_name AS file_name FROM projects INNER JOIN images_to_proj ON projects.proj_id=images_to_proj.proj_id WHERE projects.proj_id=".$pid."") or trigger_error("Query: $projectsQ1\n<br />MySQL Error: " .mysql_error()); if(mysql_num_rows($projectsQ1) > 0){ //$projectsR1 = @mysql_fetch_array ($projectsQ1); echo '<link rel="stylesheet" href="/includes/smoothgallery/css/layout.css" type="text/css" media="screen" charset="utf-8" /> <link rel="stylesheet" href="/includes/smoothgallery/css/jd.gallery.css" type="text/css" media="screen" charset="utf-8" /> <link rel="stylesheet" href="/includes/smoothgallery/css/ReMooz.css" type="text/css" media="screen" charset="utf-8" /> <script language="javascript" type="text/javascript" src="/includes/smoothgallery/scripts/mootools-1.2.1-core-yc.js"></script> <script language="javascript" type="text/javascript" src="/includes/smoothgallery/scripts/mootools-1.2-more.js"></script> <script language="javascript" type="text/javascript" src="/includes/smoothgallery/scripts/ReMooz.js"></script> <script language="javascript" type="text/javascript" src="/includes/smoothgallery/scripts/jd.gallery.js"></script> <div id="myGallery">'; while ($projectsR1 = mysql_fetch_array($projectsQ1, MYSQL_ASSOC)) { $getImg1 = getUploadImgPath(27, "/site_uploads/portfolio/", $projectsR1['file_name'], $projectsR1['img_id'], 1, "portfolio"); $ImgThumb_small = str_replace($image_ext, '_site_thumb.jpg', strtolower($getImg1)); list($width1, $height1, $type, $w) = getimagesize(strtolower($getImg1)); if($width1 >= 632){ //if image was large, get resized $thumbimg_large = str_replace($image_ext, '_large_thumb.jpg', strtolower($getImg1)); } else {$thumbimg_large = $getImg1;} //echo '--->'.$projectsR1['plocation'].' - '.$projectsR1['ptitle'].' - '.$projectsR1['img_id'].' - '.$thumbimg_large.'<br/>'; echo '<div class="imageElement"> <h3>'.$projectsR1['ptitle'].' '.$projectsR1['plocation'].'</h3> <p>'.$projectsR1['caption'].'</p> <a href="'.$thumbimg_large.'" title="open image" class="open"></a><img src="'.$thumbimg_large.'" class="full" /><img src="'.$ImgThumb_small.'" class="thumbnail" /> </div>'; } echo '</div> <script language="javascript" type="text/javascript"> function startGallery() { var myGallery = new gallery($(\'myGallery\'), { timed: false, useReMooz: true, embedLinks: false }); } window.addEvent(\'domready\',startGallery); </script>'; mysql_free_result ($projectsQ1); } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-790320 Share on other sites More sharing options...
Floydian Posted March 23, 2009 Share Posted March 23, 2009 That's not going to work. The page you're requesting is outputting html and javascript. It clearly was not intended to be used as part of an ajax script. Simply put, the javascript in that output is treated as mere text and never executed. You'd have to remove that javascript from the output and either have that js in the original page or run it through eval (which is bad) You're going to have to heavily refactor that deal. Perhaps you might just use an iframe for this, since anything you load into the iframe would be executed (i.e., the js) Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-791412 Share on other sites More sharing options...
sassenach Posted March 24, 2009 Author Share Posted March 24, 2009 hi, so i decided to use iframes and it works perfectly and pretty quickly as well. I still want to learn how to use jquery/ajax/json, etc, but that i will have to halt when i have some time. thanks again Quote Link to comment https://forums.phpfreaks.com/topic/149963-displaying-data-from-db-using-xmlhttprequest/#findComment-792385 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.