phpfox , get value as response from an ajax call - ajax

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);
}

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;
}

sending data from controller to model

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

jQuery plugins, scope, and binding a created element to the 'change' event

So, I'm writing my first plugin. I'm using the advice on the jQuery website, so my plugin setup looks something like this:
(function( $ ){
var methods = {
init : function( options ) {
var $this = $(this);
// do some code.
// Add an element
$this.append('<select id="test"><option value="yes">Yes</option>' +
'<option value="no">No</option></select>');
// Bind the change handler (chose '.on' after reading the documentation for '.delegate')
$this.on('change', '#test', methods['handler'].call($this, $('#test').val()));
},
handler : function( content ) {
alert ('You chose: ' + content);
}
};
$.fn.testbed = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist' );
}
};
})( jQuery );
I know that the handler itself is working, because I can substitute
function(){ alert ("You did it!");}
for the function call, and it works.
But, the way I'm calling the function now doesn't work. It's how I call other functions from within other methods, but it doesn't work with a handler.
So, my questions are: (1) How do I make it call the function? and (2) is this the best place to set up the handler?
An id should be unique in the page. Having several elements with the same id will give you a different element from what you think when you try to access it. Don't use an id at all, use this in the callback to get the right element.
There is no reason to create a delegate when you are creating one for each event. Bind the event on the select element directly.
The handler for an event should be a function, not the result of a function call.
init : function( options ) {
// Add an element
this.append('<select><option value="yes">Yes</option>' +
'<option value="no">No</option></select>');
// Bind the change handler
$('select', this).on('change', function() {
methods['handler']($(this).val());
});
},

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;

Resources