I have a good understanding of AJAX and normally would have no problems using it but I am relatively new to Joomla and have only recently started building components, etc.
I have created a component (named directory) which is using the 'default' view. Within here I have the following code which is an AJAX call:
<script type="text/javascript">
var url = "index.php?option=com_directory&view=directory&task=clubFilter&format=raw";
jQuery(document).ready(function() {
jQuery('#city').change(function() {
jQuery.ajax({
url: url,
type: "POST",
data: jQuery("#city").serialize(),
dataType: 'json',
success: function(data) {
alert('data');
}
});
});
});
And within my 'views/directory/views.html' file I have created the following function which currently contains a die so I can confirm when it is working:
public function clubFilter() {
die(print_r('here_i_am'));
}
When I run the following code I ge the following error within Firebugs console..
'Error: 500 View not found [name, type, prefix]: directory, raw, directoryView'
I think it is because of the AJAX url var being incorrect but I have tried many different solutions from here nad other sources and just can't get the AJAX function working. Is my URL wrong?
Many Thanks
Normally, I make ajax calls to a task on the controller.
Here is the url format I am using in one of my extensions that uses ajax calls to a component:
index.php?format=raw&option=<component_name_goes_here>&task=<task_goes_here>
Then, in my component's default controller I put a function with the same name as the task:
function getSomeData()
{
echo(json_encode($data));//I normally return json
}
Hope this helps.
try this url. it might help you out.
var url = "index.php?option=com_directory&view=directory&task=clubFilter&tmpl=component";
format=raw replace with &tmpl=component
Else you can try the below format too.
jQuery.post('index.php',{
'option':'component_name',
'controller':'controller_name',
'task':'task_name',
'format':'raw',
'data': jQuery("#city").serialize(),
'dataType': 'json',
},function(result){
//edit the result here
return;
});
If you have any problem regarding this don't hesitate to ask.
Related
I'm novice with Ajax syntax. So I create my load content with append but, I want to know if its possible with PHP? Say to ajax "Learn this php file to display data" and on my PHP file we find a while or foreach with the data of my json file.
I want to use it in PHP because I use this template in some file (this "append") was normally call in 10 files, so i don't want to copy and paste all code, I need to change something, I want to edit only one file.
This is my actually ajax file:
$.ajax(
{
url: 'http://localhost/concerts/json/getConcerts?date=previous&limit=10&offset=' + i++ + '',
type: "get",
dataType: 'json',
success: function (data) {
$.each(data, function (idx, elem) {
$('#concertHome').append('<div>'+elem.bID9+'</div>')});
},
error: function () {
alert('Erreur lors de la requête...');
}
});}
PHP scripts execute when you open a file and before everything else (It's server side language). Ajax calls exectue when the Javascript is completely loaded. (After php).
So you cant do that. they cant communicate with each other without someting like Ajax Call or Fetch etc.
It seems to me that you do not necessarily need to have the Ajax code portion in a PHP file. What you really require is some reusable chunk of code that you can apply in various places within the same page or, in your case, in different pages.
What you should take from the itsolutionstuff post is the idea of putting the Ajax call into a function which you can then call with varying arguments like:
function doAjax(params)
$.ajax(
{
url: 'http://localhost/concerts/json/getConcerts?date=previous&limit=10&offset='
+ (params.i++),
type: "get",
dataType: 'json',
success: function (data) {
$.each(data, function (idx, elem) {
$(params.target).append('<div>'+elem[params.prop]+'</div>')});
},
error: function () {
alert('Erreur lors de la requête...');
}
});}
}
You should put this code segment into a separate .js file which can then be included into all your pages with a <script src="ajaxcode.js"></script> directive. Each time you want to trigger the ajax event you need to call the function doAjax(actualParamaterObject). The actualParameterObject contains various properties to be used in the function, like - for example -
actualParameterObject={i:25, prop:'bID9', target:'#concertHome'};
Handing down the offset i inside this parameter object will have the desired side effect that it will be incremented within the function call. Handing it down as a direct argument would not work in this way.
I am trying to fetch the contents of an external XML URL, into the javascript's ajax script, but it simply won't accept it, due to CROSS domain issue. I have searched through google regarding this issue, but nothing good so far, everything I've read so far stated that I need to incorporate PHP as well, but with that, the page would take reload.
I simply want that when a user enters a number that number gets passed as an argument in the URL, then displays the XML content in the screen without reloading.
SO any help will be highly appreciated.
Here's my code so far.
<script>
function myFunction() {
$("#dvContent").append("<ul></ul>");
$.ajax({
type: "GET",
url: "http://lx2.loc.gov:210/lcdb?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=1&query=bath.isbn%3D9781452110103",
dataType: "xml",
success: function(xml){
$(xml).find('record').each(function(){
var sTitle = $(this).find('datafield[tag="245"]').find('subfield[code="a"]').text();
var sAuthor = $(this).find('datafield[tag="100"]').find('subfield[code="a"]').text();
var sIsbn = $(this).find('datafield[tag="020"]').find('subfield[code="a"]').text();
$(".mypanel").html(text);
});
$("<li></li>").html(sTitle).appendTo("#dvContent ul");
$("<li></li>").html(sAuthor).appendTo("#dvContent ul");
$("<li></li>").html(sIsbn).appendTo("#dvContent ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
</script>
This is what am trying to achieve, I have a function in controller that generates a random password and returns the same, on button click I want to capture the generated password and display it in the view (password field). Here is the jquery/ajax call:
$(document).ready(function(){
$("#generate_password").click(function(){
$.ajax({
type: "GET",
dataType: 'text',
url: "http://127.0.0.1/public/admin/content/manufacturers/generate_password",
async:false,
success: function(resp){
alert(resp); //this alerts BLANK
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
});
Controller function:
public function generate_password($length = 9)
{
return $password_str;
}
Is this the correct way to call controller method?
Why am I getting blank value on alert, even though when printed in php am getting correct value?
Coz it's in the admin area can that be the reason, don't think so but is there any interference because of tokens?
In most cases, it is going to work okay, however you can use json format(and just json_encode/json_decode will finish the job for you), not sending via GET method and some other modifications.
Are you sure that the url is correct, if you open it in your browser, what happens?
You have to echo the variable in your function in place of return. Because return returns the value to the caller whereas echo sends something to the browser. JavaScript will only understand data which is sent to the browser. So, edit your function code as follows:
public function generate_password($length = 9)
{
echo $password_str;
}
On the other hand you should be doing this over HTTPS rather than HTTP as mentioned by #rodamn
Well strange but changing the url from:
url: "http://127.0.0.1/public/admin/content/manufacturers/generate_password",
to this:
url: "generate_password",
did the trick and everything is working fine now :)
Thanks everyone for their valuable inputs.
I have been researching and trying to learn the proper method to accomplish this. I have done the following but, I still have no change on my form. Is there anyway to see if the ajax call is even being made? Could anyone correct this code to figure out why I am not getting any change on the field in my form.
In my model I have the following function
public function standardRate($country)
{
$country_std_rate = Yii::app()->db->createCommand()
->select('AVG(rate_syr_mh)')
->from('packaging_metrics')
->where(array('like', 'country', '%'.$country.'%'))
->queryRow();
echo CJSON::encode($country_std_rate);
}
In my controller I have added this function as well as added 'countryRate' to my access control for all
public function countryRate()
{
$input_country = $_POST['country'];
$model = PackagingMetric::model()->standardRate($input_country);
echo CJSON::encode($model);
Yii::app()->end();
$this->render('countryRate',array(
'model'=>$model,
));
}
This is my Jquery call in my form
$('#PackagingMetric_std_rate').live('click',function()
{
var country = $('#country').val();
$.ajax({
type: 'POST',
url: 'PackagingMetric/countryRate',
data: {country:country},
success: function(data)
{
$('#PackagingMetric_std_rate').html(data);
}
});
});
However, nothing on my form changes with a value, I am using Yii-Debug-toolbar and not seeing any POST calls or any sql queries upon clicking the appropriate field on my form.
Rename the function in the controller to actionCountryRate()
When a post request is made to a controller, it looks for an action using the action prefix.
Your url parameter for the $.ajax(); is wrong could be wrong.
That is if you are not hiding the entry script (index.php), you will have to write:
url: 'index.php/controllername/actionname'
instead of:
url: 'controllername/actionname'
It would be better to use createUrl():
url: '<?php echo $this->createUrl('PackagingMetric/countryRate'); ?>'
(Ofcourse the echo above and how you include php code in js will depend on how you are including the js in the first place)
And name your countryRate as actionCountryRate().
I consider to use absolute url while firing an ajax call.
Try to make your url in this way, it will solve your problem.
url: '<?php echo Yii::app()->createAbsoluteUrl('PackagingMetric/countryRate'); ?>',
and your controller action name should be "actionCountryRate" because this function is hit from url, not internally called from controller, also set its accessRule if you are using access control otherwise the function will not execution.
I'm trying to implement a simple api request to the SEOmoz linkscape api. It works if I only use the php file but I want to do an ajax request using jquery to make it faster and more user friendly. Here is the javascript code I'm trying to use:
$(document).ready(function(){
$('#submit').click(function() {
var url=$('#url').val();
$.ajax({
type: "POST",
url: "api_sample.php",
data: url,
cache: false,
success: function(html){
$("#results").append(html);
}
});
});
});
And here is the part of the php file where it takes the value:
$objectURL = $_POST['url'];
I've been working on it all day and can't seem to find the answer... I know the php code works as it returns a valid json object and displays correctly when I do it that way. I just can't get the ajax to show anything at all!!
...data: 'url='+encodeURIComponent(url),