Dropzone in Codeigniter url not used? - codeigniter

I'm using Dropzone in Codeigniter. I can see in Chrome's Network inspector that the URL is picked up (it sends a request to the URL), but it seems that the upload function in the controller is not executed.
Whatever URL I put in the Dropzone config, the Network inspector always indicates that it returns a HTTP 200 code.
View
<div class="dropzone" id="my_dropzone"></div>
Javascript
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone('#my_dropzone', {
paramName: "file",
url: '/pretty/url/upload-photos',
}
Note; whatever URL parameter I put here the Network inspector always indicates that it returns a HTTP 200 which is weird to me. Even if I put a non-existing URL like /asdfasdf.
With CodeIgniter I'm used to working with pretty URLs in AJAX and then mapping them to a controller in the routes config, this always works fine.
I've also tried directly putting the path to the function and controller as the URL parameter, like url: /folder/subfolder/Edit/upload_photos. This doesn't work as well.
In config/routes.php
$route['/pretty/url/upload-photos'] = '/folder/subfolder/edit/upload_photos'
In the controller 'Edit.php' (that's located in application/folder/subfolder)
public function upload_photos()
{
echo 'test 1';
if(!empty($_FILES)) {
echo 'test 2';
var_dump($_FILES);
}
}

Related

Do I sent two requests to the ActionResult?

I have an ASP.net MVC project and depending on the filter options chosen by the user I am sending different ajax requests to the same actionresult, for example:
$(document).on("click", "#filter_reset_button", function () {
var url = "/Admin/Index";
ajaxRequest({
url: url,
type: "get",
data: { reset: true },
successCallback: function () {
window.location.href = url;
}
});
});
Other listeners sent different data, something like:
data: { page: 2, filterUpdate: true }
and so on. The Index ActionResult returns different lists of items, depending on different options chosen in the data and the code works completely fine.
A colleage of mine told me, that my code is actually sending two get requests to the AR everytime, so its not efficient. Is that true? And if its the case, how can I refactor it. to make it just one request? If I let window.location.href = url part out, the site actually doesnt load the server response.
Yes you are doing 2 request in button click. First in Ajax Get, Second in Success Call Back.
But Why are you calling window.location.href = url; success call back. ?
If you want update the page after click, you can do partial updates to page. Check this post.
That is correct 2 request called.
First request when you call AJAX get to Action Index in Admin Controller.
Second request when you set window.location.href = url, it will same as you enter /Admin/Index in browser.
In this case you only need window.location.href = '/admin/index?reset=true' in click function
You can see the post here at this post
Actually on success callback you must change your code accordingly to the above post

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

Laravel: controller not teletransporting me (redirect-ing me) to the page

from Ajax the controller does get the keyword I want, as it confirms it (because I echo it), and my idea was that on getting that keyword, it should redirect to the page I want. Yet, it does not, and also, while it does change the locale, I have to reload the page, otherwise, it won't show any translation and locale changes on the page. In Firebug when I hover over the POST, I get the correct URL to where I would want to go: sort of http://myweb.com/es but the controller does not change the http URL box of my browser on my web to go there.
I am simplifying the Controller code here, but actually I will want it to go to different URLs depending on the keyword it gets, something that I would do with a switch statement or IF else if etc.
So the controller is as simple as this:
public function changelanguage()
{
$lang = \Input::get('locale');
echo "I got $lang";
Session::put('locale', $lang);
return redirect('/es');
}
If instead of using ajax I use a Form, then I dont need to reload, the Action of the form makes the controller change the locale and translate the page without reloading. But I need to use ajax and in any case, the controller does get correctly the keyword ('en', 'es', 'de' etc ) for languages, so it should take it from there and redirect me to the URL page, but it just doesnt move.
if you are curious about the Ajax, here it is, but it does send the keyword as I said.
$(document).ready(function(){
$('.choose-language').on('click', function(e){
e.preventDefault();
var selectedlanguage = $(this).data('value');
$.ajax({ // so I want to send it to the controller
type:"POST", // via post
url: 'language',
data:{'locale': selectedlanguage},
}); // HERE FINISHES THE $.POST STUFF
}); //HERE FINISHES THE CLICK FUNCTION
}); // HERE FINISHES THE CODE
ROUTES
Route::post('language', array(
'as' =>'language',
'uses' => 'LanguageController#changelanguage'
));
If you’re trying to perform the redirect in the AJAX-requested script, then it won’t work. You can’t redirect from a script request via AJAX otherwise people would be doing all kinds of nefarious redirects.
Instead, set up a “success” handler on your AJAX request that refreshes your page if the request was successful. It can be as simple as:
var url = '/language';
var data = {
locale: $(this).data('value');
};
var request = $.post(url, data)
.success(function (response) {
// Script was successful; reload page
location.reload();
});
I’m not sure how you’re allowing users to select locales, but since you need a reload any way I think AJAX is pointless here. Just have a traditional form that submits the new locale to an action, set the locale in a session/cookie/whatever, and then redirect back to the referring page.

How to Use Relative URL in Ajax Post in MVC3

I have an Ajax post call written in a separate ".js" file which I call in multiple pages.
My code looks like this:
$.ajax({
url: '/MyVirtualDirectory/Controller/Action',
type: 'POST',
dataType: 'json',
....
....
})
Each time I change my virtual directory in my server, I'm required to change the code in "URL" to make my Ajax call working.
Is there any method that can make my code independent of my "Virtual Directory" name in IIS ..?
My application is MVC3.
Description
You should use the Url.Action method. But in your case, a seperate js file, you cant access this method. So i would create a javascript variable for each url in your view. Then you can use this variable in your js file.
UrlHelper.Action Method - Generates a fully qualified URL to an action method.
Sample
Your View
<script type="text/javascript">
var myUrl = '#Url.Action("actionName", "controllerName")';
</script>
<script type="text/javascript" src="yourJsFile.js"/>
Your js file
$.ajax({
url: myUrl,
....
})
Update
Another way is to store your url in a hidden field inside your view and get the hidden fields value inside your js file.
More Information
MSDN - UrlHelper.Action Method
I finally found a partial work around.
In my .js file i did some dirty coding like this:
var Path = location.host;
var VirtualDirectory;
if (Path.indexOf("localhost") >= 0 && Path.indexOf(":") >= 0) {
VirtualDirectory = "";
}
else {
var pathname = window.location.pathname;
var VirtualDir = pathname.split('/');
VirtualDirectory = VirtualDir[1];
VirtualDirectory = '/' + VirtualDirectory;
}
$.ajax({
url: VirtualDirectory/Controller/Action,
....})
The basic idea is I check the URL for localhost and port number. If both are there, it means that then I'm debugging in my local machine and so I don't need virtualdirectory in URL. If I'm running a hosted version then there won't be localhost and port number in my URL(provided I'm hosting on port 80).
And by this way when I run on my local machine while debugging the url will be only Controller/Action and while I host the URL will be VirtualDirectory/Action/Controller. It works fine for me now.
But please post if there is any other simple method.
I think it would be safer to declare a global Javascript variable and then set the variable for the first time, maybe when Home/Index fires. and then reuse it in every ajax calls like so:
$.ajax({... url: GlobalVariablePath + "Controller/Action/RouteValues" ...})
if you already designed your WebApp and every thing works fine and stuck when site is deployed, then you can manipulate the all ajax URLs like so:
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
settings.url = GlobalVariablePath + settings.url;
}
});
Using this way, you can safely use the existing js codes and leave the rest without change.

Spring MVC and Ajax Operation using JQuery

I have a JSP page called CreateProcessGroup.jsp and I use an annotation controller to map requests to CreateProcessGroup.htm to that page. But I'm having an interesting issue when I request the page from browser it works, when send a request using jQuery $.get method I get 404 (CreateProcessGroup.htm not found) is there a difference between two requests?
My JSP page just under WebContent dir and JS file under WEBContent/Jquery my function sending the request like below:
function SendCreateProcessGroupRequest()
{
var pid = $('#pid').val();
var description = $('#processGroupDescription').val();
var x = "/CreateProcessGroup.htm";
alert(x);
$.get(x, { pid: 62, description: description },
function(data){
alert("Data Loaded: " + data);
});
}
Do I need to give the URL as ../CreateProcessGroup.htm? Indeed I tried:
/CreateProcessGroup.htm
../CreateProcessGroup.htm
/../CreateProcessGroup.htm
../../CreateProcessGroup.htm
/../../CreateProcessGroup.htm
My guess is DispatcherServlet can not map Ajax requests to Controllers but this is stupid isn't it?
How can i get rid of the situation?
Thanks all.
Try this instead:
var x = "CreateProcessGroup.htm";
If the page you're requesting is beside the one making the request there's no need for a path in front, it will (by default) make a request to the same path just with that page/handler on the end.

Resources