I am trying to add an item to the end of an array, kind of like an arraylist. I tried using the .push() but I can't get it working correctly reading from my xml. How could I "auto" update the array in jquery? (append to the end of it if you want to think of it that way)
Here is what my jquery looks like at the moment.
images = new Array();
$.ajax({
type: "GET",
url: strXMLURL,
dataType: "xml",
success: function(xml) {
$(xml).find("image").each(function() {
images.push($(this).attr("src"));
});
},
error: function() {
alert("Error reading the XML");
}
});
xml
<?xml version="1.0" encoding="utf-8" ?>
<gallery>
<image src="images/gallery/gallery1.jpg"/>
</gallery>
If you need any more information, I'll happily provide more.
Declare the images array inside the success function of the ajax call to ensure the scope remains correct then your function should work...
Related
I have a Javascript application and I need to retrieve an HTML file to template it. The way I am doing this now is:
var _$e = null;
$.ajax({
type: "GET",
url: "/static/jobs_overview.html",
async: false,
dataType: "xml",
success: function (xml) {
_$e = $(xml.documentElement);
}
});
This does seem to work, but for some reason, I am not getting a proper jQuery object in _$e. I know that because the styling is done by jQuery is getting lost at some point, but also, when I set a breakpoint in success, here is what I see:
> _$e
[<div class="hello" style="background-color:#FFD700;height:200px;width:100px;"><p> Hi </p></div>]
> _$e.width()
TypeError: Cannot read property 'position' of null
However, when I copy the HTML string manually and convert it to a jQuery object as in success, the output is:
> $('<div class="hello" style="background-color:#FFD700;height:200px;width:100px;"><p> Hi </p></div>').width()
100
Seems like the xml object returned isn't getting converted properly into jQuery (or not all attributes of the object are being read properly by jQuery -- given that the HTML is rendering but styling isn't).
The xml object is:
> xml
#document
<div class="hello" style="background-color:#FFD700;height:200px;width:100px;">…</div>
Any ideas how to get the xml (or the HTML file) rendered as a jQuery object properly?
Could it be because you're grabbing the datatype XML? Have you tried setting your datatype to HTML (or nothing) and just do this (ignoring the .documentElement and just assuming the whole glomp is your HTML):
$.ajax({
type: "GET",
url: "/static/jobs_overview.html",
async: false,
dataType: "html",
success: function (data) {
_$e = $(data); // we are getting back HTML,
console.log(_$e.width()); // jQuery is fine with html globs
}
});
This is likely because you are pulling it in as XML. Try setting the dataType to html and see if that makes any difference.
It also sounds like .load() might better fit your needs: http://api.jquery.com/load/
A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems.
However I am not quite managing it.
Here is what I have going on:
<h1>Whatever</h1>
<div id="replace_me">
</div>
<a id="click_me" href="#">Click Me</a>
<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
$("#click_me").click(function(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: dataX,
datatype: "json",
success: function(data) {
alert(data);
$("#replace_me").load(data);
},
error: function() {
alert("Nope...");
}
});
});
});
</script>
When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?
You have an error in your success function. Check documentation on jQuery load(). Instead, you should do
success: function(data) {
//alert(data);
$("#replace_me").html(data);
},
or, slightly better style
success: function(data) {
//alert(data);
$("#replace_me").empty().append($(data));
},
Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():
$("#replace_me").empty().append($(JSON.stringify(data)));
If your server does not produce valid JSON, your success method will not be called in most cases.
load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()
i.e.
var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);
Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.
I have seen several examples of how to load a file with javascript, however most of those examples use the data from the file to display it in a html.
I need to keep accessing a file since the file keeps updating and use those values in javascript as variables.
I got the closest with this,
function test() {
$().ready(function(){
var url = 'output.txt';
$.get(url, function(data) {
// can use 'data' in here...
console.log(data);
});
});
}
It logs document to the console and I can collapse that.
There is really a lot of stuff (to much to list here). I only don't know in what kind of format it needs the data to be or how to access it. I do see stuff about xml-stylesheet, so can i even use this?
Changing the way I write the file is no problem for me.
I suggest using a JSON file. For example:
{
username: "Rocket",
realname: "Eric",
age: 23
}
To read this, you can use jQuery's $.getJSON method.
$.getJSON('/path/to/your/file.json', function(data){
var username = data.username;
});
You can also use XML, though I suggest using JSON (it's easier to get the data from it).
<?xml version="1.0" encoding="UTF-8" ?>
<item> <!-- XML needs a root element -->
<username>Rocket</username>
<realname>Eric</realname>
<age>23</age>
</item>
jQuery doesn't have a $.getXML method, so we have to use $.get.
$.get('/path/to/your/file.xml', function(data){
var username = $('item', data).find('username').text();
}, 'xml');
Try using the Jquery GetJson method: Something like this. May need some tweaking.
$.ajax({
url: 'http://www.yourfile.html',
dataType: 'json',
data: data,
success: function(data){
$('#yourdiv').html(data);
}
});
I am trying to parse the following XML with javascript:
<?xml version='1.0' encoding='UTF-8'?>
<ResultSet>
<Result>
<URL>www.asd.com</URL>
<Value>10500</Value>
</Result>
</ResultSet>
The XML is generated by a PHP script to get how many pages are indexed in Bing.
My javascript function is as follows:
function bingIndexedPages() {
ws_url = "http://archreport.epiphanydev2.co.uk/worker.php?query=bingindexed&domain="+$('#hidden_the_domain').val();
$.ajax({
type: "GET",
url: ws_url,
dataType: "xml",
success: function(xmlIn){
alert('success');
result = xmlIn.getElementsByTagName("Result");
$('#tb_actualvsindexedbing_indexed').val($(result.getElementsByTagName("Value")).text());
$('#img_actualvsindexedbing_worked').attr("src","/images/worked.jpg");
},
error: function() {$('#img_actualvsindexedbing_worked').attr("src","/images/failed.jpg");}
});
}
The problem I'm having is firebug is saying: 'result.getElementsByTagName is not a function'
Can you see what is going wrong?
Thanks
I actually just fixed it, what I was doing wrong was when I was trying to set the value of '#tb_actualvsindexedbing_indexed' I was not telling it to use the first entry of the xml, and was just passing it the entire object.
$('#tb_actualvsindexedbing_indexed').val($(result[0].getElementsByTagName("Value")).text());
Thanks for the help anyway.
result = xmlIn.getElementsByTagName("Result")[0];
$('#tb_actualvsindexedbing_indexed').val($(result.getElementsByTagName("Value")[0]).text());
element = element; elements = array of elements