I am attempting to retrieve data from a table on another website using YQL and display the data in a form on my website using jQuery. I have been successful retrieving the data and displaying it on my website as-is, however, I am not sure where to start to put the data into my form inputs.
The data being retrieved looks like this:
<table>
<tbody>
<tr class="">
<td class="nobr">
C Borup
</td>
<td class="num IP">
<p>0.2</p>
</td>
<td class="num H:pitching">
<p>2</p>
</td>
[...]
</tr>
</tbody>
</table>
I guess I can do 1 of 2 things at this point.
1) Try to convert the p tags in this table to inputs, but just as important I would need to apply the class from the td to the input as well.
2)retrieve the value from the p tag in the table and place it in the existing form based on the td class (is this possible?).
My jQuery to retrieve and display the data look like this:
jQuery("#bbnuke_retrieve_gamechanger_results_btn_id").bind('click', function() {
var gameID = jQuery("#bbnuke_plugin_gamechanger_import").val();
var pitchLink = 'http://www.gamechanger.io/game-' + gameID + '/boxscore/pitching/standard';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select tbody FROM html where url ="' + pitchLink + '" and xpath="//table[#id=' + "'tbl_home_pitching'" + ']"') + '&format=xml&callback=?';
jQuery.getJSON(yql, cbFunc);
function cbFunc(data) {
if (data.results[0]) {
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
jQuery("#gamesitedump").html(data);
}
else {
jQuery("#gamesitedump").html("Error");
throw new Error('Nothing returned from getJSON.');
}
}
});
Any help is much appreciated!
You could "convert" the <p> into <input> this way :
$("td > p").each(function() {
// creates a new <input> element
$newInput = $("<input type='text'/>");
// find the parent of the current <p>, and applies its class to the new <input>
$newInput.addClass($(this).parent().attr("class"));
// get the value of the current <p>, and set the value of the new <input> to this
$newInput.val($(this).text());
// replace the current <p> element with its <input> equivalent
$(this).replaceWith($newInput);
});
You can find a jsFiddle example here .
Related
I'm new to PHP and Ajax. I am trying to create a table of object data where I can select the displayed data based on a <select><option>... form.
I have a PHTML template which looks like the following:
<?php
$content = "";
// creates data selector
$content .= "
<form id = select_data>
<select id = data_selection>
<option value = data1>Data 1</option>
<option value = data2>Data 2</option>
<option value = data3>Data 3</option>
<option value = data4>Data 4</option>
</select>
<input id = selected_data type=submit />
</form>";
// creates table header
$content .= "
<tr>
<th>Data</th>
</tr>";
$array_ids = array(1, 2, 3); // etc, array of object id's
foreach ($array_ids as $array_id) {
$object = // instantiate object by array_id, pseudocode
$object_data = $object->getData('default-data'); // get default data to display
// create table item for each object
$content .= "
<tr>
<td><p>$object_data</p></td>
</tr>";
}
print $content;
?>
This prints out the table content, loads objects by their id, then gets and displays default data within the <p> tag.
And then I have some Javascript which looks like the following:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){ // get selected data type
e.preventDefault();
var data_selected = $("#data_selection :selected").val(); // create var to pass to ajax
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected},
success: function(data){
$("p").html(data); // replace all <p> tag content with data
}
});
});
});
</script>
This Javascript gets the selected data type, creates a variable out of it to pass on to the ajax which then calls post.php, which looks like the following:
<?php
$attribute = false;
if (isset($_POST['data_selected'])){
$data = $_POST['data_selected']; // assigns variable out of ajax data
$object = //instantiate object, again pseudocode
$object_data = $object->getData($data); // get new data to replace into the ```<p>``` tag
echo $object_data;
}
?>
The problem is that the Javascript that I have changes every single <p> tag to the last data iterated by the foreach loop because each <p> tag is not uniquely identified and the Ajax does not update the data based on a unique identifier, such as maybe the $array_id. Which brings me to my attempted solution.
I tried to identify each <p> tag with the following:
<td><p id = $array_id>$object_data</p></td>
And then creating a new Javascript variable out of the array ID:
var p_tag_id = <?php echo $array_id; ?>;
And finally making the Ajax success function target element ID's based on var p_tag_id:
$("#" + p_tag_id).html(data);
While this does not change all the <p> tags like previously, it only changes the final <p> tag and leaves all instances before it unchanged because the Javascript is not iterating over each <p> tag, or because the foreach loop does not call the Javascript as a function for each $array_id.
How can I rewrite this code so that the Ajax updates the data of each table item uniquely instead of updating them all with the same data? Is there a better way to approach this problem?
You need a way to identify the table row containing the <p> tag you wish to update, and perhaps the value attribute of the SELECT element could help.
You can get the number of the clicked option from your data_selected variable by using slice to strip-off the last character (i.e. the number):
var num = data_selected.slice(-1) - 1;
(Subtract 1 because the table rows are zero-indexed)
Then, in the AJAX code block's success function:
$('table tr').each(function(i,v){
if (i == num){
$(v).find('td').find('p').html(data);
}
});
The above grabs all the table rows (as a collection) and loops through them one-by-one. In the function, i is the index number of the row and v is the row itself. Index numbers begin at zero, which is why you earlier subtracted 1 from the (for eg) data3 [3] value, leaving num == 2. When you find the right row number, use .find() to find the <td> in that row, and then the <p> in that <td> and Bob's yer uncle.
I haven't tested the above code so there could be bugs in the example, but off-the-cuff this approach should work.
I figured out a solution. I assigned the $array_id to each <p> tag after all in order to identify them uniquely:
<td><p id = $array_id>$object_data</p></td>
Then I looped over all the <p> tags and assigned the $array_id of this <p> tag to a variable like so:
$("p").each(function() {
var array_id = $(this).attr("id");
And finally I made the Ajax success target elements based on their ID:
$("#" + array_id ).html(data);
Here is the full Javascript code for anybody who is interested. Hopefully this helps someone else out!
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){
e.preventDefault();
var data_selected = $("#data_selection :selected").val();
$("p").each(function() {
var array_id = $(this).attr("id");
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected, array_id: array_id},
success: function(data){
$("#" + array_id).html(data);
}
});
});
});
});
</script>
Well,
I've been trying to figure this out for quite a while now with absolutely no luck.
Right now, I have an HTML form with jQuery that can dynamically add or remove a charge. This information is then put into a php array and stored into a database.
What I want, is to be able to pull that array from a database, count the entries, and place them into the correct number of input boxes on an HTML form. I would still like jQuery to be used here, as I would like users to be able to add or remove charges in this 'edit' stage.
If it's confusing, please ask questions.
jQuery v
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum)
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
$('input[name="name[]"]:last').val(null);
// enable the "remove" button
$('#btnDel').attr('disabled','');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
HTML v
<tr id="input1" style="margin-bottom:4px;" class="clonedInput">
<td><span style="color:#00CD00;">Charge:</span></td>
<td><input type="text" name="name[]" size="35"/></td>
</tr>
<tr>
<td><input type="button" id="btnAdd" value="Add Another Charge" /></td>
<td><input type="button" id="btnDel" value="Remove Charge" /></td>
</tr>
Also, if you seen any improvements I can use in my code, please do suggest. I am fairly new to using jQuery, and I am wanting to learn as much as I can.
While repopulating the products in jquery is possible, I would try to repopulate them using php within a tag. This is purely to simplify the development. Populating with jquery would require getting the elements in a json feed and based on that, you can possibly re-use the same code you have to re-populate but this time, with a value in the text box.
I have json array return as bellow
{"id":16,"minutes":146}
{"id":17,"minutes":137}
{"id":18,"minutes":123}
{"id":22,"minutes":84}
I'm trying to render above json array inside table tbody td which json array id's equal to td id's and display the minutes inside td tag
for example json id :16 minute:146 and display it in <td id="16">146</td>
<table>
<thead>
<tr>
<th>op</th>
<th>Minutes</th>
</tr>
</thead>
<tbody>
<tr>
<td>op1</td>
<td id="16">0</td>
</tr>
<tr>
<td>op2</td>
<td id="17">0</td>
</tr>
<tr>
<td>op3</td>
<td id="18">0</td>
</tr>
<!--....and goes on -->
</tbody>
</table>
js
$.ajax({ url: statUrl, type: 'POST',
data: {
begin: begin,
end: end
},
success: function(data){
}
});
Your JSON is invalid it should only represent one object, a valid version of what you have will be
[{"id":16,"minutes":146},
{"id":17,"minutes":137},
{"id":18,"minutes":123},
{"id":22,"minutes":84}]
If your data IDs directly correspond to already existing DOM element IDs then it should be rather easy:
for (var i = 0; i < data.length; i++) {
$('#' + data[i].id).text(data[i].minutes);
}
This is using jQuery ofc.
you can use json_decode($json, true) in php to convert the json to an array then loop over it's elements and build your table.
If you want to do it client side, I think you must create table, tr and td elements manually and populate them. ExtJS has ready grid for this.
Server side is easier.
I created a jsFiddle here: http://jsfiddle.net/5pKjW/11/
As Musa stated, the JSON you posted is not valid, it should be an array containing all the objects.
The code following is basically what you need to do inside the success callback, just use data instead of result.
What I do is creating a table, appending a row for every element of the array and then appending the whole table to an element of the DOM.
var result = [{"id":16,"minutes":146},{"id":17,"minutes":137},{"id":18,"minutes":123},{"id":22,"minutes":84}];
var $table = $('<table><thead><tr><th>op</th><th>Minutes</th></tr></thead>'),
$tbody = $('<tbody>').appendTo($table),
i;
for (i = 0; i < result.length; i++){
$tbody.append('<tr><td>op' + (i+1) + '</td><td id="' + result[i].id + '">0</td></tr>');
}
$table.appendTo('#container');
As T.J. Crowder commented, a valid HTML4 id attribute can't start with a digit. If I were you, I would prefix it with a string (<td id="prefix' + result[i].id + '">0</td>).
MrOBrian suggested to use a rendering engine. Maybe for a simple case like this, and if you don't need a rendering engine elsewhere, it's an overkill, but that's absolutely something worth considering, if you need something more complicated in the future.
as suggested fixed json array to
{
"25":72.3833,
"17":116.3167,
"16":25.75,
"34":28.3333,
"29":136.8831,
"19":40.9166,
"32":43.6,
"22":83.9001
}
and js
$.getJSON(statUrl, {begin: begin, end: end}, function(data) {
$.each(data, function(key, val) {
$('#op_' + key).text(Math.ceil(val));//also fixed td id
});
});
so got the result as expected.
thanks for your time.
I am creating a drag and drop system using redips javascript.
This is my script using html and php to generate the data
<div id="base">
<table>
<tbody>
<?php
foreach($deviceID as $row)
{
echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus" value="'.$row['description'].'"></div></td></tr>';
}
?>
</tbody>
</table>
</div>
This is the fragment of my javascript file.
var redips_init;
redips_init = function () {
// reference to the REDIPS.drag
var rd = REDIPS.drag;
// initialization
rd.init();
rd.drop_option = 'shift';
rd.animation_shift = true;
rd.myhandler_dropped = function () {
alert($('#bus').val());
}
};
I am not good with php but what i usually do in jsp is create a local index variable and append it to each of the ID attribute in the loop.
So your code would look something like this
<?php
$index=0;
foreach($deviceID as $row)
{
echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus'.$index++.'" value="'.$row['description'].'"></div></td></tr>';
}
?>
In javascript, your dragAndDrop event should return an index location by which u can get appropriate value.
Now you can use this dynamic ID in your JavaScript to do whatever you want to do.
REDIPS.drag contains save_content() method to scan all DIV elements in a table and to return the result as Query string or JSON object. Input parameters are table id and type of returned result (default is query string). If this is not good enough, you can search for save_content() source and make customization. Method is simple and it uses several loops to scan table content.
On the other hand, if you need to know ID of dropped DIV element that can be written inside myhandler_dropped event hander. Here is code snippet:
rd.myhandler_dropped = function () {
// define DIV id
var id = rd.obj.id;
// write DIV id to the console
console.log(id)
};
Hope this answer will be helpful.
Using some code to create a form dynamically which I got here: http://www.trans4mind.com/personal_development/JavaScript2/createSelectDynamically.htm
This works great. However I have a regular html table I generate with html/php to get data out of a DB. I want to replace that data with a form so when users click the edit button the original entry is replaced with a form (either textbox or pull down menu). The user makes a selection and the new table comes back with the appropriate edit.
So for example one part of the data has this in the table:
<td><?php echo $result[0] ?></td>
Using the link about to create a form dynamically I change this to:
<td id="paraID"><form id="form1" name="form1" method="post" action enctype="text/plain" alt=""><?php echo $result[0] ?></form></td>
Also note the onclick event for the edit button:
This is hard to explain but hoping someone can help me with this interaction. I need some way to say:
if (user clicks edit button)
then
replace html table with form for each entry (for example, the table returns a name called foo and a textbox will appear with foo in it but now they can edit to change the name).
If you can start out with an id for the td then it will make things easier. Then you will need an edit button somewhere. Notice: It might be nice to replace "result_0" with the name for the value/field:
<td id="result_0_parent"><?php echo $result[0] ?><input type="button" onClick="editField('result_0','select')" value="Edit" /></td>
Then in your javascript you will have the editField function defined so that it sets the content of the td to be the dynamic form. Looking at makeForm function in the example javascript, you see this happening with appendChild(myform); The function editField will be like the makeForm function except you will pass in the field_id and field_type as parameters:
function editField(field_id, field_type)
I suggest you change the line that defines mypara to define mytd or better yet, field_parent instead since in your case it will not be a paragraph element, but a td (or possibly some other type of element):
field_parent = document.getElementById(field_id+"_parent");
The example code create a select (dropdown), but I am guessing you want to create other field input types so I recommended having field_type as a second parameter to the function. This means that it would make more sense for your implementation to use myfield instead of myselect and then use the field_type parameter to decide what myfield will be.
Replace the line in the makeForm / editField function:
myselect.setAttribute("id","selectID");
with
myfield.setAttribute("id",field_id);
One more thing: To set the initial value of the input field to be the displayed content, you will need to copy the "innerHTML" of the "parent" element. So place something like this right after defining field_parent:
initial_value = field_parent.innerHTML;
and I think you can figure out the rest. If not, I can elaborate a little more.
This works great. However I have a regular html table I generate with
html/php to get data out of a DB. I want to replace that data with a
form so when users click the edit button the original entry is
replaced with a form (either textbox or pull down menu). The user
makes a selection and the new table comes back with the appropriate
edit.
This is a script that allows with a double click on values to edit them and has a button to send them back. Maybe it would be of some help to use it (or use parts of it).
<?PHP
if(count($_POST)>0)
{
echo 'You gave:<br><per>';
print_r($_POST);
echo '<a href=http://localhost/temp/run.php>Start over</a>';
exit;
}
?>
<html>
<head>
<script type="text/javascript">
/**formEditor Class
*/
function formEditorCls( )
{
/**
Constructor simulator
*/
this.lastFieldEditedId = null;
/** Change span with input box, hide the eddit button and store theses IDS
*/
this.edit=
function (field)
{
//if there was a field edited previously
if(this.lastFieldEditedId != null)
this.save();
//get the inner element of the div, it can be span or input text
var childElem = document.getElementById(field).getElementsByTagName('*')[0];
//then replace the span element with a input element
document.getElementById(field).innerHTML="<input type=text name=n_"+field+
" id=id_"+field+" value="+childElem.innerText+">";
//store what was the last field edited
this.lastFieldEditedId =field;
}//func
this.save=
function ()
{
dbq="\"";sq='\'';
//get the last value
var lastValue = document.getElementById(this.lastFieldEditedId).
getElementsByTagName('*')[0].value;
//store it as span
document.getElementById(this.lastFieldEditedId).innerHTML="<span ondblclick="+dbq+
"formEditor.edit("+sq+this.lastFieldEditedId+sq+");"+dbq+" >"+lastValue+"</span>" ;
//now must reset the class field attribute
this.lastFieldEditedId=null;
}//func
this.submit=
function (path)
{
this.save();//if ay field was edited put new values in span elements
var form = document.createElement("form");//create a new form
form.setAttribute("method", "post");
form.setAttribute("action", path);
var myDiv = document.getElementById( "fieldsDiv" );//get the div that contains the fields
var inputArr = myDiv.getElementsByTagName( "SPAN" );//get all span elements in an array
//for each span element
for (var i = 0; i < inputArr.length; i++)
{
var hiddenField = document.createElement("input");//create an input elemet
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", i);
hiddenField.setAttribute("value", inputArr[i].innerText);
form.appendChild(hiddenField);//append the input element
}
document.body.appendChild(form);//append the form
form.submit();//submit the form
}//func
}//class
formEditor = new formEditorCls( );
</script>
</head>
<body onclick="rt();">
Double click any value to change it..<br><br>
<div id="fieldsDiv">
Name:<font id="nameField">
<span ondblclick="formEditor.edit('nameField');" >Mark</span>
</font><br>
Surname:<font id="surnameField" >
<span ondblclick="formEditor.edit('surnameField');">Smith</span>
</font><br>
</div>
<input type=submit name="submit"
onclick="formEditor.submit('http://localhost/temp/run.php');" value="Submit">
</body>
</html>