Hi I have the following script to look up an xml file and produce an ordered list
$(document).ready(function() {
$.ajax({
type: "GET",
url: "search_action.php" + string,
dataType: "xml",
success: disxml
});
})
} // function
function disxml(data) {
$(data).find('results').find('client').each(function(row) {
name = $(this).find('name').text();
var add1 = $(this).find('address1').text();
var add2 = $(this).find('address1').text();
var pcode = $(this).find('postcode').text();
var num1 = $(this).find('number1').text();
var num2 = $(this).find('number2').text();
var contact = $(this).find('contact').text();
var email = $(this).find('email').text();
display += "<a onclick='populate();'> <b>" + name + "</b> - " + add1 + "<br></a>";
})
divbox.html(display); // draw contents
}
function populate() {
}
this is the xml file that it is referencing
<results>
<client>
<name>Ascot Racecourse</name>
<address1>Berkshire</address1>
<address2/>
<postcode>SL5 7JX</postcode>
<number1/>
<number2/>
<contact>Alastair Warwick</contact>
<email>As per course</email>
</client>
<client>
<name>Aston Villa Football Club</name>
<address1>Villa Park</address1>
<address2>Birmingham</address2>
<postcode>B6 6HE</postcode>
<number1/>
<number2/>
<contact>Andrew Evans </contact>
<email>Info#avfc.co.uk</email>
</client>
<client>
<name>Asda 1 Year Celebration</name>
<address1>Park In Ipswich</address1>
<address2>Ipswich</address2>
<postcode>IP</postcode>
<number1/>
<number2/>
<contact/>
<email>Jonathan Stephenson</email>
</client>
</results>
it does all work fine , when I have my list I have a link on each line which when clicked calls the function 'populate'
When the script gets to the populate function I am really stuck as how I reference the particular results line that called the function , how can I find this ?
Thanks for any help and I hope it makes sense !!
This should do:
function disxml(data) {
$(data).find('results').find('client').each(function(row) {
var clientItem = this;
var name = $(clientItem).find('name').text();
var add1 = $(clientItem).find('address1').text();
var add2 = $(clientItem).find('address1').text();
var pcode = $(clientItem).find('postcode').text();
var num1 = $(clientItem).find('number1').text();
var num2 = $(clientItem).find('number2').text();
var contact = $(clientItem).find('contact').text();
var email = $(clientItem).find('email').text();
var link = $("<a href='#'><b>" + name + "</b> - " + add1 + "<br/></a>")
link.click(function(evt){
evt.preventDefault();
populate(clientItem);
});
divbox.append(link);
});
}
function populate(item) {
alert("Populating " + $(item).find("name").text());
}
Related
I have dynamic text field at Demo JSFiddle and I have done the autocomplete part for my item part no.
$ (document).ready(function() {
$("#addField").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div id=\"field" + intId + "\"/>");
var fpartNo = $("<input type=\"text\" name=\"erfq_partNo[]\" class=\"partNumber\"/>");
var fDescription = $("<input type=\"text\" name=\"erfq_desc[]\" disabled/>");
var fPrice = $("<input type=\"text\" name=\"erfq_price[]\" disabled style=\"width:80px\"/>");
// remove textboxes and dropdown boxes
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fpartNo);
fieldWrapper.append(fDescription);
fieldWrapper.append(fPrice);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
$(".partNumber").autocomplete({
minLength:1,
source: 'readPart.php',
select: function(event, ui){
var selected = ui.item.value;
}
});
});
});
readPart.php
$searchTerm = $_GET['term'];
$getPartSQL = base_executeSQL("SELECT * FROM eitem_item where eitem_item_part_no LIKE '%".$searchTerm."%' ORDER BY eitem_item_part_no" );
while($Partdata_row = base_fetch_array($getPartSQL))
if (base_num_rows($getPartSQL)!= 0)
{
$data[] = $Partdata_row['eitem_item_part_no'];
}
echo json_encode($data);
The first text field is uses for entering the part No.
My question is once the part no has been entered, the other relevant information (description and price) will be displayed at the other readonly text fields which the data are extract from my database. I have no idea what to continue with this select: function(event, ui){. Any help will be appreciated.
well, if you want to get the data on the basis of part # from database you can trigger an ajax call on blur of text box part number.
you can do something like this
$("#partNum").blur(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part, //url to your database fetcher code.
complete: function (response) { //response contains what you got from pap page
$('textarea#des').val(response.responseText); //set textarea and textbox value popping out from db file
}
});
});
Here is HTML snippet to this request.
<input type = 'text' id = 'partNum' name = 'parts' />
<textarea id = "des" name = 'description' disabled></textarea>
FIDDLE
this will work on blur means when clicked outside the textbox. But if you want to get real time data(while user is typing) then you've to bombard the ajax requests on keyup event.
something like this:
$("#partNum").keyup(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part,
complete: function (response) {
$('textarea#des').val(response.responseText);
}
});
});
FIDDLE here
Hope this will help.
Hello I am trying to parse a .json file.. it only has 1 set of data I don't think the $.each is the best approach but it's all I can find....
Here is my code:
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var url = 'http://f.cl.ly/items/1L2k221B183J1e1G411j/200.json';
/* <![CDATA[ */
$(document).ready(function(){
$.getJSON(url, function(data){
$.each(data.test, function(i,test){
content = '<h1><p class="p1"><span class="s1">' + test.name + '</span></p></h1><table class="table table-bordered"><tbody><tr><td>Section:</td><td>Chemistry</td></tr><tr><td>Synonyms:</td><td>Mg Level</td></tr><tr><td>Container:</td><td>' + test.container + '</td></tr><tr><td>Reference Ranges:</td><td>' + test.reference + '</td></tr><tr><td>Availability:</td><td>' + test.availability + '</td></tr><tr><td>Special Handling:</td><td>' + test.specialHandling + '</td></tr><tr><td>Additional Comments:</td><td>' + test.additionalComments + '/td></tr></tbody></table>';
$(content).appendTo("#main");
$("#main").fadeIn( );
});
});
});
/* ]]> */
</script>
The result kinda works... the table is there but the code loops 3 times and displays "undefined" for all veribles.
Any help would be great!
Just use the result data without a loop. If data.test is not an array, you can access the object properties directly.
something like :
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var url = 'http://f.cl.ly/items/1L2k221B183J1e1G411j/200.json';
/* <![CDATA[ */
$(document).ready(function(){
$.getJSON(url, function(data){
content = '<h1><p class="p1"><span class="s1">' + data.test.name + '</span></p></h1><table class="table table-bordered"><tbody><tr><td>Section:</td><td>Chemistry</td></tr><tr><td>Synonyms:</td><td>Mg Level</td></tr><tr><td>Container:</td><td>' + data.test.container + '</td></tr><tr><td>Reference Ranges:</td><td>' + data.test.reference + '</td></tr><tr><td>Availability:</td><td>' + data.test.availability + '</td></tr><tr><td>Special Handling:</td><td>' + data.test.specialHandling + '</td></tr><tr><td>Additional Comments:</td><td>' + data.test.additionalComments + '/td></tr></tbody></table>';
$(content).appendTo("#main");
$("#main").fadeIn( );
});
});
/* ]]> */
</script>
Try this:
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var url = 'http://f.cl.ly/items/1L2k221B183J1e1G411j/200.json';
/* <![CDATA[ */
$.getJSON(url, function(data)
{
for(var i in data.test)
{
var obj = data.test[i];
var content = '<h1><p class="p1"><span class="s1">' + obj.name + '</span></p></h1><table class="table table-bordered"><tbody><tr><td>Section:</td><td>Chemistry</td></tr><tr><td>Synonyms:</td><td>Mg Level</td></tr><tr><td>Container:</td><td>' + test.container + '</td></tr><tr><td>Reference Ranges:</td><td>' + obj.reference + '</td></tr><tr><td>Availability:</td><td>' + obj.availability + '</td></tr><tr><td>Special Handling:</td><td>' + obj.specialHandling + '</td></tr><tr><td>Additional Comments:</td><td>' + obj.additionalComments + '/td></tr></tbody></table>';
$(content).appendTo("#main");
$("#main").fadeIn( );
}
});
/* ]]> */
</script>
$.each(Object or Array, iterator) is probably what you should use. The real issue is that data.test has to be an Object or an Array, not an Object property that's not an Object or an Array.
I wrote a JavaScript function to convert GeoJson data to WKT format. It works when i get the input value in the javascript code directly. But I don't know how to get the input from the php and send it back.
Here is the php code:
<?php
$geojson=file_get_contents("clipfeature.geojson");
$WKT = $_POST['wkt'];
echo ($WKT);
?>
So it gets geojson data from a file and I want to receive the converted WKT code from the Javascript function.
Please help me finish the JavaScript Code:
function converttoWKT (){
$.ajax({
type: "GET",
url: "readJson.php",
contentType: "application/json"
}).done(function (data) {
var JSONObject = How to give the value from PHP to this Variable;
var coordinate = JSONObject.features[0].geometry.coordinates;
var type= JSONObject.features[0].geometry.type;
var coordinate1 = "";
var coordinate2 = "";
for (var i=0; i< coordinate[0].length; i++) {
coordinate1= coordinate[0][i][0]+" "+coordinate[0][i][1];
coordinate2=coordinate1+","+coordinate2;
}
var WKT= "\""+ type + "((" + coordinate2;
WKT=WKT.substring(0,WKT.length-1);
WKT=WKT+"))\""
sendback ( );
});
function sendback(){$.post("readJson.php",
{'wkt':How to send the value of var WKT back to php 'wkt'
});
}
Basically:
var jsVar= "<? echo $myVariable_value_goes_in_here; ?>";
or, as mentioned above:
var JSONObject = <? echo json_encode($WKT); ?>;
// this NEED TO BE json, otherwise syntax error in JS!
Since you already know your return data will be JSON, you can just use $.getJSON() for convenience. This is a $.get() request paired with JSON.parse(). With $.getJSON(), the JSON is parsed on response. To send the data back, just use use jQuery's $.post().
Here's an edited version of your code.
function converttoWKT() {
$.getJSON('clipfeature.geojson', function(data) {
var coordinate = data.features[0].geometry.coordinates;
var type = data.features[0].geometry.type;
var coordinate1 = '';
var coordinate2 = '';
for(var i = 0; i < coordinate[0].length; i++) {
coordinate1 = coordinate[0][i][0] + ' ' + coordinate[0][i][1];
coordinate2 = coordinate1 + ',' + coordinate2;
}
var WKT = '"' + type + '((' + coordinate2;
WKT = WKT.substring(0, WKT.length - 1);
WKT = WKT + '))"'
sendback(WKT);
});
};
function sendback(data) {
$.post('readJson.php', {
'wkt': data
});
};
i have a upload form that uses the new multiple attribute and i made an ajax upload form to make things more user friendly. My problem is im trying to update percentages for all of these files that are being uploaded and appended to a div, instead of one percentage being updated all of them get updated from the last file. Here is some code.
$('#File').change(function(event) {
for(I = 0; I < this.files.length; I++)
{
var Name = this.files[I].name;
var Size = this.files[I].size;
var Type = this.files[I].type;
$('#UploadContent').prepend('<div class="UploadLabel" style="width:60%;">'+Name+'</div><div class="UploadLabel UploadPercent" style="width:10%;">0%</div><div class="UploadLabel" style="width:15%;">N/A</div><div class="UploadLabel" style="width:15%;">'+Type+'</div>');
var Data = new FormData();
Data.append('File[]', this.files[I]);
var Request = new XMLHttpRequest();
Request.upload.addEventListener('progress', function(event){
if(event.lengthComputable)
{
var Percent = event.loaded / event.total;
var Progress = $('#UploadContent').find('.UploadPercent');
$(Progress).text(Math.round(Percent * 100) + '%');
}
});
Request.upload.addEventListener('load', function(event) {
});
Request.open('POST', '/Home/Upload/Upload.php');
Request.setRequestHeader('Chache-Control', 'no-cache');
Request.send(Data);
$('#UploadModal').fadeIn('fast');
}
});
now as you can see in the progress listener my
var progress = $('#UploadContent').find('.UploadPercent');
how would i select the file that is supposed to be updated correctly. If someone can find a comepletely different method to change the percent that would be great too! - Thanks!
When you're prepending, add a new, specific class (yes, you could use an id, but I'd just stick to class) to the .UploadPercent element:
$('#UploadContent').prepend('<div class="UploadLabel" style="width:60%;">'+Name+'</div><div class="UploadLabel UploadPercent UploadTarget' + I + '" style="width:10%;">0%</div><div class="UploadLabel" style="width:15%;">N/A</div><div class="UploadLabel" style="width:15%;">'+Type+'</div>');
// LOOK HERE----------------------------------------------------------------------------------------------------------------------^ HERE
And when you're targeting, use this:
var progress = $('#UploadContent').find('.UploadTarget' + I);
Because you need the value of I to be accurate based on where you are in the loop, you need to use a closure as well. So your code will end up looking like:
$('#File').change(function(event) {
for(I = 0; I < this.files.length; I++) {
(function (I) {
// Your current code inside the for loop
})(I);
}
});
While the example from above is definitely an option, it probably makes more sent to just store a reference to the newly inserted element and not have to deal with a new class and I, and then use it later.
Here is the final code I'd use:
http://jsfiddle.net/MeL7L/2/
$("#File").on("change", function (event) {
for (var i = 0; i < this.files.length; i++) {
(function (curFile, i) {
var Name = curFile.files[i].name;
var Size = curFile.files[i].size;
var Type = curFile.files[i].type;
var newEl = "";
newEl += '<div class="UploadLabel" style="width:60%;">' + Name + '</div>';
newEl += '<div class="UploadLabel UploadPercent" style="width:10%;">0%</div>';
newEl += '<div class="UploadLabel" style="width:15%;">N/A</div>';
newEl += '<div class="UploadLabel" style="width:15%;">' + Type + '</div>';
newEl = $(newEl);
$("#UploadContent").prepend(newEl);
var Data = new FormData();
Data.append("File[]", curFile.files[i]);
var Request = new XMLHttpRequest();
Request.upload.addEventListener("progress", function (event){
if (event.lengthComputable) {
var Percent = event.loaded / event.total;
var Progress = newEl.find(".UploadPercent");
Progress.text(Math.round(Percent * 100) + "%");
}
});
Request.upload.addEventListener("load", function(event) {});
Request.open("POST", "/Home/Upload/Upload.php");
Request.setRequestHeader("Cache-Control", "no-cache");
Request.send(Data);
$("#UploadModal").fadeIn("fast");
})(this, i);
}
});
One page I have articles with prices. I would like to do administration. When I am administrator and I would click on price input field text would show.
My code for this:
$('#priceBig').click(function() {
var originalelement = this;
var dishID = this.id;
var currentText = $.trim($(this).text())
$(this).hide().before('<input class="input" id="'+dishID+'" style="padding:3px; text-align:left; font-size:17px; width:50px;" type="text" value="'+currentText+'"/>');
$('.input').live('change', function() {
var picaID = this.id;
var price = $(this).val();
var thisparam = this;
$.post('<?= site_url('dish/changePicaBigPrice') ?>',{ picaID : picaID, price:price},
function(data) {
$(thisparam).remove();
$(originalelement).text(price).fadeIn(1000);
},'text');
});
});
But this doesn't work because jQuery store all originalelement objects and every change of price change all originalelements which were clicked before...
I hope I was clear what I want to do.
I would like to click on price, change and one I go on other price
I believe my old answer won't work.
New tactics - save the old ID in an attribute on the new input you create, and use it in the success handler.
$('#priceBig').click(function() {
var currentText = $.trim($(this).text())
var input = $('<input />')
.addClass('input')
.attr('type', 'text')
.attr('orig-id', $(this).attr('id'))
.val(currentText)
.bind('change', function () {
var t = $(this);
var price = t.val();
var origID = t.attr('orig-id');
$.post('<?= site_url('dish/changePicaBigPrice') ?>',{ picaID : origID, price:price},
function(data) {
t.remove();
$('#' + origID).text(price).fadeIn(1000);
},'text');
});
$(this).hide().before(input);
});
EDIT: fixed typo in var origID = t.attr('orid-id');
EDIT: change picaID to origID in the $.post parameters