I'm querying a large (1000 nodes) XML file using the following code :
$.ajax({
type: "GET",
cache: false,
url: "someFile.xml",
dataType: "xml",
contentType: "text/xml",
success: function(xmlHttpRequest)
and the following XML structure :
<hospitals>
<hospital>
<id>1</id>
<name>H1</name>
<city>Riyadh</city>
<tel>1234567</tel>
<coordinates>27.034052,49.490662</coordinates>
</hospital>
</hospitals>
My question is : Is there a way to filter (based on city for example) the XML file in place without reading the whole file and then filtering it by myself ? I'm pretty sure there is a field in the above call the does the filtering but I cannot figure it out.
use parse XML like
var xml = "<hospitals>\
<hospital>\
<id>1</id>\
<name>H1</name>\
<city>Riyadh</city>\
<tel>1234567</tel>\
<coordinates>27.034052,49.490662</coordinates>\
</hospital>\
</hospitals>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "city" ).text();
if($title=='Riyadh')
alert($xml.find("tel").text());
http://jsfiddle.net/9JUNK/3/
or you can use dataFilter to filter the response and then process it in the success handler
dataFilter(data, type)Function
A function to be used to handle the raw response data of XMLHttpRequest.
This is a pre-filtering function to sanitize the response.
You should return the sanitized data. The function accepts two arguments:
The raw data returned from the server and the 'dataType' parameter.
Related
I am trying to load an xml file containing config for a single page apps logic using jquery.
I can get the console to show the xml has been loaded and even display the xml in console but have yet to be able to get the xml to be declared as a string variable. I am using the following code
$.ajax({
type: "GET",
url: "dummy.xml",
dataType: "xml",
success: function (url) {
console.log('started function xml');
console.log(url);
// Parse the xml file and get data
parseXMLConfig;
}
});
I have a separate function to parse the xml using jquery which works if I declare the xml directly in the JavaScript but need to separate the xml and js for later development efforts.
Can anyone tell me how to set the js object to a variable for use elsewhere in scripts.
You can do something like this
$.ajax({
type: "GET",
url: "dummy.xml",
success: function (xmContent) {
console.log(xmContent);
xmlDoc = $.parseXML(xmContent),
$xml = $( xmlDoc ),
$title = $xml.find( "title" );
console.log($title );
}
});
For more detail refer DOC
I have a PHP file called terminal_tester.php which runs a number of terminal actions and creates json data at the end using
echo json_encode($jsonData);
The data looks like this
{"source":"Betting Tips","published":"2015-05-20 15:20:22;","status":true,"eventIDs":["27448131","27448900"],"TipsTB":"TIP 1 MLADENOVIC TO BEAT RISKE\",\"TIP 2 DOLGOPOLOV TO BEAT GULBIS\"]","TipsTW":"[]"}
I now want to populate my HTML file with this data, but am having trouble understanding the correct format for the Ajax data input. I am trying the below in the script area of my html file
function callbackData(){
return $.ajax({
dataType: 'JSON',
url: 'terminal_tester.php',
type: 'GET',
cache: false,
data: jsonData
});
};
callbackData().success(function (data) {
document.getElementById("phpReturn2").innerHTML = jsonData
document.getElementById("phpReturn3").innerHTML = eventIds
document.getElementById("phpReturn4").innerHTML = published
});
but I'm not getting any response. I've searched and I think the problem lies in the data: area of the ajax request but am also confused by the need of a GET command in the PHP file. Could somebody explain how to correctly structure the ajax request?
EDIT
terminal_tester.php has quite a few functions which come together at the end to build the json data, the final part of the php file looks like this
$jsonData = createJson($eventIds, $TipsTB, $TipsTW, $status);
echo json_encode($jsonData);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($jsonData));
fclose($fp);
First, I think your json data is incorrect. It should be like this-
{"source":"Betting Tips","published":"2015-05-20 15:20:22","status":true,"eventIDs":["27448131","27448900"],"TipsTB":["TIP 1 MLADENOVIC TO BEAT RISKE","TIP 2 DOLGOPOLOV TO BEAT GULBIS"],"TipsTW":"[]"}
Second, normal jquery ajax syntax is -
$.ajax({
dataType: 'JSON', //This means data which come back from terminal_tester.php should be in json format.
url: 'terminal_tester.php',
type: 'GET', // If you are using get request then you should get data by $_GET[]
cache: false,
data: {"jsonData":jsonData}, // Edited this from your code.
success:function(data){ //This data is coming from terminal_tester.php
alert(data.result);
}
});
In terminal_tester.php, it should be like this-
if(isset($_GET['jsonData'])){
$jsonData = $_GET['jsonData']; // GET array (Edited)
// your operation with $jsonData
// In the end, below json will be get in success data.
echo json_encode(array('result'=>true));
}
Hope this helps you!!
$.ajax().success() has a data parameter for accessing the data sent back from your GET request. eventIds and published are both properties of data.
callBackData().success(function (data) {
document.getElementById("phpReturn2").innerHTML = jsonData;
document.getElementById("phpReturn3").innerHTML = data.eventIds;
document.getElementById("phpReturn4").innerHTML = data.published;
});
I've been searching around, but I cannot find an answer, my guess is that my question is not defined very well, so i hope to get some guidance
I'm using turbogears2.2
I'm sending from the client view a JavaScript object through $.post(),
On the server I receive this object (as kw):
{'phones[1][surname]': u'sym', 'phones[2][name]': u'', 'phones[1][phone]': u'5498498', 'phones[0][phone]': u'0564', 'phones[1][name]': u'jhon', 'phones[0][surname]': u'cat', 'phones[2][phone]': u'', 'phones[0][name]': u'bob'}
I'm sending a data from a table with 3 columns
On my server I'm trying to separate the data for each row, but I'm a bit lost here.
how can I split that dict into different rows of data?
Doing
import json
json.loads(str(kw))
Fails
{ValueError}: Expecting property name: line 1 column 2 (char 1)
How can I convert that dict/object to a nested dictionary (or something else)?
Thanks
Thanks for the help Martijn Pieters , I thought I was posting JSON, but i wasn't.
You didn't post JSON; you posted application/x-www-form-urlencoded data that jQuery formatted for the PHP array feature. – Martijn Pieters
Here is my JavaScript, I'm trying out HandsOnTable (jQuery data grid editor)
$("#sendToServer").click(function(){
var tableData = $("#myTable").data('handsontable');
$.post(
URL,
{phones:tableData.getData()},
function(data){
console.log(data)
}
)
})
And that wasn't JSON, even though I thought it was
Anyway, simple fix:
Client side (JavaScript):
var tableData = $("#myTable").data('handsontable');
var jsonData = JSON.stringify(tableData.getData())
...
$.post(URL,
{phones:jsonData},
...
)
And now on the server side (Python):
import json
def getPhones(self,**kw):
phones = json.loads(kw['phones'])
...
And I have the data as a dict of rows, great
Thanks for the guidance
To post JSON, don't use $.post(). Use $.ajax() instead, and set the content type explicitly:
$.ajax({
url: URL,
type: "POST",
data: JSON.stringify({phone: tableData.getData()}),
contentType: 'application/json; charset=utf-8'
dataType: 'json',
success: function(data) {
console.log(response);
},
});
This can especially help if you have a controller that handles JSON directly, such as those provided by TurboGears Web Services.
Trying to pass a array using ajax call.
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info: info, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
However when i try to catch it on the server side using :
request.getParameter("info"); //Displays null**
Also, if i wish to send an array of arrays ? is it possible?
I tried using serialize however my IE throws error that serialize : object doesnt support this property i Did include jquery lib.
You can use JSON.stringify(info) to create a JSON representation of the object/array (including an array of arrays). On the server side you should be able to get the string via getParameter and then unserialize it from JSON to create constructs JSP can use.
Yes,It is Possible to send arrays.
var info_to_send = ['hi','hello'];
$.ajax({
type: "POST",
data: {info: info_to_send, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
You can only provide strings in a request url.
You could encode the array like so:
info = JSON.stringify(info);
// results in "['hi', 'hello']"
Then send it to the server, also JSON parse on the server.
You will need to go to http://www.json.org/ to get a Java implementation of JSON parsing.
I'm having some problems posting data from a web page, using jQuery, to a servlet. While I'm an experienced Java developer, I'm very new to javascript/jQuery/servlets. I'm using Eclipse, Apache Tomcat, and Chrome.
I have an XML file (from 6KB to 30MB in size) that I wish to load into the browser, modify, then post to the servlet.
My HTML has:
<input id="filechooser" type="file" onchange="readFile()">
My JS has:
var file = document.getElementById('filechooser').files[0];
var reader;
reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = loaded;
function loaded(evt){
var result = evt.target.result;
var xml = $(result);
...
[make modifications to xml]
}
Some jQuery code that I use in modifying the xml are $(xml).find("NODE").val() and $(xml).find("OTHER_NODE").attr("attribute-name","newValue")
I now need to post that xml to a URL, where it will be used to process some information. In the Chrome console, I can view the content of the xml object:
> xml
[<!--?xml version="1.0" encoding="ISO-8859-1"?-->,#text,
<root_element>...</root_element>]
> $(xml)
[<!--?xml version="1.0" encoding="ISO-8859-1"?-->,#text,
<root_element>...</root_element>]
> console.dir(xml)
jQuery.fn.jQuery.init[3]
0: #comment
1: #text
2: root_element
length: 3
__proto__: Object[0]
My servlet is empty so far:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Post");
}
I created a button that executes some javascript. The following two code snippets both post to the server:
$.post("http://localhost:8080/MyWebApp/MyWebAppUrl", xml);
and:
$.ajax({
type: "POST",
url: "http://localhost:8080/MyWebApp/MyWebAppUrl",
data: xml
});
My problem is, I don't know if I'm sending my XML correctly, or how to properly consume it. What do I need to do to my jQuery code to post it correctly? How do I get it out of my HttpServletRequest? If I can get the xml text as a String, I know exactly how to manipulate it in Java, and get it to do whatever I want.
After 10+ hours searching the web, I still can't find the answer. I'm sure it's out there, but I can't seem to connect the dots.
UPDATE:
epascarello was spot on for posting an XML document. However, I was parsing the document incorrectly.
Notice that I read the file, then stored the result var xml = $(result). The file was read as a text string, and I was converting it to an HTML document.
What I needed to do was var xml = jQuery.parseXML(result). That way, I didn't have to convert it back to a text string, and tag capitalizing is maintained.
Note that maintaining capitalization is of critical important.
Set the content type
$.ajax({
type: "POST",
contentType: "application/xml", //or text/xml?
url: "http://localhost:8080/MyWebApp/MyWebAppUrl",
data: xml
});
Add processData: false to your call and it should leave the string alone...
$.ajax({
type: "POST",
contentType: "application/xml", //or text/xml?
url: "http://localhost:8080/MyWebApp/MyWebAppUrl",
data: xml,
processData: false
});