I would really need some help from to AJAX Guru master overthere to help me building my update cart function on my website in AJAX.
So basically, what I would like to do is, when I modify one of my product in one input_dropdown, my 'update_cart' function is automaticaly called and my prices are updated as well as my input
EDIT : I rewrite my question since I made some progress thanks to Matei
Here is my view :
<?php
$options = array(
'0' => '0',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
'6' => '6',
'7' => '7',
);
if($product['quantity']==0){
$value[$product['title']] = set_value('quantity'.$product['title']);
}else{
$value[$product['title']] = $product['quantity'];
}
$data0 = 'class="quantSelect" value="'.$value[$product['title']].'" id="quant'.$product['title'].'"';
echo form_dropdown('quantity'.$product['title'], $options, $value[$product['title']],$data0);
?>
</td>
<td>
<?php echo $product['price'] ?>
</td>
<td id="<?php echo 'price'.$product['title']?>">
$<?php echo $total[$product['title']] ?>
</td>[/code]
Well, everything is in a foreach loop but I think that here, it doesn't matter.
Then I tried to set up the Matei AJAX function :
$(".quantSelect").click(function(){
$.POST("<?php echo base_url().'main/update_cart';?>",
{product_id:$('<?php echo $product['quantity']; ?>').val(),quantity:$('<?php echo 'quantity'.$product['title'] ?>').val()},
function(data){
if(data.success) {
$("<?php echo 'price'.$product['title']?>").val(data.some_returned_value); // update value of an text input or textarea (view more info about jQuery selectors)
$("#totalPriceWithTaxes").html(data.some_other_returned_value); // update value of a paragraph
}
}, 'json');
});
And at last the update cart function :
function update_cart(){
$success = false;
if(!empty($_POST['product_id']) && !empty($_POST['quantity']) && is_numeric($_POST['quantity'])) {
// I get all the information i need here in order to calcul the final price
//We calcul the final price with taxes, shipping and everything.
$data['totalPriceWithTaxes'] = $data['tax'] + $data['totalPrice'] + $data['Shipping']->shipping;
$this->session->set_userdata('totalPriceWithTaxes', $data ['totalPriceWithTaxes']);
$success = true;
$some_returned_value = 69;
$some_other_returned_value = $data['totalPriceWithTaxes']; // the final price
}
echo json_encode(array("success" => $success,
"some_returned_value" => $some_returned_value,
"some_other_returned_value" => $some_other_returned_value));
}
Here we are, so I can't see any update. If someone could help me to figure out how to set up that AJAX Function, I would deeply appreciate :)
I recommend you to take a look at jQuery.post() method of jQuery library.
Let's see the following example:
Javascript code:
$("#submit-button").click(function(){
$.POST("/PATH_TO/update_cart.php",
{product_id:$('#product-id').val(),quantity:$('#quntity').val()},
function(data){
if(data.success) {
$("#form-field-id").val(data.some_returned_value); // update value of an text input or textarea (view more info about jQuery selectors)
$("p#form-p-id").html(data.some_other_returned_value); // update value of a paragraph
}
}, 'json');
});
For more info about jQuery Selectors please check this
PHP code:
<?php
$success = false;
if(loged()) { // verify if the user is loged (if it's needed)
if(!empty($_POST['product_id']) && is_numeric($_POST['product_id']) && !empty($_POST['quantity']) && is_numeric($_POST['quantity'])) {
// use here your additional code
// update database
// if every condition is applied then confirm that the fields are updated
$success = true;
$some_returned_value = "data has been successfully updated";
$some_other_returned_value = 45.3; // the final price
}
}
echo json_encode(array("success" => $success,
"some_returned_value" => $some_returned_value,
"some_other_returned_value" => $some_other_returned_value));
?>
This is a simple example about how you can use jQuery POST method and PHP for updating data you want. I didn't use any of your code, but you can try to update your cart like this. jQuery is a powerfull library, so I'll recommend you to take a look at it.
Related
I'm having trouble with my project. I am trying to post something to the database via jQuery, but there is something wrong in my code and I am unable to figure out what.
Basically, I have a form:
<form id="addCartForm" method="POST" action="callback/additemtocart.php">
</form>
Inside the file additemtocart.php I have the following code:
$item_id = $_POST['item_id'];
$brand_id = $_POST['brand_id'];
$category_id = $_POST['category_id'];
if(item_exists($item_id, $brand_id, $category_id, $_SESSION['user_id']))
{
$errors[] = 'this item is already in your cart';
}
else
{
//register the user
$item_data = array(
'user_id' => $_SESSION['user_id'],
'item_id' => $item_id,
'brand_id' => $brand_id,
'category_id' => $category_id
);
add_item_to_cart($item_data);
$cart[] = 'An item has been added to your cart!';
}
Once the user clicks on the item, I will execute the following code:
$(".cart_item").click(function(){
var name = $(this).attr("id");
var array = name.split("|");
var data = [];
data.push({"item_id": array[0]});
data.push({"brand_id": array[1]});
data.push({"category_id": array[2]});
$.post($("#addCartForm").attr("action"), data, function(info){
});
});
$("#addCartForm").submit(function(){
return false;
});
Is there something wrong with it?
Your code won't work the way you want it to.
Javascript/jQuery is executed client side, the PHP is executed server side. When the callback in jQuery is fired, there's no PHP server on the client to deal with this PHP you've got there.
What you want to do instead, is pass the array key and string as a parameter in the $.post, to the script on the server, which can then add the string to your errors array.
Like this:
data.push({"item_id", array[0]});
data.push({"brand_id", array[1]});
data.push({"category_id", array[2]});
data.push({"errors", "my error string"});
$.post($("#addCartForm").attr("action"), data, function(info){
//success message?
});
Then in the action script, you'll be able to check for the get parameter $_POST['errors'], and add it to your PHP errors array.
if(isset($_POST['errors']) && !empty($_POST['errors'])){
$errors = $_POST['errors'];
}
EDIT: That aside, given your edit, your error is that your array isn't defined, is it? You have arrays named array1 and array2 but you're then trying to access array[0], array[1] and array[2]. It should be array2[0], etc.
I'm need help in making a cascading dropdown that contains data from the database
I found a tutorial about this
and
I've tried this
Controller:
function ajax_call() {
if(!empty($_POST['table'])){
if ($_POST) {
$table = $_POST['table'];
$arrYear = $this->my_model->get_categories($table);
foreach ($arrYear as $years) {
$arrFinal[$years->category2 = $years->category2;
}
echo "<p>2nd Category:<br>";
echo form_dropdown('year',$arrFinal);
echo "</p><br>";
}
else
{
echo "<p>2nd Category:<br>";
echo form_dropdown('year','');
echo "</p><br>";
}
}
}
My view:
$options = array(
'' => 'Select',
'category_one' => 'Category 1',
'category_two' => 'Category 2',
);
echo form_error('table');
echo "<p>Category:<br> ";
echo form_dropdown('table', $options, $this->input->post('table'), 'id="table"');
echo "</p><br>";
Script inside my view:
<script type="text/javascript">
$(document).ready(function(){
$('#table').change(function(){
var selTable = $(this).val(); // selected name from dropdown #table
$.ajax({
url: "ajax_call", // or "resources/ajax_call" - url to fetch the next dropdown
async: false,
type: "POST", // post
data: "table="+selTable, // variable send
dataType: "html", // return type
success: function(data) { // callback function
$('#year').html(data);
}
})
});
});
</script>
My Model:
function get_categories($table) {
$this->db->select('category2')->from($table);
$query = $this->db->get();
return $query->result();
}
My only problem with this is that the 2nd dropdown isn't visible on the page when loaded, and it would only appear when I select on the 1st dropdown.
How can i make set it to appear on the page without selecting on the 1st dropdown?
Can anyone help?
Ok I couldn't figure out how to do what i wanted. So instead i searched around the deep parts of the internet and found this little tutorial that was actually what i needed.
http://supundharmarathne.wordpress.com/2013/03/13/simple-ajax-drop-down-filtering-with-codeigniter/
This is happening because the ajax call to populate your table is only being triggered after the table changes $('#table').change(function(){...}). Try populating the table without waiting for such change; maybe inside $(document).ready(function(){...})
you added a completely obsolete if ($_POST) to your code. You are already checking if a variable in $_POST exists, hence it can never be empty after that. That caused your ELSE statement to relate to the second IF, not the first.
function ajax_call() {
if(!empty($_POST['table'])){
$table = $_POST['table'];
$arrYear = $this->my_model->get_categories($table);
foreach ($arrYear as $years) {
$arrFinal[$years->category2 = $years->category2;
}
echo "<p>2nd Category:<br>";
echo form_dropdown('year',$arrFinal);
echo "</p><br>";
}
else
{
echo "<p>2nd Category:<br>";
echo form_dropdown('year','');
echo "</p><br>";
}
}
and that is why you should always indent your code correctly.
I use the following select2 Yii widget in my view to populate a drop-down list. Since the data necessary for the preparation of the select list consists of more than 2K records I use select2 with minimumInputLength parameter and an ajax query to generate partial result of the list based on user input. If I create a new record I have no problem at all. It populates everything fine and I can save data to my database. However I don't know how to load saved data back to this drop-down during my update action. I read somewhere that initselection intended for this purpose but I couldn't figure out how to use it.
Can someone help me out on this?
My view:
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
'allowClear'=>true,
'placeholder'=>'Kérem válasszon összetevőt!',
'minimumInputLength' => 3,
'ajax' => array(
'url' => Yii::app()->createUrl('etelOsszerendeles/filterOsszetevo'),
'dataType' => 'json',
'quietMillis'=> 100,
'data' => 'js: function(text,page) {
return {
q: text,
page_limit: 10,
page: page,
};
}',
'results'=>'js:function(data,page) { var more = (page * 10) < data.total; return {results: data, more:more }; }',
),
),
));?>
My controller's action filter:
public function actionFilterOsszetevo()
{
$list = EtelOsszetevo::model()->findAll('nev like :osszetevo_neve',array(':osszetevo_neve'=>"%".$_GET['q']."%"));
$result = array();
foreach ($list as $item){
$result[] = array(
'id'=>$item->id,
'text'=>$item->nev,
);
}
echo CJSON::encode($result);
}
I use initSelection to load existing record for update in this way (I replaced some of your view code with ... to focus in main changes). Tested with Yii 1.1.14. Essentially, I use two different ajax calls:
View:
<?php
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
...
...
'ajax' => array(
'url' => Yii::app()->createUrl('client/searchByQuery'),
...
...
'data' => 'js: function(text,page) {
return {
q: text,
...
};
}',
...
),
'initSelection'=>'js:function(element,callback) {
var id=$(element).val(); // read #selector value
if ( id !== "" ) {
$.ajax("'.Yii::app()->createUrl('client/searchById').'", {
data: { id: id },
dataType: "json"
}).done(function(data,textStatus, jqXHR) { callback(data[0]); });
}
}',
),
));
?>
Now in your controller you should receive parameters for ajax processing: query (q), as string, when inserting; id (id) as int when updating. Parameter names must be same as ajax data parameters (in this sample insert q; in update id) when read in $_GET. Code is not refactored/optimized:
Controller:
public function actionSearchByQuery(){
$data = Client::model()->searchByQuery( (string)$_GET['q'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
public function actionSearchById(){
$data = Client::model()->findByPk( (int) $_GET['id'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
Model - custom query and a little of order / security / clean :)
public function searchByQuery( $query='' ) {
$criteria = new CDbCriteria;
$criteria->select = 'id, ssn, full_name';
$criteria->condition = "ssn LIKE :ssn OR full_name LIKE :full_name";
$criteria->params = array (
':ssn' => '%'. $query .'%',
':full_name' => '%'. $query .'%',
);
$criteria->limit = 10;
return $this->findAll( $criteria );
}
EDIT:
It works out of box when update is preloaded with traditional HTTP Post (synchronous, for example with Yii generated forms). For async/Ajax updates, for example with JQuery:
Event / Trigger:
$('#button').on("click", function(e) {
...
... your update logic, ajax request, read values, etc
...
$('#select2_element').select2('val', id_to_load );
});
With this, initSelection will run again in async way with new id_to_load value, reloading record by id.
In your case and for your needs, initSelection could be complete different to avoid load record from db or you can use formatResult and formatSelection custom functions (are described in Load Remote Data sample source code). Reading documentation, I understand that initSelection's callback need JSON data with id and text elements to load properly or you could try to combine both concepts (this initSelection with your custom JS event/trigger call) (not tested):
'initSelection'=>'js:function(element,callback) {
// here your code to load and build your values,
// this is very basic sample
var id='myId';
var text='myValue';
data = {
"id": id,
"text": text
}
callback(data);
}',
Or directly on Trigger call:
$('#button').on("click", function(e) {
...
... ...
$("#select2_element").select2("data", {id: "myId", text: "MyVal"});
});
Hope that helps.
I tried doing that way, but couldn't do it
the solution I came up to get my record filled and selected was:
In case of the attribute having some data(in update mode or default value), I wrote some javascript that after document ready event, would fill the select with my data (just selected it ind pushed html in it), and made it selected, and then I rest( or update) the select to show my work.
I'm building a website with Yii framework 1.1 and i'm implementing a portion wherein i have a like button associated with each post.i want to update the content of the like buttons text everytime i click on it without refreshing the page?please help?
EDIT
i did this
`id;
$foo = $data->likes;
echo CHtml::ajaxbutton($foo.' '.'Likes',
array('post/like/'.$id),
array(
'type'=>'POST',
'success'=>'js:function(data){ $.fn.yiiAjaxButton.update("label");}')
);
?>`
still doesnt work
Your View should be like bellow
<?php
$postId = 1; //Your post id
echo CHtml::Button('SUBMIT', array('onclick' => 'getComments(this);', 'data-value' => $postId, 'value' => 'Get Comments'));
?>
And Write your Ajax call some thing like
<script type="text/javascript">
function getComments(obj)
{
$PostID = $(obj).data('value');
$.get('Controller/YourMethod', {id:$PostID}, function(dataJSON)
{
//Get data in JSON formate
},'JSON');
}
</script>
EDIT
If you want to add Ajax call directly to your button, you can do as
<?php
$postId = 1;
echo CHtml::Button('SUBMIT', array('value' => 'Get Comments','onclick' => ''
. '$.get("Controller/YourMethod", {id:'.$postId.'}, function(dataJSON)
{
//Do what ever you want here
},"JSON");'));
?>
I am trying to validate the dropdownlist as the value of dropdownlist changes. I want to check is there an in the the table already of the selected job status.
Below is my code:
<script>
function validate_dropdown(id)
{
alert("Selected id = "+id);
//var msg = <?php echo NotificationRules::model()->validate_job($_POST['id']);?>
//alert("Message from model func = "+msg);
}
</script>
<?php
echo $form->dropDownList($model, 'job_status_id', $jobstatuslist ,
array('empty'=>'Please Select job status (required)', 'onchange'=>'js:validate_dropdown(this.value)')
);
?>
I am trying to pass js variable id to php function and send back a message if there is already an entry for the selected job status. I am able to get selected value in js function validate_dropdown(), but not able to proceed further.Anybody pls help.......
Check this bellow example. In this i'm displaying all the users in a drop down list. I'm keeping user id as option value and username as option label.
User Table:
id username
------------------
1 Heraman
2 Dileep
3 Rakesh
4 Kumar
<?php
$list=CHtml::listData(User::model()->findAll(), 'id', 'username');
echo CHtml::dropDownList('username', $models->username, $list, array('empty' => '---Select User---','onchange'=>'alert(this.value)'));
?>
In you case, you can use
'onchange'=>'validate_dropdown(this.value)
//Your script
<script>
function validate_dropdown(id)
{
alert("Selected id = "+id);
}
</script>
I solved the problem by making an AJAX call...
Final working code:
Code of dropdown in view
<?php
echo $form->dropDownList($model, 'job_status_id', $jobstatuslist ,
array(//AJAX CALL.
'prompt' => 'Please Select job status (required)',
'value' => '0',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('NotificationRules/notificationPresent/'),
'data' => array("job_id" => "js:this.value"),
'success'=> 'function(data) {
if(data == 1)
{
alert("Rule is already present for this status, Please update existing rule.");
}
}',
'error'=> 'function(){alert("AJAX call error..!!!!!!!!!!");}',
)//end of ajax array().
));
?>
Code in controller(action)
<?php
public function actionNotificationPresent()
{
if (Yii::app()->request->isAjaxRequest)
{
//pick off the parameter value
$job_id = Yii::app()->request->getParam( 'job_id' );
if($job_id != '')
{
//echo "Id is received is ".$job_id;
$rulesModel = NotificationRules::model()->findAllByAttributes(array('job_status_id'=>$job_id));
if(count($rulesModel))
echo 1;
else
echo 0;
}//end of if(job_id)
else
{
//echo "Id id not received";
echo 0;
}
}//end of if(AjaxRequest).
}//end of NotificationPresent().
?>
Now i am getting an alert if there is any rule already with selected job status.