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.
Related
I am new to php and am trying to update a hidden field value inside a php function and can't see to find a solution that works.
In template.php I have:
<input type="hidden" id="variable_ID" name="variable_name" value="variable_value">
This works fine.
However I need to update the value of the variable to the record ID of inserted record in a function in functions.php eg
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
// *** Set Hidden field value to $get_record_id here ***
}
I have tried a myriad of things but can't seem to find a solution.
Any pointers on how to solve this problem?
Here is the solution I used - thanks to #Steven and #El_Vanja for direction.
(I may need to change the question title now though because what I actually needed to do was return a variable to javascript from PHP using Ajax. I didn't need to use hidden fields).
PHP
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
echo json_encode($get_record_id);
exit;
}
JS
jQuery.ajax({
url: ajax_url,
type:'POST',
data: {
action: "myFunction",
anydata:"to be posted"},
success: process_record_ID
});
function process_record_ID(data_returned_from_myFunction){
recordID = data_returned_from_myFunction;
}
Hope this helps others!
Notes
I believe that we have to declare 'process_record_ID' as a separate function outside of AJAX because AJAX is asynchronous. If we define the function in the success handler, the function runs in AJAX before the value is actually returned from PHP.
In the AJAX success handler, we don't need to explicitly list the 'data_returned_from_myFunction' variable in the call to process_record_ID function. When the data is returned to the AJAX success handler from PHP, it still gets sent to the function.
Additional answer
You're correct AJAX is an asynchronous construct which means that certain tasks can be carried out before you might expect them to (from a synchronous perspective).
For example we can (as per the code in the original answer) use jQuery to update the value of a field directly in the success handler.
We can't update a JS variable directly, i.e:
some_variable = response.value;
If you attempt it the variable some_variable will likely be undefined.
The difference comes down to callbacks:
Callbacks allow the asynchronous function to call a function after it completes. Where as setting a variable happens on the spot.
There are two easy ways to solve this issue then:
Create a function outside of the AJAX request and allow it to callback that function once the AJAX request has completed -- as you've already discovered.
Use the complete option inside of your AJAX request.
Using a call back
Firstly we need to define out variable to be updated and the function which we will use to update it:
var inserted_id = "";
function update_id(data){
inserted_id = data.record_id;
}
Then we can make out AJAX call:
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : update_id
});
N.B.
Calling update_id in this fashion means we pass the entirety of the returned JSON object; not just the returned number.
Alternatively...
var inserted_id = "";
function update_id(data){
inserted_id = data;
}
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response){
update_id(response.record_id);
}
});
This method is effectively the same but we only pass the returned number to the update_id function.
Using complete
complete works the same way as success however activates once the AJAX request is... complete...
var inserted_id = "";
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
complete: function(data) {
inserted_id = data.responseJSON.record_id;
}
});
Original answer
Having not seen the rest of your code giving a complete answer is tricky. However, this should set you on the right track:
PHP
Firstly, in your PHP you need to make sure and output the data that you want returned to the webpage. In this case we want to return the insert id of the newly created record; to do this we're going to output a JSON object so that the AJAX call can interpret the value and update the page:
function myFunction() {
$mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
echo json_encode(["record_id" => $mydb->insert_id]);
exit;
}
N.B.
We don't want any output other than the JSON string. Hence exit has been used after the echo. You may want/need to adjust the echo and exit to fit with the rest of your code etc.
JS
Now that we have our PHP returning usable data to our ajax call (which should look something like the below) we can take the returned data aka response and update the value of the hidden field accordingly.
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response) {
$("#id_of_hidden_field").val(response.record_id);
}
});
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.
I have the following function that is called when I click on a button to submit a form:
function dadosFormularios(preenchimentoForm){
//var path = document.location.pathname;
//alert(path);
alert(preenchimentoForm);
//window.location.href = 'wp-content/themes/template/index.php';
var qstringA = '';
//dados dos campos
var nome=document.getElementById("nome").value;
qstringA = 'nome='+ nome;
//alert(qstringA);
if(preenchimentoForm==false){
alert('Please correct the errors in the Form');
}
else{
if(preenchimentoForm==true){
window.location.href = 'index.php?'+qstringA;
return false;
}
}
}
Since I'm using this way of processing the data, how can I alert my page index.php that the data sent by the function arrived on the index? I can't use a if (isset($_POST['button']..) since I send the information by the function and not through the button of the form, right?
window.location.href = 'index.php?'+qstringA;
This line is just redirecting to index.php with a query string ?nome=nome_value.
For example. index.php?nome=nome_value
So, in your index.php You can simply get everything posted with $_GET.
Check it by doing a print_r($_GET); there.
In index.php, you can simply check
if(isset($_GET["nome"])){
//Nome is set
//Do something here
}
P.S. Although, without knowing the other circumstances or reasons behind usage of this function, it can be said that this function is just doing what a simple <form action=index.php> would have done.
P.P.S. Although you have mentioned jQuery in title and also tagged it, I am not sure this function is using any of the jQuery code. I think it is just a simple Javascript function.
If you're using jQuery, check out .ajax(). Just remember, it's asynchronous, so the results may not be what you think they are. You don't need to reload the whole page (which is what your window.location.href = 'index.php?'+qstringA; would do) just to submit information.
If you want to alert or something when the ajax call completes, you can define a function to call on a successful ajax call.
Use ajax() like :
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
http://api.jquery.com/jQuery.ajax/
I am building an application with codeigniter and I want to post some data using jQuery but for some reason it doesn't work. Here is the code what am I doing wrong ?
$.ajax({
url: "<?=site_url('requests/save')?>",
type: "POST",
data: data,
success:function(msg){
alert(msg)
}
});
I haven't written any code in the controller yet, just something simple to test it. Also as long as javascript is concerned that's about it. The ajax is trigered when the user clicks a button.
function save()
{
if($this->input->is_ajax_request()) {
echo 'ajax';
}
else
{
echo'sdfs';
}
}
Dante,
First make sure you load your helper:
$this->load->helper('url');
Also post the JAVASCRIPT for us, not the PHP. The Javascript is what is failing, not the CI PHP. You might have a PHP issue also on your controller for 'requests/save', have you checked that?
I believe you need to pass a cross site request forgery token.
If you set XSS to true in your config, then your form helper creates a hidden field that is required to be passed to your server.
Make sure you are properly collecting your form data. Easiest to use jquery the .serialize() function.
Load the url helper in the autoload.php. Your url in the ajax call should just be 'requests/save'.
Also php shorthand echo tags are a bad practice stick to
<?php echo ?>
for better code portability
Moved my comment to an answer
EDIT : to test the ajax, use the relative url instead use a php tag inline in your js, to your controller, which will work in any condition (in CI) whether you already removed the index.php from your url (using htaccess) or not by include the index.php in your url.
$.post('/index.php/request/save', { foo: 'bar' }, function (html) {
alert(html);
});
At targeted controller
function save()
{
if($this->input->is_ajax_request())
{
echo $this->input->post('foo') ? $this->input->post('foo') : 'Not Bar';
}
else
{
echo'Not from AJAX';
}
}
EDIT :
also make sure you have already load the url helper before using its function
$this->load->helper('url');
Before I begin, I'm using PHP and JS lib Prototype to handle Ajax in my code.
So my problem is the following:
I'm using the following function to load a php file into a target DIV
function ajaxUpdater(id, url)
{
new Ajax.Updater('targetDiv', 'data.php', {asynchronous: true});
}
using the onClick function within a button, I grab the contents of data.php and display it in a DIV with the id of 'targetDiv'.
the problem is this.
There are certain things within data.php that i want to have hidden and only shown when an event is triggered.
I've been trying loads of different solutions, but nothing seems to work.
(just to add to the confusion, functions work when data.php is opened individually, but not when data.php is loaded using my ajax function.
Any help or clues or anything will be much appreciated!
Hiroki,
I'd suggest passing some a parameter with your Ajax method and using some logic in data.php to pick and choose what data to send back. Here's an example of how I pass parameters with my prototype calls.
new Ajax.Updater('targetDiv', 'data.php', {
parameters: { myParam1: 'hello', myParam2: 'world'}
});
The go into your data.php file to create some logic. Note that by default, prototype's method to send params is POST, but you can always change that by declaring method: 'get' in the same Ajax.Updater call, like so:
new Ajax.Updater('targetDiv', 'data.php', {
method: 'get',
parameters: { myParam1: 'hello', myParam2: 'world'}
});
Check out the AJAX section of the Prototype API. In it, it talks about an option you can use called 'evalJS' that you can set to true. When you have this option set, any javascript returned by the updater will be evaluated and ran like normal.
function ajaxUpdater(id, url) {
new Ajax.Updater('targetDiv', 'data.php', {
asynchronous: true,
evalJS: true
});
}