Phpfox implement autocomplete with ajax - ajax

I have this in my javascript file
$("#searchPlaces" ).autocomplete({
source:function( request, response ) {
$.ajaxCall('mymodule.getcities', 'startsWith='+request.term);
},
autoFocus: true
});
And this is in my ajax php file.
public function getcities(){
$cities = array("1" ,"2", "3", "4");
$this->call(json_encode($cities));
}
It returns the array as json just fine, but nothing shows up in the autocomplete field.
Would anyone know how to accomplish this task in phpfox using the ajaxCall function?
Thanks.

So I was able to get around the issue. The issue is autocomplete needing the response specified. ajaxCall doesn't have a real callback on success, so there is no way to set the response with the data that gets returned. I decided to go a round about way and set everything manually. This is what I came up with.
include\component\controller\mycontroller.class.php
$this->template()->assign(array('token' => Phpfox::getService('log.session')->getToken());
template\default\somehtml.html.php
<input id="security_token" type="hidden" name="phpfox[security_token]" value="{$token}" />
static\jscript\myjavascript.js
$("#searchPlaces" ).autocomplete({
source:function( request, response ) {
$.ajax({
url: "/static/ajax.php",
minLength: 1,
dataType: "json",
data: {
startsWith: request.term,
'core[security_token]': $("#security_token").val(),
'core[ajax]': true,
'core[call]': 'mymodule.myfunction'
},
success: function( data ) {
response( data );
}
});
},
autoFocus: true
});
include\component\ajax\ajax.class.php
public function myfunction(){
$yourdata = array("1" ,"2", "3", "4");
$this->call(json_encode($yourdata ));
}
Basically the security token is set via a hidden element. The url will always be url: "/static/ajax.php", as this will take care of calling the ajax file for you. 'core[call]': 'mymodule.myfunction' this is set to how you would use $.ajaxCall('mymodule.myfunction'). All you need to do is find the autocomplete items you want to return as normal now.
Hopefully this helps in case someone else gets in the same situation.

The default phpfox $.ajaxCall actually returns a jQuery jqXHR object.
So, instead of rebuilding the entire ajax call manually, one could still use phpfox's $.ajaxCall and set the autocomplete response inside the .done() promise callback:
$("#searchPlaces" ).autocomplete({
source:function( request, response ) {
$.ajaxCall('mymodule.getcities', 'startsWith='+request.term)
.done(function( data ) {
response( $.parseJSON(data) );
});
},
autoFocus: true
});
Note that the $.ajaxCall ajax request uses 'script' as dataType, so you need to do your own parsing of the returned string, in this case it's a json string and $.parseJSON() will do the trick.

Related

How to fetch ajax request data in cakephp 2 controller?

I'm trying to send some data from my view to my controller via ajax. How do I retrieve this data in my action?
I've tried jQuery's $.ajax and $.post methods, providing the url and data, but using $this->data, $this->request->data, $_POST, $_GET or $_REQUEST doesn't work (all return as empty arrays).
$.ajax({
url: "<?php echo Router::url( array("controller" => "Progression", "action" => "submit", $user['User']['id']) ); ?>",
type: 'post',
data: { name: "John" }
}).done( function(data) {
console.log(data);
});
function submit() {
$this->request->allowMethod('ajax');
$this->autoRender = false;
$data = array();
$data['answer'] = $this->request->data; // or any of $_POST, $_GET, etc.
return json_encode($data);
}
My console always keeps printing {"answer":[]}. I checked the network tab of my devtools and the data is successfully listed under Form data, yet I can't seem to get hold of the data in the action.
EDIT:
Thanks to Greg Schmidt I found out that my request indeed got redirected: first it gives me a 302, then it makes a new request without the post data and returns a 200. I just can't find what the critical difference is between the two requests (URLs look the same, no case difference or anything). Can anybody help me with that?
First request:
Second request:

replacement for async:false in $.ajax

I have a form that submits data to the database and then gets submitted to google docs.
I am using jquery ajax to achieve this.
javascript:
var name ="a";
var company = "b";
var phone = "1";
...
$.ajax({
async: false,
url: "view/templates/includes/abc.php",
//type: 'POST',
//timeout: 10000,
data: {
"name": name,
"company": company,
"phone": phone,
"email": email,
"comments": comments
},
success: function(data) {
//called when successful
alert(data);
//alert('success');
$('#php-code').html(data);
},
error: function(e) {
// alert(e.message);
//called when there is an error
//console.log(e.message);
}
});
return true;
}
abc.php is where lies my code to insert data into the DB.
Now the issue is I don't wanna use async:false since I read it should never be used because it may cause browser hangs and it destroys the purpose of using ajax. However, if I dont use async:false the form gets submitted before my ajax response comes and so it always goes to the error function.
What could I do to not to use async:false?
You may calling ajax function on submit.
You may want to stop submitting form at your event(click of button may be).
And in the ajax success method, explicitly submit the form.
(can be done using jQuery - $('#id_of_form').submit())
EX. can follow the steps,
$('#id_button_submit').click(function(event){
// this will prevent form to be submitted
event.preventDefault();
// call the function of ajax
serviceCall();
});
In the success method of ajax
success: function(data) {
$('#id_of_form').submit();
// rest of your code
},
Or A jQuery plugin http://malsup.com/jquery/form/#ajaxSubmit may be useful to you

MooTools: How do package data for a POST ajax request?

I'm using MooTools 1.4.1. I want to create an ajax post requst, but I can't figure out how to construct the "data" attribute, which I wish to contain the name value pairs of a form whose id is "myForm".
$('save').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'save',
data: { ... },
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
});
});
Anyone know how I should populate the "data" attribute? Thanks, - Dave
You can use
$('myForm').toQueryString();
Alternatively, The MooTools More package has a Form.Request() class to send a Form using Ajax.
As Savageman commented, you can throw your form element into toQueryString() and send it through in the data property, or by running .send() or .post() on the request object.
You also seem to be missing a closing squiggly bracket.
Anyhow, this is how I make AJAX requests:
new Request({
url: 'http://url/to/ajax/script.php',
onSuccess: function(data) {
doStuff();
}
}).post('action=foo&bar=baz');
I'd recommend you use Request.JSON if you're planning on sending stuff back. It's less "shotgun approach"-ey.
You can just pass form element to "data" property, and conversion is automatic.
var req = new Request({
method: 'post',
url: 'example.com/form.php',
data: $('myForm'),
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
}
});
data - (mixed: defaults to '') The default data for Request:send, used when no data is given. Can be an Element, Object or String.
If an Object is passed the Object:toQueryString method will be used to convert the object to a string.
If an Element is passed the Element:toQueryString method will be used to convert the Element to a string.
http://mootools.net/docs/core/Request/Request

How can I manipulate an Ajax response before it's injected into the DOM?

Here is what I have so far:
$(function () {
dataValModify('body');
$('body').bind('ajaxSuccess', function (e, xhr, settings) {
dataValModify(xhr.responseText);
});
});
function dataValModify(elem) {
// Code to modify elements within the response.
}
How can I take the Ajax response and modify it before it is injected into the DOM? Previously, I was binding ajaxComplete and modifying the DOM directly after injection, but I would like to modify the response instead. I don't think it makes a lot of sense to find elements in the Ajax response and use them to modify the DOM. I send the xhr.responseText into my function so that I don't reapply the modifications to the rest of the body, which will have already been modified by the time of an Ajax call. Also, is there something better than xhr.responseText to use for this? I couldn't get xhr.responseHTML to work.
EDIT: Right now I'm just using a simple test Ajax call to return an MVC partial view:
$('#ajaxTest').load('<MVC Route>')
If I'm understanding your requirements correctly, they are as follows:
Make an asynchronous HTTP request to get some HTML
Modify the returned HTML using the dataValModify() function
Insert the modified HTML into your element with the ID: 'ajaxTest'
If so then it sounds to me like you need to make a lower level ajax call than what you're using at present i.e. $(elem).load()
Essentially the call to .load() is a wrapper for $.get() followed by a call to $(elem).html(someContent) where "someContent" is the responseText from the HTTP request.
Therefore if you want to modify the response before it's injected into the DOM, then you can do something similar to the following:
$.ajax({
type: "GET",
url: "<MVC Route>",
dataType: "html",
success: function(jqXHR, textStatus, errorThrown){
// Your HTTP call was successful but nothing else has happened with the response yet
// Therefore you can now do whatever you want with the it...
// First modify the HTML using the dataValModify function
// Assumption being that your function returns the modified HTML string
var myModifiedHTML = dataValModify(jqXHR.responseText);
// Inject the modified HTML
$('#ajaxTest').html(myModifiedHTML);
}
});
You can use ajaxComplete to modify the responseHTML itself.
$('body').ajaxComplete(function(e, xhr, settings) {
dataValModify(xhr.responseHTML);
});
Update: I haven't tried it, but it might help:
$.ajaxSetup({
converters: {
"text html": function( textValue ) {
if ( valid( textValue ) ) {
// Some parsing logic here
return dataValModify(textValue );
} else {
// This will notify a parsererror for current request
throw exceptionObject;
}
}
}
});
More info here: http://api.jquery.com/extending-ajax/

Set ajax request in joomla using mootools

I am having a prob for ajax request in joomla using mootools.
var url = '<?php echo JURI::base();?>index.php?option=com_test&task=getselectmode&selectedid='+$('parent_question').value;
var params ={method: 'post',update:'test'};
var myAjax = new Ajax(url, params);
myAjax.request();
My prob is that, is there any to set onComplete event of the ajax request.
i have set it as below on above code but nothing happen.
onComplete: function(response) { alert('Response: ' + response); }
Can you please provide full code of how to use ajax using mootools 1.1 ??
Thanks in advance
just add the onComplete to the params object, no need to add the event seaprately. also, you can use this.response.text. it can all look a bit more compacted - depends on your preference. if you don't plan on reusing the object, just call it direct and don't assign it to a variable either:
new Ajax(url, {
method: "get",
update: $("someelement"),
onComplete: function() {
alert(this.response.text);
}
}).request();
if you do something with the response text, you may want to remove the update: bit. if you need to evaluate the response (as javascript), use evalResponse: true instead of eval(this.response.text);. also handy - evalScripts: true|false if you want to do something from the server side along with the response.
This should work:
var ajaxObj = new Ajax ('index.php?option=com_yourcomponent&view=yourview&format=raw', {
method: "get"
});
ajaxObj.addEvent('onComplete', function (data) {
// data is the response text
// use as desired
});
// this initiates the call
ajaxObj.request();
maybe:
var a = new Ajax( url, {
method: 'post',
data: { parfoto: foto },
onComplete: function( response ){
..........
}
}).request();

Resources