How to initiate controller/action in CFWheels, for Ajax? - javascript

I have been trying to get cfwheels to work with FineUploader for two days now, and I just can't figure out how to force the jQuery script to execute a Controller/Action. This is how far I've come so far:
$(document).ready(function() {
var restricteduploader = new qq.FineUploader({
// Since we're using jQuery, use the jQuery way to select the HTML element
element: $('##restricted-fine-uploader')[0],
request: {
type: "POST",
url: $(this).attr("href") + "/index.cfm?controller=users&action=UploadFileXhr&format=json", // References "/say/hello?format=json"
dataType: "json",
endpoint: '/index.cfm?controller=users&action=UploadFileXhr&format=json'
},
multiple: false,
validation: {
allowedExtensions: ['jpeg', 'jpg', 'txt'],
sizeLimit: 5120000000 // 50 kB = 50 * 1024 bytes
},
text: {
uploadButton: 'Click or Drop'
},
showMessage: function(message) {
// Using Twitter Bootstrap's classes and jQuery selector and method
$('##restricted-fine-uploader').append('<div class="alert alert-error">' + message + '</div>');
},
debug: true
});
});
The CFWheels documentation says I have to use this to get an asynchronous request:
(function($){$(document).ready(function(){
// Listen to the "click" event of the "alert-button" link and make an AJAX request
$("#alert-button").click(function() {
$.ajax({
type: "POST",
url: $(this).attr("href") + "?format=json", // References "/say/hello?format=json"
dataType: "json",
success: function(response) {
$("h1").html(response.message);
$("p").html(response.time);
}
});
return false; // keeps the normal request from firing
});
});})(jQuery);
These three lines is what I'm trying to incorporate into my code (because that's what I think I need):
type: "POST",
url: $(this).attr("href") + "?format=json", // References "/say/hello?format=json"
dataType: "json",
But everything I've tried has not worked. I can't even work on my actual upload code to get that to work, since I can't even get the uploader to initiate the required controller/action.
Hopefully someone will be able to point me in the right direction. Thank you!
Question also posted to cfWheels mailing list: https://groups.google.com/forum/?fromgroups=#!topic/cfwheels/UKk_57y9ncQ

I'm not familiar with FineUploader, but normally when I am doing AJAX requests in Wheels, I use the urlFor() function to build the correct controller/action location.
CFWheels - urlFor

I think I know what problem you're facing. Follow these steps:
Make sure in your controller Say.cfc provides the JSON format to the Ajax call:
In the init() function of Say.cfc, make sure to add this:
<cffunction name="init" hint="It secures component from invalid access">
<!--- this is necessary --->
<cfset provides("json") />
</cffunction>
Now, in the hello action, render the data you want to provide without layout. Remove any <cfabort> tags present inside the action:
<!--- this will go at the very end of the action --->
<!--- here the attribute data is the data you want to serve: a query, struct or any other custom data generated inside a `<cfsavecontent>` --->
<cfset renderWith(data=data,layout=false) />
I hope this works for you.

Related

JSON call giving value that is not actually in the .json file

I am a little new when it comes to JSON and Javascript , so please excuse me if if this is a stupid question, but I have run into a problem that is starting to drive me insane.
On a webpage I am including two scripts; jQuery and a file called "scripts2.js". In the same directory as scripts2.js, I have a JSON file; "settings.json". From within my "scripts2.js" file I am running he following code inside of a function.
var settingsPath = settings.json;
jQuery.getJSON(settingsPath, function (data){
jQuery.each(data, function(index){
console.log("!"+data[index].name);
/*unrelated other stuff */
});
});
Previously the settings.json file looked like this
[
{"name":"Standard Black"},
{"name":"Gold"},
{"name":"Silver"}
]
So naturally when I looked in the Chrome Dev Console the log would print out
!Standard Black
!Gold
!Silver
However, when testing what would happen upon editing my settings.json file I changed "name":"Gold" to "name":"Test".
[
{"name":"Standard Black"},
{"name":"Test"},
{"name":"Silver"}
]
After the json updates I tried refreshing the page but my console log is still printing out
!Standard Black
!Gold
!Silver
...
I am at a loss. I have no idea why the data being retrieved with jQuery.getJSON() is sending the data of my old settings.json even after the changes has been saved. I have perused my .php file (which is generating the HTML) , as well as my included javascript and there is no other mention of another json file or any sort of clone of my json file in any related directory.
I really have no idea what is going on and I am starting to go insane. Does anyone have an idea of what the issue might be?
I dont know if it matters but I am running a XAMPP stack on my localhost. All files (index.php, scripts2.js, and settings.json) are in a directory located inside XAMPP's htdocs folder.
EDIT: Thank you all for the speedy and thorough answers, many of you answered the question I was a bout to ask next. I really appreciate it!
This is because the browser is caching the file from your first request. Simply clear the cache and run it again and the new data will be retrieved.
UPDATE:
To prevent the browser from caching this file, change your AJAX settings like so:
jQuery.ajaxSetup({ cache: false });
Before you make the getJSON call
Try clearing web cache and restart local servers if you have not already
When using jQuery.ajax() instead of the shorthand method, you can disable caching like this:
jQuery.ajax(settingsPath, {cache: false})
jQuery will append a timestamp parameter to your request URL which changes with every request and therefore keeps the browser from caching the response.
To force the browser to get a new version each time you can use cache: false in jQuery.ajax()
$.ajax({
dataType: "json",
url: settingsPath,
cache: false,
success: function (data){
$.each(data, function(index){
console.log("!"+data[index].name);
});
}
});
Pass additional parameter to your requested url which value will change with every request.So,your browser will consider it as new request every time and will not cache the data.
var random = Math.round(new Date().getTime())
var settingsPath = 'settings.json&time=' + random;
jQuery.getJSON(settingsPath, function(data) {
});
});
You can use any algoritham that generate random new value everytime for random for every request.
OR
you can have same things with jQuery#Ajax method
jQuery.getJSON is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So, set the optional parameter cache to false (this value by default is always true):
$.ajax({
dataType: "json",
url: url,
data: data,
cache: false, // If set to false, it will force requested pages not to be cached by the browser
success: success
});
Therefore, your getJson becomes:
var settingsPath = settings.json;
jQuery.ajax({
dataType: "json",
url: settingsPath,
data: data,
cache: false,
success: function(data) {
jQuery.each(data, function (index) {
console.log("!" + data[index].name);
/*unrelated other stuff */
});
}
});

Codeigniter: Change languages on the fly (AJAX)

I am trying to work out how to change the languages on the fly using the Codeigniter Language System. So I made this ajax call which works but obviosly the values won't change until I reload the page unlease I somehow print out the values or set the variables in the function which is being called by AJAX ? What is the best way of doing this.
<script>
$(function(){
$('.lang-choices a').on('click' , function() {
var language = $(this).attr("data-lang");
$.ajax({
type: "POST",
url: js_site_url('langswitch/switchLanguage'),
data: "requestedLanguage=" + language,
cache: false,
success: function(html){
},
error:function(exception){alert('Exeption:'+exception);}
});
return false;
});
});
</script>
switchLanguage Function
public function switchLanguage()
{
$language = $this->input->post('requestedLanguage');
$this->session->set_userdata('site_lang', $language);
}
Your question is a little bit unclear so the assumption I'm making is that you're flipping a backend flag that changes the output from the server. Using that assumption, here's what I'd recommend in order of magnitude:
In your success handler, reload the page using window.location.reload(true). The true argument is essential since it makes a trip to the server to get new data. https://developer.mozilla.org/en-US/docs/Web/API/Location.reload
Your success handler seems to take html as an arg. I'm not sure if you're actually sending that based on your switchLanguage function or if that's leftover from copy+paste somewhere. If you are indeed getting HTML data and it's page data, I'd use the context option (http://api.jquery.com/jquery.ajax/) to filter down to the content of the document you're receiving then replace my page's content with this data
Here's an example of the latter:
$.ajax({
type: 'POST',
url: js_site_url( 'langswitch/switchLanguage' ),
data: 'requestedLanguage=' + language,
cache: false,
context: document.body,
success: function( html ){
// or similar
$( 'body' ).replaceWith( html );
},
error: function( exception ) {
alert( 'Exeption:' + exception );
}
});

Ajax request 'onError' handler

There is one feature on my site: delete without page refresh. The user just presses 'delete' and the browser will send Ajax-request. It will load 'delete' script with id parameter.
All work well. But it is not very good because of referential integrity of the database. For example, It is possible to delete street, where some people are living.
I want to upgrade my script. I want to add a check to delete script and don't let delete data if some 'people' are connected to 'street' table.
jQuery handler of button click:
$('body').on('click', '.deleteStreet', function()
{
var id = $(this).attr('id');
var hideMe = $(this).parent().parent();
var dataString = 'id=' + id;
if(confirm("Are you sure you want to delete street? It is possible some people living there!"))
{
$.ajax({
type: "GET",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
hideMe.hide();
}
});
return false;
}
});
It will call script anyway and now will delete data anyway. I can add some checks to delete script now and it wouldn't delete, but jquery script would work anyway and will hide table row anyway (because request was send ok, without 404, etc)
1) Is it possible to see delete script result and hide or not hide row depending on it? For example, it will return true or false, js script will catch it and show message about deleting or not deleting of data depending on it.
2) This problem caused by structure of my site. There are some switches on index.pl and load appropriate scripts loading depending on query (mode=street then load street.pl, mode=user then load users.pl etc). So it will show all data loaded before delete.pl script and it will be impossible to check script returned true or false.
Any help? :) Thank you!
P.S.: I am very sorry for my awful english.
You can have the result of your ajax call in the first parameter of the success callback. ex:
$.ajax({
type: "POST",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
if(e === '1'){
hideMe.hide();
}
}
});
try to log your result in the console for tests: console.log(e).
For deleting data you should use a POST request ( or DELETE but not supported by all browsers).
I dont know how your datas (streets) looks like but an other way could it be to return all your existing streets in a json object on the delete request result. And refresh all lines.

How can I post my href value in an ajax function?

I am trying to create an action that allows me to post an anchor href with an ajax call. Firstly the anchor tag is created with a backend set up so it cannot be inside a form etc so that is not going to work.
Here is the markup for the button, the href is added dynamically with js:
<a class="js-add-to-cart button buying-options buy-button" data-products-in-cart="<?= $products_in_cart ?>">
Select a size
</a>
I have currently got this code working which posts the anchor:
jQuery(function(){
jQuery('a.buy-button').click(function(event) {
event.preventDefault();
jQuery.ajax({
url: jQuery(this).attr('href'),
type: 'POST',
async: true,
beforeSend: function(){
jQuery('#result').hide();
jQuery('#ajax-loader').show();
},
error: function(xhr, status, thrown){
alert(xhr + ',' + status+ ',' + thrown);
},
complete: function(){
jQuery('#ajax-loader').hide();
},
success: function(data) {
jQuery('#result').empty().append(data);
jQuery('#result').fadeIn('slow');
}
});
});
});
It works but my only issue is that it basically does a get request and in the header network response I get this:
This does not post the add to cart url and make the product added to cart.
Does anyone know how this can be done?
Cheers,
Mark
try to see if the POST-action is actually triggered within the PHP code. It seems like it should be working.
Also the 'async' parameter is superfluous since you're already calling an A-jax function
perhaps using the .post() shorthand will help you (and also clean up your code).
I'm assuming that you are not using the $ alias for jQuery because you are not aware of it, and not because of any conflict issues.
$(function(){
$('a.buy-button').click(function(event) {
event.preventDefault();
$('#result').hide();
$('#ajax-loader').show();
$.post($(this).attr('href'), function (data) {
$('#ajax-loader').hide();
$('#result').empty().append(data);
$('#result').fadeIn('slow');
});
});
});

AJAX Load Content

Im completely lost on how to work AJAX. Looked up some tutorials and all seemed pretty confusing. I ran into the problem: [ Script only runs once ].
I would use it to reload pages like so: [ http://www.roblox.com/Poison-Horns-item?id=62152671 ] so I could get the latest item prices, without refreshing the page. if anyone could help/tell/point me in the right direction, it'd help TONS.
Im somewhat a beginner scripter, so be a little patient ;)
Thanks for any help,
Alex
AJAX requests are the same as page requests (GET and POST), except that they are handled asynchronously and without leaving the current page. The response data is the source of the page you wanted to fetch. That source is useless until you parse/use it.
A simple jQuery example:
//for example, we are on example.com
$.ajax({
type : 'get', //the METHOD of the request, like the method of the form
url : 'index.php' //the url to fetch
data : { //additional data which is synonymous to:
query1 : 'foo', // - url queries
query2 : 'bar', // - form inputs
query3 : 'baz',
},
success : function(resposeText){ //response text is the raw source of the fetched resource
$(element).html(responseText); //use response as HTML for element
}
});
//this is similar to requesting:
http://example.com/index.php?query1=foo&query2=bar&query3=baz
agree with joseph. You can use ajax by javascript manner or by jQuery, I personally suggest jQuery because it is simple to implement.
$.ajax({
type: 'GET',
url: "URL you want to call" ,
data: 'Data you want to pass to above URL',
cache: true, //to enable cache in browser
timeout: 3000, // sets timeout to 3 seconds
beforeSend: function() {
//when ur ajax call generate then u can set here loading spinner
},
error: function(){
// will fire when timeout is reached
},
success: function(response){
//in response you can get your response data from above called url.
}
});

Categories

Resources