I'm trying to assign the contents of an xml file to a var, like so:
var testing = $.load('xx.xml');
$('#display').text(testing);
but it's not working. I tried the ".load" function as suggested in:
How to assign file contents into a Javascript var
and I had a look at the page they suggest form the jquery website, but I can't find something specific to assigning the contents of the .xml file to the var as a string.
I appreciate this is probably very obvious & I am arguably being lazy, but I have been trying random things for a while & cannot figure this out.
Thanks
EDIT! I was loading up the contents inside the load function, i didn't mean this, it's now edited.
Firstly, $.load isn't a defined function in the latest jQuery source, nor is it documented on the jQuery site.
Secondly, assuming you haven't modified jQuery's global AJAX settings, jQuery.fn.load and other request functions will be asynchronous, so you can't just assign the result to a variable because the function returns before the request has completed. You need to use callback handlers.
Try using $.ajax with a callback function instead:
var testing;
$.ajax('xx.xml', {
dataType: 'text',
success: function (data) {
testing = data;
$('#display').text(testing);
}
});
Since you want the data as text and the file appears to be XML, we're using dataType to tell jQuery to return the data as a string.
There is no $.load function. What you probably want is jQuery.get:
var xml;
$.get("xx.xml", function(data) {
xml = data;
});
As the file is retreived asynchronously, you need to assign the result to the variable inside the callback, which is executed when the request returns successfully. Note however that if you try and run code that depends on xml after the .get call, xml is going to be undefined because the callback won't have run yet. For example:
var xml;
$.get("xx.xml", function(data) {
xml = data;
//Do stuff with data here
});
console.log(xml); //Most likely undefined because asynchronous call has not completed
If you are trying to insert the results into a DOM element, then you can use the .load method:
$("#someElem").load("xx.xml");
if you are trying to get an xml from your server using ajax, you may try something like this -
function getXml()
{
var contents;
$.ajax({ url :'/website/method', type: 'GET', dataType :'xml', async : false,
cache : true, success : function(myXml){
contents = myXml;
}
});
return contents;
}
Related
I am trying to parse a yaml file that exists as a local file in the filesystem and assign it to a variable that can be used in jquery.
I can see from the console.log that _yaml variable contains the read yaml in a readable format but the returning of it and assigning it to ymlconfig does not seem to work (//NOT WORKING part below shows up as undefined in console).
$( document ).ready(function() {
var ymlconfig = read_config('config.yaml');
console.log(ymlconfig["compute"][0]); //NOT WORKING
function read_config(cfgfile) {
$.get({url: cfgfile, dataType: "text"}).done(function (data) {
var _yaml = jsyaml.load(data);
console.log(_yaml["compute"][0]) //WORKING OK
return _yaml;
});
};
This string:
console.log(ymlconfig["compute"][0]); //NOT WORKING
executes before the config is read. Because the called read_config('config.yaml') runs asyncronously in the separate thread.
Also your function read_config(cfgfile) does not return any value.
To better understand this behaviour please read and run the following code:
$( document ).ready(function() {
var ymlconfig;
read_config('config.yaml'); // calling function
console.log(ymlconfig["compute"][0]); // is empty
setTimeout(function() { // let's wait 2000 ms. hope it's enough to send the request and receive and read the response
console.log(ymlconfig["compute"][0]); // TADA! It's read.
}, 2000);
function read_config(cfgfile) {
$.get({url: cfgfile, dataType: "text"})
.done(function (data) {
ymlconfig = jsyaml.load(data);
});
};
});
So depending on your task you have several options:
work with the config data within .done callback function,
or make your request syncronous,
or catch the asyncronous response (e.g. using promise)
or maybe something else?
Hi I am using ajax to do a post request. I think what I want to do is call a function within a php file but am a little confused if and how you do this, could anyone shed any light on this? This is what I have in my js file:
function callAjaxAddition2() {
arguments0 = jQuery('#code').val();
$.ajax({
type: "POST",
url: file.php",
data: {code: arguments0},
success: function(data) {
request( $posted )
}
});
return false;
}
'request' is a function within the php file.
Update I think I should be able to trigger what I need to using this: http://docs.woothemes.com/document/wc_api-the-woocommerce-api-callback/ if I put the url into the url field however that doesn't seem to work, how might I use a callback with ajax post?
First fix this line with the missing opening quote file.php".
You cannot call a PHP function through AJAX but can trigger when it needs to be called, the following demonstrates the same:
In your PHP, your code would be:
if(isset($_POST['code'])){
#'code' here is the identifier passed from AJAX
request($_POST['code']);
}
Once your function has been called, does the necessary and returns the output to AJAX, you can use the data parameter you have set to see what output was sent back from PHP:
success: function(data) {
alert(data); //contains the data returned from the
//PHP file after the execution of the function
}
Calling on a php file via ajax call is like running the script that you pass in the url parameter.
You don't get access to the inner functions, all you can do is pass data and get response.
If you want the request() function to be called in the script, you will have to call it in the php script.
When I do console.log(info) is it possible to later use JS to extract everything from the browsers console and add it to a var? I would like to extract all contents of the console and send it to the server through AJAX
Basically I'm looking for something like:
var console_content = console.read();
Is there anything in JS or jQuery that will make this possible?
instead of writing to the console (which you really shouldn't do in a production environment) why not just push each thing you want to log to an array and then pass it to the server with a PUT when you want to?:
var _log = [];
//instead of console.log(message)
_log.push({message:'message goes here'});
//using jquery because it's easier
function pushAjax(url, data, callback, method) {
return jQuery.ajax({
url: url,
type: method,
data: data,
success: callback
});
}
//call your push function when you want...
pushAjax('www.yourserver.com',_log,'PUT',successFunction);
I really need your help.
I got this problem in my jQuery, i try to make a ajax call to a Javascript there keep an array inside in this file.
test-ajax.js
var data = ["kategori", "Alarm"];
return data;
But it come not with an array or anything not a single error.
Here is the ajax call.
$(document).ready(function() {
$(".tip").mouseover( function() {
$.ajax({
url: "http://localhost:8080/kraftvaerk/falck/FalckAlarmWeb/FalckAlarmWeb.Website/js/test-ajax.js",
dataType: "javascript",
succes: function(resultat) {
console.log("here");
$(".tip").append("<span>Katagori: " + resultat[0] + " <br /> Beskrivelse: "+ resultat[1] +"</span>");
}
});
});
});
In Html i got a table inside that table is there an a tag with class tip.
When the user mouse over that tag it should make the ajax call.
WARNING.
I use jQuery 1.2.2 the customer site i canĀ“t upgrade it
Json is not ALLOW on thit project.
You don't need to define and return a variable in your test-ajax.js file. You can simply define it as follows:
["kategori", "Alarm"]
Also, you had an extra bracket on the end that was invalid syntax.
The method you are using is more similar to jsonp. jsonp works by including a script tag on your page that points to a js script that executes a function containing the data.
For example, your test-ajax.js would be:
testajax(["kategori", "Alarm"]);
and to request it, simply do this:
window.testajax = function(data) {
console.log(data[0],data[1]);
};
$.getScript("test-ajax.js");
There you go. you just performed your first JSONP request, and it didn't involve any "json".
i try to do the same like you but from $.ajax it is not returning the result but if you use the below example then you will get the result but your file should like this :
JScript1.js ["kategori", "Alarm"]
JScript1.json ["kategori", "Alarm"]
1. $.getJSON("JScript1.js", function (data) {
console.log(data);
});
2. $.getJSON("JScript1.json", function (data) {
console.log(data);
});
result:
Array[2]
0: "kategori"
1: "Alarm"
length: 2
I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).