sending data from controller to model - ajax

I have the following code on my site which sending data to Ajax and works normal. It is about add to cart.
public function adding()
{
$id_lap=$this->input->post('id_lap');
$num_items=$this->input->post('num_items');
$price=$this->input->post('price');
if($id_lap !='')
{
$this->session->set_userdata('num_items',$num_items);
$this->session->set_userdata('price_new',$price);
$response=array(
'status'=>1,
'num_items'=>$num_items,
'price_new'=>$price
);
} else {
$response=array(
'status'=>0
);
}
echo json_encode($response);
}
When I want to send data to model also where I want to write data into database along with IP adress which I will collect with model. When I add new row anywhere my Ajax crashed. Part of code which I want to add is:
$this->users_mod->AddSesija($id_lap,$price);
And Ajax code which I am using is :
function Addtocart(id,prices)
{
var id_lap=id;
var ajaxURL= BASE_URL +'home/adding';
var num_items = parseInt($('#num_items').html()) + 1;
var price = parseInt($('#price_b').html());
var price_new = price + prices;
/*console.log(id_lap +' '+num_items+' '+price_new);
$('#num_items').html(num_items);
$('#price_b').html(price_new); */
$.ajax({
url:ajaxURL,
type:'POST',
data:{'id_lap':id_lap,'num_items':num_items,'price':price_new},
success:function(response)
{
var parsed = JSON.parse(response);
if(parsed.status ==1)
{
$('#num_items').html(parsed.num_items);
$('#price_b').html(parsed.price_new);
}
}
}
)
}

I am agree with Vladimir Glisovic in concept. we know that for adding or inserting group of data we should bind them into an array.
Sample:
$data=array( 'ip_adress'=>$ip_adress, 'id_lap'=>$id_lap, 'cena'=>$price );
N.b: get IP address from PHP code keep in $ip_address.
Then pass the data to model with the CI syntax.
Model calling in Controller:
$this->users_mod->AddSesija($data);
Now write the inserting code in the model file as
public function AddSesija($data){
insertion code here.....
}
Hope it will help you.
Thanks!
Amadercode

Related

Zend 1 ajax with dojo informatiom person

I'm working with Zend 1 with dojo and do not know how to use ajax . In my particular case that when selecting a select , whether made ​​in consultation ajax back from the database information. To enter a ID from user print the information from user by ajax.In my work I can't use jquery.
Good question!
Not is very productive work with dojo, but is possible make exactly how do you want. You will create p element with information captured in data base
In your form, add attribute 'onChange'
$form->setAttrib('onChange', 'recoveryData()');
In js file do you have a function recoveryData(), something as:
dojo.require("dojo.html");
// clean data
var myNewElement = dojo.byId('myNewElement');
if (myNewElement != null) {
dojo.empty("myNewElement");
}
dojo.xhrPost({
content: {id: dojo.attr(dojo.byId("myElement"), "value")},
url: 'your-base-path/recovery-data/',
load: function (response) {
if (response != false) {
// converte to obj
var obj = dojo.fromJson(response);
// creat new element
var node = dojo.create("span", {
innerHTML: obj.NomeServidor,
id: "myNewElement",
'class': 'row'
}
);
dojo.place(node, dojo.byId("myElement"), "after");
}
}
});
Now, you need create an Action "recoveryDataAction()" in your Controller like this:
$data = $this->getrequest()->getPost();
$id = $data['id'];
if ($this->getrequest()->isXmlHttpRequest()) {
// disable layout
$this->_helper->layout()->disableLayout();
// disable view render
$this->_helper->viewRenderer->setNoRender();
$yourTable = new Project_Model_YourTable();
$row = $yourTable->fetchRow($id);
if ($infos != null) {
echo Zend_Json::encode($row);
return;
}
echo false;
}

phpfox , get value as response from an ajax call

Trying to make an ajax call and get something as response in phpfox .
the JS :
$.ajaxCall('module.check_whether_first_time',
'u_id='+u_id+'&my_user_id='+my_user_id).done(function(data) {
alert(" data = " + data )
});
The function which the ajax calls from within ajax.class.php :
public function check_whether_first_time(){
$u_id = $this->get('u_id');
$my_user_id=$this->get('my_user_id');
// processing with data goes here
$counter=1;
echo $counter;
}// end of function check_whether_first_time
I want to get the value of $counter in data variable. The code does not work but FireBug shows the ajax request with no result returned as response. What is the way ?
{literal}
<script>
function check(u_id,my_user_id)
{
$.ajaxCall('user.check_whether_first_time','u_id='+u_id+'&my_user_id='+my_user_id).done(function(data)
{
alert(" data = " + data)
});
}
</script>
{/literal}
click
i Use this function and it return me output in data variable
ajax function in user module
public function check_whether_first_time(){
$u_id = $this->get('u_id');
$my_user_id=$this->get('my_user_id');
$counter=10;
echo $counter.$u_id;
}
$.ajaxCall('organization.getUsersbyid', 'id=' +id+ '&ids=' +ids +'&idss=' +idss +'&idsss=' +idsss );
public function getUsersbyid() {
$id=$this->get('id');
$join=1;
$ids=$this->get('ids');
$idss=$this->get('idss');
$idsss=$this->get('idsss');
$add = Phpfox::getService('organization.process')->getUsersbyid($id,$ids,$join,$idss,$idsss);
}

Kohana validation client-side ajax

i've been working on a validation script for client-side, that uses built-in Kohana validation, trying to do it in a way that works both client and server sides. So far i made the server side work, but i need some help improving my javascript (My javascript knowlodgement ain't that good) and finish implementing it. (Currently it works for inputs and textareas).
A random controller:
// ...
$errors = array();
if ($this->request->method() == 'POST')
{
// Post to validate/look and get the decoded array
$validate = Request::factory('validate/look')->post($this->request->post())->execute()->body();
$errors = json_decode($validate, TRUE);
// Empty array, Validation OK
if ($errors === array())
{
// anything u want here
}
}
Now, the Validation controller (which will be called from any controller, or via ajax):
class Controller_Validate extends Controller {
public function action_look()
{
//$user = $this->user->loader() ? $this->user : NULL;
//Validation
$valid = Validation::factory($this->request->post())
->rules('name', array(
array('not_empty'),
array('min_length', array(':value', 10)),
array('max_length', array(':value', 80)),
array('regex', array(':value', '/^[\pL\pN ]++$/uD')),
array(array($this, 'check_name')),
))
->rules('description', array(
array('not_empty'),
))
->rule('look_tags', array($this, 'check_tags'))
;
$valid->check();
// Only get messages for the posted fields
$resp = array_intersect_key($valid->errors('uploadlook'), $this->request->post());
$this->response->body(json_encode($resp));
}
}
And this is the javascript:
$(function(){
$('.validate').find('input,textarea').blur(function(){
var element = $(this);
var name = $(this).attr('name');
var value = $(this).val();
$.ajax({
type: 'POST',
url: '/comunidad/validate/look',
data: name + '=' + value,
success: function(e){
e = JSON.parse(e);
if(e.length !== 0) {
var msg = e[name];
var error = '<p>' + msg + '</p>';
if (element.next().length === 0) element.after(error);
else element.next().replaceWith(error);
} else {
if (element.next().length) element.next().remove();
}
}
});
});
});
I need some feedback and little help completing the javascript :)
Some feedback on the code:
The validation code shoud be put in a helper and should just return an array. Then you should have an AJAX-controller that uses the helper and outputs JSON. The serverside check should only use the helper.
That would be much cleaner and the json encode/decode on the server side is pretty ugly when you can just return an array.
What is wrong with the javascript?

AjaxSubmit overwrite form field before send

I would like to overwrite the value of the "password" field before submiting a form on Jquery using AjaxSubmit function.
I know I can just update the value on the input field but, I don't want the user to see this transformation. In other words, I just want to send a custom value to the password field and keep the current value on the screen...
How could I do that?
My current code:
var loginoptions = {
success: mySuccessFuction,
dataType: 'json'
}
$('#My_login_form').submit(function(e) {
e.preventDefault();
var pass=$("#My_login_form_password").val();
if (pass.length>0){
loginoptions.data={
password: ($.sha1($("#My_login_form_csrf").val()+$.sha1(pass)))
}
$("#My_login_form").ajaxSubmit(loginoptions);
delete loginoptions.data;
});
The problem with this code is that it is sending a "password" POST variable with the form field value and, a duplicated one with the value I set on "loginoptions.data".
Building off of Cristiano's answer, I was able to get this to work. If you use :beforeSubmit(), the changed value doesn't post, but if you use the :beforeSerialize(), it posts the changed value.
$('#ff').ajaxForm({
beforeSerialize:function(jqForm, options){
var serializedForm = decodeURIComponent(jqForm.serialize());
options.data = serializedForm.deserializeToObject();
options.data.tPassword = MD5($("#tPassword").val())
},
success:function(data){
// do stuff
}
});
If you want to do it anyhow then I think you can use callback function beforeSubmit: function(contentArray, $form, options){}
beforeSubmit: function(contentArray, $form, options){
for(var i=0; i<contentArray.length; i++){
if(contentArray[i].name == "password") {
contentArray[i].value = ($.sha1($("#My_login_form_csrf").val()+$.sha1(pass)))
}
}
}
It seems that ajaxSubmit uses the serialize() function of jquery on the form and then, adds the extra data serialized too. So, if I have a field named "password" with the value "1234" and then try to change that to "abcd", using "loginoptions.data.password", it will serialize everything and put the "options.data" like this:
"password=1234&field_2=value_2&password=abcd"
After many tries, I gave up on using ajaxSubmit function and decided to use ajax function to submit the form:
var the_form=$('form#My_login_form');
loginoptions.url=the_form.attr("action");
loginoptions.type=the_form.attr("method");
var serializedForm=decodeURIComponent(the_form.serialize());
loginoptions.data=serializedForm.deserializeToObject();
var pass=$("#My_login_form_password").val();
if (pass.length>0){
loginoptions.data.password= ($.sha1($("#My_login_form_csrf").val()+$.sha1(pass)));
}
$.ajax(loginoptions);
Here is the deserializeToObject() function:
function deserializeToObject (){
var result = {};
this.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { result[$1] = $3; }
)
return result;
}
String.prototype.deserializeToObject = deserializeToObject;

dojo.xhrPost and Zend Framework action, no POST data, not using a form

I'm trying to send some data via dojo.xhrPost to an Zend Controller Action. I can see the data being sent in Firebug console. However, when inspecting the post data, the array is empty.
I'm not sure if it is possible to send an arbitrary string of data via dojo.xhrPost without using a form. This is probably a very n00b mistake. In any case, I'll post my code here and see what you all think.
In my layout script I have:
<?php
$sizeurl = $this->baseUrl() . '/account/uisize';
?>
function resizeText(multiplier)
{
if (document.body.style.fontSize == "")
{
document.body.style.fontSize = "1.0em";
}
document.body.style.fontSize = parseFloat(document.body.style.fontSize) + (multiplier * 0.1) + "em";
var size = document.body.style.fontSize;
var xhrArgs = {
url: "<?= $sizeurl; ?>",
postData: size,
handleAs: "text"
}
dojo.xhrPost(xhrArgs);
}
Then my action is:
public function uisizeAction()
{
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
print_r($_POST);
$request = $this->getRequest();
if ($request->isXmlHttpRequest())
{
$postdata = $request->getPost();
print_r($postdata);
if ($postdata)
{
$user = new Application_Model_DbTable_User();
$user->updateSize($postdata);
}
}
}
I'm pretty sure that post data from a form is an array with the form elements' names as the keys. When looking at the dojo.xhrPost examples on the dojo campus web site (http://docs.dojocampus.org/dojo/xhrPost second one to be precise), it looks as if I can just send a string of data. How do I access this data from a Zend Controller Action?
I'm using ZF 1.10 and Dojo 1.4.2
Thanks for your help!
PS
I'd try to ask on one of the related questions, but I cannot seem to comment.
After reading about http methods here:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
I figured that I need to encode the data sent in a way that will be converted to an array by PHP. So here is the new bit of javascript:
function resizeText(multiplier)
{
if (document.body.style.fontSize == "")
{
document.body.style.fontSize = "1.0em";
}
document.body.style.fontSize = parseFloat(document.body.style.fontSize) + (multiplier * 0.1) + "em";
var rawdata = "uisize="+document.body.style.fontSize;
var xhrArgs = {
url: "<?= $sizeurl; ?>",
postData: rawdata,
handleAs: "text"
}
//Call the asynchronous xhrPost
dojo.xhrPost(xhrArgs);
}
The difference is I am now specifying a key pair and sending that. When using AJAX that could make forms overkill. So now my UI is resized and the size is stored with the user's profile. So the next page they request will use the size they set. Cool.

Resources