'evaluating' image[x] in a loop - php

for (m=0;m<z;m++) {
document.write("<img src=" + image1 + '>' + "<br>");
}
I'm successfully getting a list of image URLs from an XML file via PHP.
The var 'image1' returns 'image_1.png'.
In the above loop I want to output these images. 'image1' above displays 'image_1.png' twice (z=2 in this case), but I'm after a list of all the images. I want to throw in something like 'image[m]', but i know thats not right.
I'd be surprised if anyone hasn't asked this question before, I searched but couldn't find an answer.
This is the PHP thats getting my XML data:
<script type="text/javascript">
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","../../file.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("project")
var j=xmlDoc.getElementsByTagName("imagelist");
for (i=0;i<x.length;i++) {
for (z=0;z<j.length;z++) {
this["image" + z] = j[z].getElementsByTagName("image")[z].childNodes[0].nodeValue
}
}

Whoa. Ok. This right here:
this["image" + z] = j[z].getElementsByTagName("image")[z].childNodes[0].nodeValue
Don't do that.
This is dynamically creating variables in the global scope. I could explain why that is (this here is the global object, and properties of the global object are themselves global variables), but for novice JS programmers it's probably sufficient to say that you should just never do that because, generally, it's a pretty bad idea.
Instead, what you really want is an array.
var images = [];
for (i=0;i<x.length;i++) {
for (z=0;z<j.length;z++) {
images.push(j[z].getElementsByTagName("image")[z].childNodes[0].nodeValue);
}
}
Now your loop later is pretty straight forward. You simply use the loop index as the array index to fetch the value you want.
for (m=0;m<z;m++) {
document.write('<img src="'+ images[m] +'"><br>');
}

<script type="text/javascript">
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","../../designportfolio.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var projectname = "<?= $name ?>";
var x=xmlDoc.getElementsByTagName("project")
var j=xmlDoc.getElementsByTagName("imagelist");
var k=xmlDoc.getElementsByTagName("image");
for (i=0;i<x.length;i++) {
//vars from xml used to display data in html
var folder = x[i].getElementsByTagName("folder")[0].childNodes[0].nodeValue;
//only defines the data if the projectname and folder name match
if (folder == projectname) {
var projecttitle = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var projectinfo_l = x[i].getElementsByTagName("projectinfo_l")[0].childNodes[0].nodeValue;
var skillsused = x[i].getElementsByTagName("skillsused")[0].childNodes[0].nodeValue;
var date = x[i].getElementsByTagName("date")[0].childNodes[0].nodeValue;
var videoURL = x[i].getElementsByTagName("videoURL")[0].childNodes[0].nodeValue;
var images = [];
for (z=0;z<k.length;z++) {
images.push(x[i].getElementsByTagName("image")[0].childNodes[0].nodeValue);
document.write("images " + images + "<br>");
}
}
}
im in a total mess. im using an IF to pick only one project, this works. I want only the images from this project. the above code is getting all the images in the xml file (13 of them), i want ONLY the images from the current project (the project corresponding to 'folder' or 'projectname'). I cant do this :(

You have an array of images that you would like to render with js. There are several approaches. The sample code you have in the question is probably the worst way to do it.
Don't use document.write() to do this.
All examples assume 'images' is an array containing n-number of image urls.
Example 1
var images = [],
target = document.getElementById('target_div'); //this is the location in the document where the images are appended to
for(var i=0, len=images.length; i++){
var img = document.createElement('img');
img.src = images[i];
target.appendChild(img);
}
Example 2
var images = [],
target = document.getElementById('target_div'); //this is the location in the document
var arr = [];
for(var i=0, len=images.length; i++){
arr.push('<img src="'+ images[i] +'">');
}
target.innerHTML = arr.join('');

Related

ajax callback function is empty

It's my first time on StackOverflow, please forgive me if I forget some important information or if my question sounds stupid!
I am building a web site which generates a list once the user writes a word and hits the "Send" button. Php is responsible for extracting the required data and returning it to the web page as a list.
My problem is that I then want to pass this data in a js function. I have read a lot of answers on StackOverflow concerning this, and it sounded like a callback function is what I needed. However, my js function keeps telling me that my node is null; it seems the data returned from ajax is not accounted for.
Here are some parts of my code:
<script>
var xmlhttp;
function loadXMLDoc(cfunc){
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var us = document.getElementById("user").value;
var ur = document.getElementById("wiki").value;
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET","contributions_old.php?user="+us+"&wiki="+ur+"",true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc(function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("result").innerHTML=xmlhttp.responseText;
var parser = new DOMParser ();
var responseDoc = parser.parseFromString (xmlhttp.responseText, "text/html");
var text1 = responseDoc.getElementById('old1').value;
var text2 = responseDoc.getElementById('new1').value;
var dmp = new diff_match_patch();
dmp.Diff_Timeout = 0;
// No warmup loop since it risks triggering an 'unresponsive script' dialog
// in client-side JavaScript
var ms_start = (new Date()).getTime();
var d = dmp.diff_main(text1, text2, false);
var ms_end = (new Date()).getTime();
var ds = dmp.diff_prettyHtml(d);
document.getElementById('outputdiv').innerHTML = ds + '<BR>Time: ' + (ms_end - ms_start) / 1000 + 's';
}
});
}
</script>
It's of course the Send button that calls myFunction() at the bottom of my web page, once the user has entered a word.
I have also verified that my web page, once the list has been generated, has the divs with "new1" and "old1" as ids (they are generated through my php code).
Any help would be really appreciated! I feel like I've tried everything!
Thank you! :)
Highly recommend using jQuery or some other lib for this.
var url = "contributions_old.php?user=" + $("#user").val() + "&wiki=" + $("#wiki").val();
$.get(url);

Passing JSON object from php to JS via Ajax

I am trying to pass a JSON object from a php script to a Javascript file with Ajax. The code below worked for a simple string, but I am now trying to amend it to work with multiple strings contained within a JSON object. I have pasted extracts of each file below. What am I doing wrong?
This is a extract from the html/javascript file which is creating the request...
function retrieveAircraftInfo(str) {
var xmlhttp;
if (str.length==0) {
document.aircraftRegForm.aircraftManufacturer.value="";
return;
}
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) {
var aircraftDataJSON = xmlhttp.responseText.evalJSON();
document.aircraftRegForm.aircraftManufacturer.value = aircraftDataJSON.manufacuter;
document.aircraftRegForm.aircraftType.value = aircraftDataJSON.type;
document.aircraftRegForm.aircraftPopularName.value = aircraftDataJSON.popularName;
document.aircraftRegForm.aircraftGenericName.value = aircraftDataJSON.genericName;
}
}
xmlhttp.open("GET","scraper.php?q="+str,true);
xmlhttp.send();
}
This is an extract from the php file which is doing the database search:
$aircraftDataArray = array("manufacturer" => $extractedManufacturer,
"type" => $extractedType,
"popularName" => $extractedPopularName,
"genericName" => $extractedGenericName);
echo json_encode($aircraftDataArray);
Try
var aircraftDataJSON = JSON.parse(xmlhttp.response);
Otherwise, check in the console of the developer tools if PHP returns some error.
Your JS example worked for me with JSON.parse

Embed Ajax requests in bind events (XHR)

I'm trying to find the answer somewhere around but i can't,
So i'm having a .bind() event and I want when's triggered to make a get query from a php file with JSON like AJAX does.
I have tried the following which doesn't work:
$(document).ready(function() {
$("#adivhere").bind("valuesChanged", function(){
// Some variables here
var max2 = 10
var min2 = 5
//The classic AJAX Request
function afunc(max2,min2){
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");}
//The classic AJAX onreadystatechange function
xmlhttp.onreadystatechange=function()
{ if (xmlhttp.readyState==4 && xmlhttp.status==200){
//The code triggered
var fets = jQuery.parseJSON( xmlhttp.responseText );
var t = fets.date.split(/[-]/);
var d = new Date(t[0], t[1], t[2]);
alert(d);
}}
//The XHR request with the .php file and the
// two values that sends
xmlhttp.open("GET","getdates.php?max2="+max2+"&min2="+min2,true);
xmlhttp.send();
};
});
It looks like you're using jQuery, so this should work:
$(function(){
$('#adivhere').bind('valuesChanged',function(){
var max2 = 10;
var min2 = 5;
$.getJSON('getdates.php?callback=?', {max2: max2, min2: min2}, function(json){
alert(json);
var t = json.date.split(/[-]/);
if (t && t.length) {
var d = new Date(t[0], t[1], t[2]);
alert(d);
}
});
});
});
There's already an awesome $.getJSON method in jQuery that will do all of the heavy lifting for you, including return your results as JSON.
You'll need to make your getdates.php script echo the callback and wrap your results in parentheses so it returns as actual jQuery.
There are several "errors" in your script:
"afunc" is never called, so why should it be executed?
the parenthesis are not closed properly; at the end there are two missing: )}

Onbeforeunload - popux box will not display or trigger

I am building a website with user-profiles. I am at the picture part at the moment. When a person upload their image with no problem, the picture will be stored in 4 different folders. One for size 25, 100, 150 and normal size. After this they will be redirected to the same page, with new content. This is the part, where they need to crop their picture. Crop part works great, but I have a problem. When they leave the site without cropping, the pciture they just uploaded is still stored in the folders, and that's not what i want. So i mate some checks with AJAX, and it will unlink the 4 files sotred already. My problem is, that this shall only happen, when they leave the site(onbeforeunload.)
This works very great in IE, but not in Chrome.(Only two browsers i've tested yet.)
Here is what I'm doing:
function unfinished(album,img){
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) {
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
}
The function above get information from "uncl/unfinished.php" by the query string. And it all works well.
Code on unfinished.php:
session_start();
require('../dbconnect.php');
$sql = "SELECT * FROM users WHERE username='".$_SESSION['username']."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$username= $row['brugernavn'];
}
$album = $_GET['a'];
$img = $_GET['i'];
$sourcex = "../users/".$username."/images/".$album."/x-x/".$img;
$source25 = "../users/".$username."/images/".$album."/25/".$img;
$source100 = "../users/".$username."/images/".$album."/100/".$img;
$source150 = "../users/".$username."/images/".$album."/150/".$img;
if(unlink($sourcex)){
}
if(unlink($source25)){
}
if(unlink($source100)){
}
if(unlink($source150)){
}
echo "Error 908. The picture didn't get cropped, and neither saved. Try again.";
The AJAX code and unfinished.php deletes the images withpout any problems. I've tested that already. Now my problem:
I am running the AJAX code by
The code should be running inside this:
//function warn(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = unfinished(album,img);
}
// For Safari
return unfinished(album,img);
};
//}
But when i try to return xmlhttp.responseText, the popup box doesn't popup, and i am not able to see the response.
But if i add "Hello world"(or some text) to the return like return Helloworld!''; or e.returnValue = 'Hello world!';, instead of the xmlhttp.responseText value, it pops up, and display the message. But it doesn't display the xmlhttp.responseText, because it doesn't run the unfinished() function.
any solutions how i can run the AJAX when user leaves page?
If it helps here is the HTML code:
if($_POST['where'] == "newalbum"){
$nameonalbum = $_POST['nameonalbum'];
}else{
$nameonalbum = $_POST['existingalbum'];
}
$filenamenew=time().'.gif';
?>
<body onload="warn('<?=$nameonalbum?>','<?=$filenamenew?>')">
Solved it by myself. Did like this:
function unfinished(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
var response = '';
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){
response = xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = response;
}
// For Safari
return response;
}
}
But now i have another problem... 1st of all the unload function works great, but I don't want it to trigger when the "Save crop" button is clicked. Any ideas how to do this?
Save button html:

I want to send multiple piece of data using a single variable to a database (using JS, PHP and AJAX)

I am not aware of the proper terminology or jargon with programming, so forgive me if this question is unclear. To make if more clear here is the code I have written so far. I will explain the problem in more detail after the code:
I use this code to retrieve data from Facebook:
function rsvpEvent() {
FB.api('/me/events/', function(response) {
for (var i=0; i<=2; i++) {
eventname=response.data[i].name;
eventid=response.data[i].id;
eventstatus=response.data[i].rsvp_status;
eventInfo(eventname,eventid,eventstatus);
strEvent=strEvent + "You are " +
eventstatus + " " + eventname + ", EID: " + eventid + "<br/>";
}
document.getElementById('rsvpEvent').style.display = "block";
document.getElementById('rsvpEvent').innerHTML = strEvent;
});
}
Request to PHP file (containing mySQL calls):
function eventInfo(eventname,eventid,eventstatus) {
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("eventInfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","event_info.php?eventName=" + eventname + "&eid=" + eventid +
"&rsvp_status=" + eventstatus,true);
xmlhttp.send();
}
So, the issue is that I need to store individual event names, ids and statuses and the code as it stands now. I can output them to a page individually, but cannot send them to the PHP file individually. How do I do this (presuming it is possible)?
Use jQuery for your ajax call to your php script.
$.post('/somefile.php', myJSobjectOrArr, function(data) {
// return something from your script to say it succeeded or not...
console.log(data);
}
In your php script just check your $_POST variable and serialize() or json_encode() it and pop it into your database.
To get your data back just unserialize() or json_decode() it.
You can join eventnames with comma(,) ,and when reading those data to save into database you can delimit comma(,), means remove commas from that and store each event name to database..
This is what i understand according to your problem..

Categories