Hi I have been playing around with jqtouch today and I'm just wondering how to manage data.
I tried looking around but couldn't see much documentation.
If I had a list of links for say products? And I click on one i can navigate to the product 'view'. How to I pass variables like you would a $_GET variable to select THAT product?
Or even if I set the id of the link to the id of the record and use JS to grab the ID and somehow pass it to the next view?
Any help with this would be most appreciated!
NOTE: I also want to use it with the offline extension so I'm not sure get ajax would work
Regards,
Billy
You can use the referrer property for the data object. The link would look like:
Product #1
where the HTML ID would correspond to the product ID. Then in the "pageAnimationEnd" event you can retrieve the product details like this:
$('#view').bind('pageAnimationEnd', function (e, info) {
// get the id of the calling href
var id = $(this).data('referrer')[0].id;
$.getJSON('/products/' + id, function (data) {
// do something with the data
});
});
You could look at the demo to see how it does form submission, i.e. AJAX > POST Form Example. Essentially, you create a form and a jQT-style submit button:
<form id="ajax_demo" action="ajax_demo.php" method="POST" class="form">
...
<a class="submit whiteButton" href="#">Submit</a>
</form>
Then in your receiving page (i.e. ajax_demo.php), you can access the form fields, e.g. PHP's $_GET or JavaScript's location.search.
Another way is to store the data in the DOM with jQuery:
// in global level
$('body').data('ajax_demo', "some data for the page");
// in page/view level
$('#ajax_demo').data('key', 'value');
Related
I am making a page with soccer teams and leauges. Now i`m printing all Leagues that i want from the database.
League 1
League 2
League 3
etc.
As you can see each League has its own League_ID. In Database i also have a table of all teams, and each team has matched League (with League_ID). I also have a view, where i can print table of League that i want. This function in php looks like this.
public function leauge_table(){
$tables = $this->scoreTableRepository
->getScoreTable(1);
//TODO how to change this "1" static to generated
//TODO when pressing link
return $this->render('leauge_table', ['table' => $tables]);
And as you can see, when i go to this page i will always see the score table from leauge that has id=1.
And the question is how can i make that when i press for example at "League 2" i will open page but with table matching to League_ID = 2. Shall it be <button></button> or <a></a> in HTML. And how to pass there League_ID so my php back will see which table should render.
Thank you really for help.
PS
Or maybe do i have to make a seperate view for each leauge score table? And then just simply make buttons direct to these views with simple JS code. But would like to avoid it if it`s possible.
It can be a link or a button. A link with the league ID as a parameter in the URL is the simplest approach though, if you're new to the concept. e.g.
League 1
The ID would then be available in the php script via $_GET["id], once the link is clicked.
In your SoccerTeam page add a button in a form with the following :
<form action="youpage.php" method="post">
<input name="leagueId" type="hidden" value="<?php echo $leagueId;?>" >
</form>
And in order to process that information, since we passed an id, we can retrieve it with $_POST['leagueId'] and because it's a POST request it wont be visible in the url:
$leagueId = $_POST['leagueId'];
OK. I know this has been tackled many times but I can't find an answer with a useful example of javascript to use.
Say I have this form:
class MyForm(Form):
category = SelectField("Category")
issue = SelectField("Issue")
What I need is for whatever is selected in 'category' at runtime to determine what the user sees in the issue dropdown without a POST of any kind ocurring. I know how to dynamically create the choices in the view from my database query. I even have gone so far as to create a dictionary of "issue choices" based off of category choices.
I just can't for the life of me figure out the javascript I need so that on select of something from the category drop down determines whats in the issue dropdown.
I found the info I needed by looking at the example at Flask jQuery AJAX Example -
- it is a minimal working example, almost a
GIST or a book chapter.
I came up with an example very close to jsbueno's implementation. You can find the Gist here. The .py file is a standalone example.
In your html template use jquery to register an ajax request when you click the select field. If the request is a success the html for the select field gets updated with the new select options (send as a response from the server). Look at the actual HTML generated by the template to see how the select field looks like.
<form action="" method="post" id="selectDevice" name="device">
Nummber of Devices: {{ form.selectAmount(size=1) }}
Select device: {{form.deviceAddress() }}
</form>
<script type="text/javascript" charset="utf-8">
$("#deviceAddress").click(function(){
$.ajax({
url: '/selectform',
type: 'POST',
data: $('#selectDevice').serialize(),
success: function(selectOptions){
$("#deviceAddress").empty();
for (var i = 0; i < selectOptions.length; i++){
$("#deviceAddress").append(
$("<option></option>")
.attr("value", selectOptions[i][0])
.text(selectOptions[i][1])
);
}
}
});
});
</script>
On the server side, use a route for the ajax post request.`As example this route changes the options depending on another form field (the information got send over with the data tag in the ajax request). In WTForms the select field options is a list of tuples containing an ID and name, I kept this the same on the python side.
#app.route('/selectform', methods=['POST'])
def updateselect():
deviceAmount = int(request.form.get('selectAmount'))
choices = [('device{}'.format(i), i) for i in range(deviceAmount)]
response = make_response(json.dumps(choices))
response.content_type = 'application/jsons'
return response`
Only one remark: the ajax request is performed on dropping down and on collapsing. The last part is not necessary of course, there is probably a way to structure the jquery so it only requests on dropdown.
So let us say i have a form with id #form which has two input fields, namely title & price.
I click on the Edit button somewhere in the application which has data attributes (e.g data-title="Apple" data-price="10")that are to be assigned to the #form upon clicking the button.
the obvious solution that works is
$("#name").val($(this).data('name'));
$("#price").val($(this).data('price'));
This obviously looks bad when you have too many fields. So I am trying to get something like this to work $('#form').data($(this).data());, more or less in a single like
Have tried this many ways with no success
Any help is appreciated
You could create a jquery plugin that you can call from the element that contains the data points and have it apply the data based on the key to elements within the form of that same name. Example below
$.fn.applyData = function(form) {
$form = $(form);
$.each($(this).data(), function(i, key) {
$form.find('#' + i).val(key);
});
};
JSFiddle: http://jsfiddle.net/LCM8S/43/
So I am trying to get a user's first name so that I can display it on my chatting app. I have the user's information. I can get the user by playing around with res.render(). In jade I can do something like #{user.firstName} to have it printed out but I am not sure how I can use this data in jQuery.
Check if you can build an element as follwed:
case 1
<input id='user-first_name' type='hidden' value='#{user.firstName}' />
// Then you can use the value of input field as.
var firstName = $('#user-first_name').val()
case 2
you can directly write a script tag where you will initialize some window variables as :
<script>
window.user_first_name = #{user.firstName}
</script>
case 3
Also you can try assigning that value to data field of any html element(html tag) as followed :
<element data-first_name='#{user.firstName}'>
// Now you can use a jquery selector for selecting that element and you
// will be able to retrieve that value using data function
var firstName = $(element_selector).data('first_name');
I'm trying to retrieve a list of users from a simple MySQL database table, e.g., called TableA, which looks something like: Username(varchar), Level(tinyint), DateCreated(datetime).
On an html page I have a search input box, say - and underneath it I have a div, say to display the results. I have it so that when I start typing a word (to look for a username), jQuery makes makes an ajax request to a php file which queries the TableA for the usernames.
The jQuery part looks like:
$("#search_bar").keyup(function()
{
var user = $(this).val();
$.post('get_user.php', user_name : user, function(data)
{
$("#result_box").html();
});
}
The php script, get_user.php, again is a simple script which looks something like
<?php
$user = $_POST['user_name'];
//connect db,
$query = mysqli_query (select Username from TableA where Username like '$user%');
//IMPORTANT PART HERE, I create a <DIV> or can be <P> and display it back
while ($row = mysqli_fetch_array($query))
{
echo "<div id="user_info" username='".$row['Username']."'>".$row['Username']."</div>
//I have the username as an attribute so I can make another .post request and get detailed user info.
}
?>
Now, previously using jQuery, every result that is being returned as a is being dumped in the result_box div ($("#result_box").html();). The problem I have with this is that if I have 3 users, say Mick, Mike and Mila and I start searching by typing 'M', the query returns all three (that's fine), however, when I click on a name, say the last one returned would be Mila, this will trigger another jQuery function which say for now just prints the name of the selected in a popup box - it however picks up the attribute of the first name, Mick, from the the first div that appeared there and not the one I clicked on. It's strange. If the search returns only a single entry then that's fine - however with multiple entries, regardless of which one I click, jQuery picks up only the first one.
I suspect its because the divs all have the same ID, and since they are being 'dynamically' created - jQuery just picks up the attribute (e.g., $("#user_info").attr('username') ) of the very first one or only one created?
Any help would be appreciated.
Thanks
You should use jQuery data()
You should create the div like :
<div class="userLink" data-username="$row['username']"></div>
And acces it from jQuery like
$('.userLink').on('click',function(e) {
var username = $(this).data('username');
}
And the attribute ID must be UNIQUE.
First off, you need to fix the issue of multiple DOM objects with the same id. Perhaps you can just use a class name. But, that probably won't fix your click issue. The click issue should be fixed by using the this reference that comes with the click event. This will tell you exactly which items was clicked on so even if there are multiple items, you can know which one was clicked on and can reference the attributes on that particular object with code like this:
$(this).attr("username");
FYI, you perhaps should use the HTML5 convention of data attributes. So, instead of an attribute of username="xxx", you would use data-username="xxx". Then, you can use:
$(this).data("username");
You can combine all these changes with delegated event handling to have a click handler like this:
Your PHP (switch to a class name and data-username attribute):
//IMPORTANT PART HERE, I create a <DIV> or can be <P> and display it back
while ($row = mysqli_fetch_array($query))
{
echo "<div class="userInfo" data-username='".$row['Username']."'>".$row['Username']."</div>
//I have the username as an attribute so I can make another .post request and get detailed user info.
}
Your delegated event handling click handler in the page:
$("#result_box").on("click", ".userInfo", function(e) {
var username = $(this).data("username");
});