I am trying to develop a form in Joomla. The basic problem is:
How can I alter the form select options depending on what the user has chosen before? I need to make several database requests, while the user fills the form. With AJAX, I will need a processing PHP file. Can someone tell me how to do this in Joomla, because with JCE File browser I can't add any.
Thank You!
Assuming you already know how to write a "normal" Joomla component that retrieves data from database and shows them in a page, here's the proposed solution.
In my example I will dynamically retrieve a list of "products" for the selected "category".
COMPONENT: the server part of the Ajax request
Let's say we use JSON to exchange data in the Ajax call.
Within every Joomla component, you can create a JSON view, creating a file view.json.php alongside the default view.html.php. That view will be used when you add "format=json" to your query string.
So you create these additional views that use the same model to get data, but output them as a JSON string. The JSON view is usually something very simple, like this:
public function display()
{
$this->products = $this->getModel()->getProducts();
echo json_encode($this->products);
}
You also need to add the "tmpl=component" so that the response only contains data from the component and not the rest of the Joomla page (like modules and such).
You should end up in a situation where you can put in the browser:
http://yoursite/index.php?option=mycomponent&view=products&format=json&tmpl=component
and you will get a JSON list of products.
Add filters to your request
Of course you only want products for the selected category so you should modify your "getProducts" model method to check for a querystring parameter like category=xyz.
The URL becomes
http://yoursite/index.php?option=mycomponent&view=products&category=1&format=json&tmpl=component
P.S. a more detailed discussion on how to implement the check is off topic, because it's not related to AJAX.
JQUERY: the client part of the AJAX request
Now that you have a component that accept requests via URL and provide a JSON response you can use jQuery to get new data each time the "category" select is changed:
var category_select = $('#category');
var product_select = $('#product');
var request = jQuery.ajax({
"url": 'index.php?option=mycomponents&view=products&tmpl=component&format=json&category=' + category_select.val()
"type": "GET"
}).done(function (result) {
result.each(function (product) {
var new_option = jQuery('<option/>', {
'value': product.id,
})
.text(product.name)
.appendTo(product_select);
});
})
This JS code should be added in the same page where you show your form.
Related
I'm migrating an old MS-DOS Foxpro program to cakePHP, but in some part of the application process the user will have the possibility to load a text file and process it according to some business logic.
I worked the algorithm, and it's working fine, I programmed it in plain PHP.
But in some parts of the process the user must interact performing some tasks, in plain PHP it's possible to do it.
My question is:
How can I have an interactive file process on a MVC framework, since the controller had processed the data when it`s give the control to the view.?
jQuery-ajax could help?
What do you think?
Regards
Update
As Borislav Sabev pointed, I do this:
Create a file upload using using: jQuery Form Plugin
A PHP file parsing according the data structure on the uploaded file that returns to the client the parsed contents of the file in JSON.
Then the JSON data is sent for processing via ajax POST
$.each(data, function (i, fb) {
callAJAX(fb);
});
callAJAX just send the POST request
function callAJAX(fb){
$.ajax({
type: 'POST',
url: "proc.php",
dataType:"json",
complete: function(r,st){
},
success: function(r,st){
processError(r);
})
},
async: false
});
}
If there is a translation error, the PHP returns to the client an error message via JSON.
function proccessError(r)
{
$.each(r,function(i,d){
if (d['error'] == 1){
$.alert('Material not found in translation table','Error');
}
})
}
Now the big question:
When I open the $.alert dialog I want the user select the correct material via an autocomplete, but the code is no waiting for the user selection and pops another $.alert window. How can I tell jquery to wait to the user input an then continue with the processing?
BTW: this is the $.alert extension that I use:
$.extend({ alert: function (message, title) {
$("<div></div>").dialog( {
buttons: { "Ok": function () { $(this).dialog("close"); } },
close: function (event, ui) { $(this).remove(); },
resizable: false,
title: title,
modal: true
}).text(message)
.parents(".ui-dialog:eq(0)").wrap('<div class="error-w"></div>');
}
});
What #AD7six told you is completely right however your question is very vague.
What you seem to need is to provide an interactive (realtime?) way for a user to edit data after a files has been uploaded and processed?. If it is 'data arranged in rows' I can suggest some DataGrid - imagine this as a Web representation of your file's structure.
What you're trying to say with 'the view shows the result of a method or action on the controller' is that this case is in the normal HTTP (with MVC) flow:
Browser (user) initiates a request => Request is processed my Controller => Model is called (gets, saves or manipulates data) => Data is returned to Controller => Controller handles the data over to the View layer => The view layer renders, Controller returns the Response (the rendered view)
In order to do this thing interactively you will have to use AJAX (I propose AJAJ).
The overall paradigm in this case is that the above flow is iterated on every AJAX request. You can achieve this in many ways:
Use plain JavaScript and XMLHttpRequest
Use jQuery's XMLHttpRequest wrapper functions ($.ajax(), $.post(), $.get(), $.load(), etc.)
Some other JS lib's AJAX capabilities (MooTools for example)
Use an real-time JS app framework
This also heavily depends on the browsers (and versions) you need to support.
You will need to provide 'access' for the client-side via a controller or a full API. The best solution for an API would be REST. If this is an enterprise app I suggest you adhere to the Richardson Maturity Model.
If you don't need a fully-realtime app I'd go with jQuery AJAX or some other JS lib's AJAX.
The thing is that what you request as an answer is an overall explanation and that is why I am not going to provide code examples.
Cake has JSON views that you can use to return data.
The other option is an empty layout and a view that returns JSON encoded data like:
<?php echo json_encode($data);?>
Hope this helps. If anything ask.
I'm developing a web app using Kohana PHP framework and I got stuck. I set a PHP variable in my Controller to use it in a View. I would like to update this variable in the View continuously without refreshing the page. What I'd like to do is show a chart in real time using data from an SQL database where the curves' data is stored in this PHP variable. How can I do this? Is it possible to update this variable directly in the View (using my function in the Model)?
You can create an AJAX request with Javascript to your application without reloading the page. What happens is that the request is made to your controller/action, there you can query your database and you can pass back whatever your like. The AJAX request can retrieve the returning data and do something with it (in our case, replace some content with the new content).
You have to include this Javascript code on your page. In this example I use jQuery to make the AJAX request:
$.ajax({
url: /do/something /* URL of your controller/action */
success: function(data) { /* the data variable will receive the new content from the controller/action */
$('#the_id_of_your_html_tag').html(data); /* replace the html content with the new data */
},
});
In your Kohana controller you have something like this:
class Controller_Do extends Controller_Template
{
public function action_something()
{
$this->auto_render = false;
// make some call to your database, use your model whatever
echo 'some string or variable';
return;
}
}
Your Html of your view will be like this (according to the example):
<div id="the_id_of_your_html_tag">something</div>
I am reading a rss feed with php and creating html DOM from the same. Now I have a bunch of <li>'s with news feed. when a user clicks on a particular <li> I want to post certain data to another php file which performs some other function.
How I want the data is tricky. I have a URL for all the feed elements. When a user clicks on a particular feed, I need to retrieve the URL associated with that particular feed.
I want to run a $.click() function in which I am going to $.post to the next php script.
How do I get that URL without storing it in the HTML itself. I do not want to store the URL in the html document for security puposes.
I am new with PHP.
You will need to assign unique id (uid) to each list element that corresponds to the url. A good way of handling this would be a database. You send the list item's identifier, look up in the database the associated url, perform some magic, and send the response back to the client. You can use jQuery's data method that leverages the html5 data attribute to store the information. Here is the basic pseudocode.
html
<li class="feed" data-uid="12345">Go</li>
javascript
$('li.feed').click( function() {
$.post({ id: $(this).data('uid') }, function(data) {
//do something with data
});
});
php
$uid = $_POST['uid'];
//db lookup of url
//do something with url
//return data to page
you could encrypt the url being sent from the server and then decrypt when it's sent back from the client. Just use a simple salt encryption method. I assume you're going to use ajax or the like to post back from the client to the server in which case, this methodology would work for you.
alternatively, you could create an array and store the urls in a collection with an associative key that you send to the client, then look up the url on the server side by that key. You could also implement a database solution to do this same thing where the key is the ID in the db.
U have to encode the variable url...
PHP
var url = ...;
JavaScript
$(function (){ var d1 = <?php echo json_encode(array($url)); ?>;});
If you check it out I have a bit of a problem with the following, I have a form (webbooks.phtml) in which I use a jQuery function
http://pastebin.com/7Pbd43fC -webbooks.phtml ( is actually a menu and in fact a view where you type the product that you are searching for)
http://pastebin.com/q8RJWdb7 -webbookscontroller ( this is a controller, which uses an API to get the data out of an SQL data base based on the string/number...etc given by the webbooks.phtml)
http://pastebin.com/vuy9GUvP -index.phtml (this is the view space where the result should be viewed.)
This is the array that I get:
{"book_title":"Bioethics in the 21st Century",
"id":"1424",
"isbn":"978-953-307-270-8","
unix_name":"bioethics-in-the-21st-century",
"visible_online":"1"}
I can see this array when I
die((json_encode)$result);
and I want this array to get to my view (index.phtml)?
I am new to PHP and I'm trying to do something that may be bad practice and may well be impossible. I'm basically just hacking something together to test my knowledge and see what PHP can do. Is this possible?
This is an example of basic usage of calling Zend Controller with ajax/json and get response to the same phtml,
so you can use it in your code.
In .phtml file I have javascript which call (in IndexController) the action ajaxAction():
<script language = "Javascript">
var param1 = 'first'; //or get value from some DOM element
var param2 = 'second'; //or get value from some DOM element
jQuery.ajax({
url: '/default/index/ajax',
type: 'POST',
data: {param1: param1, param2:param2 },
dataType: "json",
success: function(result){
var return1 = result.return1;
var return2 = result.return2;
// return1 and return2 is value from php file.
// fill out DOM element or do the windows.location()
}
});
</script>
In IndexController the ajaxAction() should get request:
public function ajaxAction(){
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$param1 = $this->_request->getParam('param1');
$param2 = $this->_request->getParam('param2');
// DO THE OTHER STUFF AND LOGIC HERE
$results = array(
'return1' => 'value1',
'return2' => 'value2'
);
$this->_response->setBody(json_encode($results));
}
In any way I suggest to listen the #jakenoble and look at(learn) Context Switching in Zend.
If the result of your client-side call is just a redirect to another page, then why not do it all on a single controller/action/viewscript, as follows:
Make the form submit a GET request rather than a POST
Submit the form back to the same page, perform your remote API call, and render the results.
Even if you want to do it in two actions - one to show the form, another to display the results - I don't see what value you are getting from the AJAX call.
Am I missing some other requirement?
Doing it with the current structure, you'd have to save the results of the remote API call into the session and then retrieve it after the redirect. Do-able, but it strikes me as unnecessary if it can be done in a single action.
i am trying from my main web page to check and in some cases send a variable via URL like this (http://192.168.0.110/CVAL.CGI?A0=1) this is to modify the status of something in my web page depending on the value seen in the url.
Sounds like you need Ajax.
There are many javascript libraries that can help you with this functionality such as jQuery, Prototype, or one of the many found on this page.
Hope that is what you are looking for and is helpful. Next time post more specific details so we can answer your question correctly the first time. Specific, detailed examples of what you want to do are also helpful.
UPDATED:
Here is an example using the Prototype Javascript library given your example form:
new Ajax.Request('/CVAL.CGI?A0=1', {
method: 'get',
parameters: { anotherValue: 'something' },
onSuccess: function(transport) {
alert(transport.responseText); // this is what the server returned
}
});
This would result in a request to /CVAL.CGI?A0=1&anotherValue=something. Whatever CVAL.CGI returns in response to that request, is available from transport.responseText.
This way, the user never has to leave the page or submit a form but it is all done behind the scenes. Your parameters can be any values you want to send which you can grab from form fields or other user input. You can return responses in JSON to make accessing the return data easier as well. Change method from 'get' to 'post' to do post requests.