I have a JSON Object getting a list of images I have on the page. The images are generated at random using a database. I want to keep adding to the images using AJAX whn the user for example clicks "show more". The images src are found so that no duplicates are pulled from the database on the AJAX call.
I want to know how to parse this array to the pHp file to perform an SQL statement to get more images to append to the images list. In the php file how would I select the elements from there. So SELECT * FROM images WHERE image_src NOT IN (JSON array) ORDER BY rand() LIMIT 12
CODE
var imageArray = {};
imageArray.itemList = [];
function imagesLoaded(){
var gal_img_thumbs = document.getElementsByClassName("gal-thumb-image");
for (var i = 0; i < gal_img_thumbs.length ; i++){
var img = gal_img_thumbs[i].firstChild.getAttribute("src");
var new_obj = {'src':img};
imageArray.itemList.push( JSON.stringify(new_obj));
//imageArray.itemList.[i]['src']=img;
}
}
function loadImages(){
console.log("load images");
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getimages.php?imgArray="+imageArray.itemList,true);
xmlhttp.send();
}
Related
Trying the create a javaScript array from a PHP array of urls to images using JSON and AJAX. Then I want to display the images on a cordova app. I believe my issue is I'm either I'm receiving or sending the Json messages with automatic html tags. My xmlhttp.response is equal the array of urls but it has html tags which are not present in the PHP file. I think because of these tags my JSON.parse isn't working?
This is my PHP stored on a server. I'm returning the urls in json message.
<?php
include("mysqlconnect.php");
$select_query = "SELECT `ImagesPath` FROM `offerstbl` ORDER by `ImagesId` DESC";
$sql = mysql_query($select_query) or die(mysql_error());
$data = array();
while($row = mysql_fetch_array($sql,MYSQL_BOTH)){
$data[] = $row['ImagesPath'];
}
echo json_encode($data);
?>
This is my script in my cordova app. I want to covent the JSON message into a javaScript array and display the first image in the array in the div contents. But I think I'm calling a message which includes html tags so I can't parse the message I could be wrong. I currently get three error alerts because the ready state is not correct.
<html>
<script>
var arr = [];
function importJson(str) {
if (str=="") {
document.getElementById("content").innerHTML="";
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 && xmlhttp.status == 200){
alert(xmlhttp.response);
arr = JSON.parse(xmlhttp.response);
//var arr = (array)json.parse(xmlhttp.response);
for (var i = 0; i < arr.length; i++) {
buildImage(arr[i]);
alert(arr[0]);
}
} else {
alert("Error");
}
}
xmlhttp.open("GET","http://server/~name/folder/content.php);
xmlhttp.responseType = "json";
xmlhttp.send();
buildImage=function(src) {
var img = document.createElement('img');
img.src = src;
document.getElementById("content").appendChild(img);
}
}
window.onload = importJson();
</script>
<body>
<div id="content"></div>
At present, your PHP script is outputting a web page, but the javascript is looking for JSON. To output JSON, you need to set the headers in the php script:
header('Content-Type: application/json');
echo json_encode($data);
I'm doing a Twitter API request that returns JSON of all tweets containing #awkward . Here's the successful response on a server: http://babbage.cs.missouri.edu/~atgvyc/php/election_tweets/index.php
But I want to be able to use that JSON in my JavaScript and parse through it with a for-loop to pull out certain information (particularly the geotags and location). I thought I could do this with AJAX and then JSON.parse, but it's not working the way I thought it would.
Any suggestions?
Here's my PHP script:
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "XXX",
'oauth_access_token_secret' => "XXX",
'consumer_key' => "XXX",
'consumer_secret' => "XXX"
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=#awkward&geocode=38.949926,-92.330037,35mi&result_type=recent';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
?>
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sample elections tweets</title>
<script>
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 json = JSON.parse(xmlhttp.responseText);
//here's where i'd like to put a for-loop
}
}
xmlhttp.open("GET","index.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<body>
Ok, I think I know what you are trying to do now. There really isn't an out of the box "for each" like there is in php, which is why a lot of frameworks implement there own (jQuery's $.each()), or make prototypes. But, you may be able to do what you need with the below. You can replace all the console.log() with alert() if you want, but it gets hectic not being in Chrome's dev tools (f12 on most machines). Also, if Dale Musser is still there tell him hello! MIZ
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 json = JSON.parse(xmlhttp.responseText);
//log entire json struct to developer console for easy viewing
console.log(json);
//you can reference individual pieces of json by doing something like
//json.statuses or json.statuses[2]
var statuses = json.statuses;
for(var i=0;i<statuses.length;i++){
var curStatus = statuses[i];
//access bits directly
var tweetAuthor = curStatus.user.name;
var tweetTime = curStatus.created_at;
//iterate hashtags
var hashtags = curStatus.entities.hashtags;
for(var k=0;k<hashtags.length;k++){
console.log("Hashtag: " + hashtags[k].text);
}
//iterate all elements of tweet
for(var key in curStatus){
var attrName = key;
var attrValue = curStatus[key];
console.log("attribute name: " + attrName);
console.log("attribute key: " + attrValue);
if(attrName = "text") {
//Do something with tweet texts... like:
//document.getElementById("statuses").appendChild(attrValue);
}
}
}
}
}
xmlhttp.open("GET","index.php",true);
xmlhttp.send();
}
I have a website that uses a javascript function below to populate List 2 when an item from the drop down List 1 is chosen. What I would like to achieve is to have List 2 and List 3 updated. The function is shown below works for both List 2 and List 3 separately but using an alert I can see that it stops after the first send if I put them together. How can I am make them both work together?
This is the Select that calls the function checkTeacherList which is working fine.
<select name="department_list" id="department_list" selected="All" onchange="checkTeacherList(this.value, '<?php echo $user_login;?>');" >
Th eJavaScript function checkTeacherList
<script type="text/javascript">
function checkTeacherList(departmentName, schoolName)
{
var xmlhttp;
//populating List 2
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("departmentTeachers").innerHTML=xmlhttp.responseText;
}
}
var d = new Date();
xmlhttp.open("GET","http://website/getTeachers1.php?schoolName="+schoolName+"&departmentName="+departmentName+"&nocache="+d.getSeconds(),true);
xmlhttp.send();
xmlhttp.send();
//populating List 3
alert("Is it getting this far?"); // this alert does not get reached
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("nondepartmentTeachers").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://website/getTeachers2.php?schoolName="+schoolName+"&departmentName="+departmentName+"&nocache="+d.getSeconds(),true);
xmlhttp.send();
xmlhttp.send();
}
</script>
The alert is not called because you are calling "xmlhttp.send();" twice.
The second call yields an error.
it is not really a good way to solve this problem. I should focus on setting up ONE AJAX connection , that the script just have to ask one connection.
The major advantage of using this method is the time required to gather all data. It will be double faster then doing it twice.
However, i am not sure if you can modify the php files.
If so, please edit it. I have noticed that both requests contains of same parameters.
in js;
// function to fill option
var fillOptions = function(data) {
// use data to fill drop down boxes
var teacher1 = data["teacher1"]; // get $teacher1 which is in 'teacher1'
var teacher2 = data["teacher2"]; // get $teacher2 which is in 'teacher2'
}
// function to check teacher list
function checkTeacherList(departmentName, schoolName)
{
// create object by browser type
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
// for IE6, IE5
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// event when request is done
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// get data
var data = JSON.parse(xmlhttp.responseText);
// send to function to handle it
fillOptions(data);
}
}
// open link
xmlhttp.open("GET","http://website/getAllTeachers.php?schoolName="+schoolName+"&departmentName="+departmentName+"&nocache="+d.getSeconds(),true);
// send
xmlhttp.send();
}
and in getAllTeachers.php ( a new php file, but you can wrap your two php file in one if you want)
$teacher1 = ... // teacher1 list
$teacher2 = ... // teacher2 list
// return with a JSON type
header('Content-Type: application/json');
// reply with json format
echo json_encode(array('teacher1' => $teacher1, 'teacher2' => $teacher2));
The php file will reply with data in JSON-format. In the js, you can see that the response is being handled with JSON.parse() function and being passed to fillOptions(data) function. There, you can access data submitted by php and use the same data to fill in your dropdown box.
(i don't know the response content, but
document.getElementById("nondepartmentTeachers").innerHTML = data["teacher2"];
should achieve the same result as intended )
If you want to go with your solution, you have called .send() function twice, which the second one will return into errors.
I have a form with a variable number of text boxes that contain an id. When the user exits the page, files on the server are deleted by a python script (delete.py). The filename of the files to delete contains the id so the id has to be passed to the python script. If my form has a single id, everything works perfectly and the file on the server is deleted. If my form has multiple id fields, no files get deleted. If I use firebug to step through the code, the files gets deleted regardless of the number of id fields. I don't understand what is going on. Any help would be greatly appreciated. My onbeforeunload method is below.
function deleteFiles()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
allElements = document.getElementsByName("id");
for (x=0; x < allElements.length; x++)
{
xmlhttp.open("GET","/cgi-bin/delete.py?id=" + allElements[x].value,true);
xmlhttp.send();
}
window.onbeforeunload = deleteFiles;
Sounds like the request's are being sent too fast. Try adding
xmlhttp.async = false;
function deleteFiles()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
allElements = document.getElementsByName("id");
xmlhttp.async = false;
for (x=0; x < allElements.length; x++)
{
xmlhttp.open("GET","/cgi-bin/delete.py?id=" + allElements[x].value,true);
xmlhttp.send();
}
window.onbeforeunload = deleteFiles;
Let me know your findings
The objective is to display a list of URLs in an HTML page. The list is retrieved from another file (currently in XML-format).
Validator: What is the proper xHTML mark-up for a list generated by JavaScript and still validate properly?
I assume the reason is that JavaScript-code inside [ul]'s is not accepted. Is this correct? Is there another solution?
The code below does produce the list anticipated, but it creates a warning (pls see below, 2.).
<ul>list A
<li>item A1</li>
<li>item A2</li>
<ul>List B
<li>item B1</li>
<script type="text/javascript">/* <![CDATA[ */
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.open("GET","/test-code/panorama-list2.xml",false);
// xmlhttp.open("GET","/test-code/panorama-list2.xml",true); //this does not work. xmlDoc is null.
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{ document.write('<li class="menu2">'+'<a href="');
document.write(x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue);
document.write('">');
document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
document.write('</li>'); }
//]]></script> //This is line: 136
</ul>
The JavaScript used in the code above is called using the synchronous method and thus creating the Warning:
"An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
/ Source File: /test-code/index2.htm / Line: 136"
The solution is to use the asynchronous method similar to the code below placed into the section.
The solution is NOT to simply setting 'true' in the function xmlhttp.open (..., ..., true);.
<script type="text/javascript">//<![CDATA[
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
xmlDoc = xmlhttp.responseXML;
var txt = "";
var txt1 = "";
var x = xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{
txt = x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue + "<br />";
txt1 = x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue + "<br />";
}
{
document.getElementById("myDiv").innerHTML=txt;
document.getElementById("myDiv1").innerHTML=txt1;
}
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
//]]></script>
That does take care of the Warning.
I assume a solution would be to combine these 2 examples of code.
That's what I am trying:
The Variables 'txt' and 'txt1' retrieve the last entry of the XML-file.
How do I get all entires as well? The amount of entries varies.
Here is the big question:
How can I create a proper list using the asynchronous method and obtain a result like in the initial code example where the list is generated by stepping through the XML-file?
After all, is there is another, better or simpler solution? The file with data for the list shall not be part of the xHTML mark-up.
At last an actual page using the initial code example. The list is revealed by hovering over the button at top-right: http://www.halo-photographs.com/2011-Cascata-da-Bernina/index.htm (yes, this is my own page)
Thanks for your attention.
you code is an soup..
you need refactor that
now with jquery
in the load the you page
you should put somthing how that
$(document).ready(function(){
BeforePrepareList();
});
function BeforePrepareList()
{
var xmlRequest = XmlHttpRequestResolver();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
var xmlDoc = xmlhttp.responseXML;
// you need parse string response a array or use xslt, the next
// is simple for each
ListSetting(xmlDoc);
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
function XmlHttpRequestResolver()
{
if (window.XMLHttpRequest)
return xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
function ListSetting(rawdata)
{
ListPopulate($("_PUT_YOUR_LIST_ID_HERE").get(0), rawdata);
}
function ListPopulate(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('All', '');
// THAT IS AN SIMPLE EXAMPLE, CHANGE FOR CREATE tag <a />
$.each(items, function (index,item) {
el.options[el.options.length] = new Option(item.[PROPERTY_A], item.[PROPERTY_B]);
});
}
and .....
more information here
invoke xml and transform http://www.ibm.com/developerworks/xml/library/x-ffox3/index.html
examples de http request http://www.jibbering.com/2002/4/httprequest.html