Seaside: list losing its content on update - ajax

This one is really simple. I've got a <select> and I want to update some internal state based on the selection. No need to redisplay anything. The problem is that after the selection and the AJAX request have been made, the list loses its contents.
renderContentOn: html
|value myId|
html form with: [
html select list: #('one' 'two' 'tree' 'four' 'five');
id: (myId := html nextId);
callback: [ :v | value := myId ];
onChange: (
html prototype updater
triggerFormElement: myId;
callback: [:h | value "do something with the value here"];
return: false
).
]

The #updater needs an DOM ID of the element to update. If you fail to provide an ID, it default to this, the DOM element triggering the event. Thus, you end up with an empty list. If you do not need to update something you should use #request instead of #updater. If you want to update something you need to provide a valid ID using #id:.
Read the section AJAX: Talking back to the Server of the Seaside Book, it explains AJAX in great detail.

Because the updater replaces the html of the element it was defined on with the content generated by the callback and your callback does not generate any html, the list is empty, I think.

Related

Rebol shift-tab side effects

Given this:
view layout [ field [print "1" ] field [print "2"] ]
When I shift+tab from field #2 to field #1, no actions are fired.
How do I get them to fire just like a normal tab?
It is a bug in the key handler for field style in the Rebol/View engine. Here is a quick patch you can include in your code to fix it and make SHIFT+Tab work:
use [body f pos][
;-- patch `ctx-text/back-field` function to fix the bug
body: copy/deep second f: get in ctx-text 'back-field
insert body/2/while [if head? item [item: tail item]]
ctx-text/back-field: func first :f :body
;-- remove test that disables face/action for back-tabs
body: second get in ctx-text 'edit-text
body: find body 'word?
pos: at body/3/7/tab-char/5/6 11
change/part pos pos/4 4
]
This code will walk through View engine functions at run-time (code is data in Rebol) and hot-patch the functions bodies, by injecting or removing code where required.
If you happen to be a Rebol/SDK user, I can give you the instructions for patching the source files directly, so you can encap a fixed View executable.
Enjoy.

three dependent drop down list opencart

I want to make 3 dependents drop down list, each drop down dependent to the previous drop down, so when I select an item from first drop down , all data fetch from database and add to second drop down as item.
I know how to do this in a normal php page using ajax, but as opencart uses MVC I don't know how can I get the selected value
Basically, you need two things:
(1) Handling list changes
Add an event handler to each list that gets its selected value when it changes (the part that you already know), detailed tutorial here in case someone needed it
Just a suggestion (for code optimization), instead of associating a separate JS function to each list and repeating the code, you can write the function once, pass it the ID of the changing list along with the ID of the depending list and use it anywhere.
Your HTML should look like
<select id="list1" onchange="populateList('list1', 'list2')">
...
</select>
<select id="list2" onchange="populateList('list2', 'list3')">
...
</select>
<select id="list3">
...
</select>
and your JS
function populateList(listID, depListID)
{
// get the value of the changed list thorugh fetching the elment with ID "listID"
var listValue = ...
// get the values to be set in the depending list through AJAX
var depListValues = ...
// populate the depending list (element with ID "depListID")
}
(2) Populating the depending list
Send the value through AJAX to the appropriate PHP function and get the values back to update the depending list (the part you are asking for), AJAX detailed tutorial here
open cart uses the front controller design patter for routing, the URL always looks like: bla bla bla.bla/index.php?route=x/y/z&other parameters, x = folder name that contains a set of class files, y = file name that contains a specific class, z = the function to be called in that class (if omitted, index() will be called)
So the answer for your question is:
(Step 1) Use the following URL in your AJAX request:
index.php?route=common/home/populateList
(Step 2) Open the file <OC_ROOT>/catalog/controller/common/home.php , you will find class ControllerCommonHome, add a new function with the name populateList and add your logic there
(Step 3) To use the database object, I answered that previously here
Note: if you are at the admin side, there is a security token that MUST be present in all links along with the route, use that URL:
index.php?route=common/home/populateList&token=<?php echo $this->session->data['token'] ?> and manipulate the file at the admin folder not the catalog
P.S: Whenever the user changes the selected value in list # i, you should update options in list # i + 1 and reset all the following lists list # i + 2, list # i + 3 ..., so in your case you should always reset the third list when the first list value is changed
P.P.S: A very good guide for OC 1.5.x => here (It can also be used as a reference for OC 2.x with some modifications)

WordPress Pagination not working with AJAX

I'm loading some posts though AJAX and my WordPress pagination is using the following function to calculate paging:
get_pagenum_link($paged - 1)
The issue is that the pagination is getting created through AJAX so it's making this link look like: http://localhost:1234/vendor_new/wp-admin/admin-ajax.php
However the actual URL that I'm trying to achieve is for this:
http://localhost:1234/vendor_new/display-vendor-results
Is there a way to use this function with AJAX and still get the correct URL for paging?
I can think of three options for you:
To write your own version of get_pagenum_link() that would allow you to specify the base URL
To overwrite the $_SERVER['REQUEST_URI'] variable while you call get_pagenum_link()
To call the paginate_links() function, return the whole pagination's HTML and then process that with JS to only take the prev/next links.
#1 Custom version of get_pagenum_link()
Pros: you would have to change a small amount of your current code - basically just change the name of the function you're calling and pass an extra argument.
Cons: if the function changes in the future(unlikely, but possible), you'd have to adjust your function as well.
I will only post the relevant code of the custom function - you can assume everything else can be left the way it's in the core version.
function my_get_pagenum_link( $pagenum = 1, $escape = true, $base = null ) {
global $wp_rewrite;
$pagenum = (int) $pagenum;
$request = $base ? remove_query_arg( 'paged', $base ) : remove_query_arg( 'paged' );
So in this case, we have one more argument that allows us to specify a base URL - it would be up to you to either hard-code the URL(not a good idea), or dynamically generate it. Here's how your code that handles the AJAX request would change:
my_get_pagenum_link( $paged - 1, true, 'http://localhost:1234/vendor_new/display-vendor-results' );
And that's about it for this solution.
#2 overwrite the $_SERVER['REQUEST_URI'] variable
Pros: Rather easy to implement, should be future-proof.
Cons: Might have side effects(in theory it shouldn't, but you never know); you might have to edit your JS code.
You can overwrite it with a value that you get on the back-end, or with a value that you pass with your AJAX request(so in your AJAX request, you can have a parameter for instance base that would be something like window.location.pathname + window.location.search). Difference is that in the second case, your JS would work from any page(if in the future you end-up having multiple locations use the same AJAX handler).
I will post the code that overwrites the variable and then restores it.
// Static base - making it dynamic is highly recommended
$base = '/vendor_new/display-vendor-results';
$orig_req_uri = $_SERVER['REQUEST_URI'];
// Overwrite the REQUEST_URI variable
$_SERVER['REQUEST_URI'] = $base;
// Get the pagination link
get_pagenum_link( $paged - 1 );
// Restore the original REQUEST_URI - in case anything else would resort on it
$_SERVER['REQUEST_URI'] = $orig_req_uri;
What happens here is that we simply override the REQUEST_URI variable with our own - this way we fool the add_query_arg function into thinking, that we're on the /vendor_new/display-vendor-results page and not on /wp-admin/admin-ajax.php
#3 Use paginate_links() and manipulate the HTML with JS
Pros: Can't really think of any at the moment.
Cons: You would have to adjust both your PHP and your JavaScript code.
Here is the idea: you use paginate_links() with it's arguments to create all of the pagination links(well - at least four of them - prev/next and first/last). Then you pass all of that HTML as an argument in your response(if you're using JSON - or as part of the response if you're just returning the HTML).
PHP code:
global $wp_rewrite, $wp_query;
// Again - hard coded, you should make it dynamic though
$base = trailingslashit( 'http://localhost:1234/vendor_new/display-vendor-results' ) . "{$wp_rewrite->pagination_base}/%#%/";
$html = '<div class="mypagination">' . paginate_links( array(
'base' => $base,
'format' => '?paged=%#%',
'current' => max( 1, $paged ),
'total' => $wp_query->max_num_pages,
'mid_size' => 0,
'end_size' => 1,
) ) . '</div>';
JS code(it's supposed to be inside of your AJAX success callback):
// the html variable is supposed to hold the AJAX response
// either just the pagination or the whole response
jQuery( html ).find('.mypagination > *:not(.page-numbers.next,.page-numbers.prev)').remove();
What happens here is that we find all elements that are inside the <div class="mypagination">, except the prev/next links and we remove them.
To wrap it up:
The easiest solution is probably #2, but if someone for some reason needs to know that the current page is admin-ajax.php while you are generating the links, then you might have an issue. The chances are that no one would even notice, since it would be your code that is running and any functions that could be attached to filters should also think that they are on the page you need(otherwise they might mess something up).
PS: If it was up to me, I was going to always use the paginate_links() function and display the page numbers on the front-end. I would then use the same function to generate the updated HTML in the AJAX handler.
This is actually hard to answer without specific details of what and how is being called. I bet you want to implement that in some kind of endless-sroll website, right?
Your best bet is to get via AJAX the paginated page itself, and grab the related markup.
Assume you have a post http://www.yourdomain.com/post-1/
I guess you want to grab the pagination of the next page, therefore you need something like this:
$( "#pagination" ).load( "http://www.yourdomain.com/post-1/page/2 #pagination" );
This can easily work with get_next_posts_link() instead of get_pagenum_link().
Now, in order for your AJAX call to be dynamic, you could something like:
$( "#pagination" ).load( $("#pagination a").attr('href') + " #pagination" );
This will grab the next page's link from your current page, and load its pagination markup in place of the old.
It's also doable with get_pagenum_link() however you'd need to change the $("#pagination a").attr('href') selector appropriately, in order to get the next page (since you'd have more than one a elements inside #pagination

Selecting Ajax Dropdown suggestion list using Selenium for Firefox

How can i select Ajax Dropdown suggestion list item using selenium code for firefox??
My problem is :the Ajax dropdown list is visible but it is not selected and next steps gets stuck.
May be selenium is waiting for something.
the list that page populates is dynamic and in bla bla tags.
Please help with a example code.
How can i use waitfor* here.
Remember i am not using firefox ide but i am writing a code.
Please help.
I had a similar problem whereby, selenium was able to find the dropdown menu but was unable to click on the visible text. I later found out that there was an Ajax call that was populating the dropdown menu data and as a result selenium seemed to not be able to select the intended visible text because the list items had not been fully populated. That is, by the time the script was selecting my option value, Ajax had not completely loaded the menu options. Here's my solution:
public void nameOfCollegeList(String optionItem) {
// declare the dropdownMenu web element
WebElement dropDownMenu = driver.findElement(By.cssSelector("#CollegeNames"));
// click on the dropdownMenu element to initiate Ajax call
dropDownMenu.click();
// keep checking the drop down menu item list until you find the desired text that indicates that the menu has
// been fully loaded. In this example I always expect "Other (please specify)" to be the last item in the drop down menu.
// If I don't find the expected last item in the list in my if condition, execute the else condition by calling the
// same method(recursively). Please note that if the "if" statement is never satisfied then you'll end up with an
// infinite loop.
if (dropDownMenu.getText().contains("Other (please specify)")) {
new Select(dropDownMenu).selectByVisibleText(optionItem);
}
else {
nameOfCollegeList(optionItem);
}
}
i am little confused with your question at " :the Ajax dropdown list is visible but it is not selected "
this sounds like that the element is disabled. (Java coding)
if so selenium.isElementDisabled()
if not then,
1) programming laguage solution using while loop and isElementPresent() OR isElementDisabled()
//trigger the Ajax request and then
long initialTime = System.currentTimeMillis();
do{
thread.sleep(1000);
}while((!selenium.isElementPresent("AjaxElement")) && (System.getCurrentTimeMillis() - initialTime <= 5000)) ;
//some thing like above for client programming solution...but for,
2) selenium's inbuilt solution
we have a method called waitForCondition("java script to be executed", "time out value");
this method loops the javascript statement until it returns true or the supplied time out occurs
here the important thing is analyzing the application/Ajax element to find out which particular condition of the element changes.
from your explation my guess is this, display=none will be changed to display=block OR
disabled=true will be changed to disabled=false OR isReadOnly will be changed to no such attribute ect.....(you need to figure out this)
and then, use this attribute = value to build a javascript function as ,
selenium.waitForCondition("window.document.getElementById('AJAX ELEMENT').disabled == 'false'", "3000");
you can work out the above statement however you want in your programming language.
try {
//do the action which triggers the Ajax call
selenium.waitForCondition("window.document.getElementById('AJAX ELEMENT[drop down element]').disabled == 'false'", "3000");
//OR
selenium.waitForCondition("window.document.getElementById('AJAX ELEMENT').disabled == 'false'", "3000");
}
catch(SeleniumException se)
{
if((se.getMessage()).toLowerCase().contains("timed out")
throw //..some a custom exception however your organisation requires
}
selenium.select("drop down element id", "option id");
and so on.....

Extract part of HTML document in jQuery

I want to make an AJAX call to an HTML-returning page, extract part of the HTML (using jQuery selectors), and then use that part in my jQuery-based JavaScript.
The AJAX retrieval is pretty simple. This gives me the entire HTML document in the "data" parameter of the callback function.
What I don't understand is how to handle that data in a useful way. I'd like to wrap it in a new jQuery object and then use a selector (via find() I believe) to get just the part I want. Once I have that I'll be passing it off to another JavaScript object for insertion into my document. (This delegation is why I'm not using jQuery.load() in the first place).
The get() examples I see all seem to be variations on this:
$('.result').html(data);
...which, if I understand it correctly, inserts the entire returned document into the selected element. Not only is that suspicious (doesn't this insert the <head> etc?) but it's too coarse for what I want.
Suggestions on alternate ways to do this are most welcome.
You can use your standard selector syntax, and pass in the data as the context for the selector. The second parameter, data in this case, is our context.
$.post("getstuff.php", function(data){
var mainDiv = $("#mainDiv", data); // finds <div id='mainDiv'>...</div>
}, "html");
This is equivalent to doing:
$(data).find("#mainDiv");
Depending on how you're planning on using this, $.load() may be a better route to take, as it allows both a URL and a selector to filter the resulting data, which is passed directly into the element the method was called on:
$("#mylocaldiv").load("getstuff.php #mainDiv");
This would load the contents of <div id='mainDiv'>...</div> in getstuff.php into our local page element <div id='mylocaldiv'>...</div>.
You could create a div and then put the HTML in that, like this…
var div = $("<div>").html(data);
...and then filter the data like this…
var content = $("#content", div.get(0));
…and then use that.
This may look dangerous as you're creating an element and putting arbitrary HTML into it, but it's not: anything dangerous (like a script tag) will only be executed when it's inserted into the document. Here, we insert the data into an element, but that element is never put into the document; only if we insert content into the document would anything be inserted, and even then, only anything in content would be inserted.
You can use load on a new element, and pass that to a function:
function handle(element){
$(element).appendTo('body');
}
$(function(){
var div = $('<div/>');
div.load('/help a', function(){handle(div);});
});
Example: http://jsbin.com/ubeyu/2
You may want to look at the dataFilter() parameter of the $.ajax method. It lets you do operations on the results before they are passed out.
jQuery.ajax
You can do the thing this way
$.get(
url,
{
data : data
},
function (response) {
var page_content = $('.page-content',response).get(0);
console.log(page_content);
}
)
Here in the console.log you will see the inner HTML of the expected/desired portion from the response. Then you can use it as your wish

Resources