How to call a controller action using Javascript $.get - Yii? - javascript

So, recently I've been trying to call a controller action via javascript $.get. I was suggested by a fellow Stack Overflow member to use
$.get("custom/balance", function(){ });
Where custom is the name of the controller that I am using and balance is actionBalance()—a function that I have declared inside of that controller. I have tried to do so but it seems that the function is not being called. I have placed intentional errors inside of that function so I am sure it is not being called via the $.get function.
previously, I had directed $.get to a file in assets like so
$.get("assets/balance.php, function() { });
This had worked perfectly.
Finally, here is the actionBalance that I have declared - is it possible that I need to then call that function? I'm not sure why custom/balance is not calling the action itself.
public function actionBalance() {
// Return a string
echo '7000';
}

I apologize for the previously incomplete answer which left you confused, as I assumed everyone would want to remove the index.php script name from the URL.
If you are using the default settings, yes, you should add the index.php?r= before the path. index.php is called the entry script in Yii. Other files are hidden/protected from the public in the protected folder.
To hide this entry script from the URL, please follow this tutorial on Yii's website:
Yii 1.1: Url: hide index.php

Related

Call a Javascript form within a controller in MVC4

I want to call a javascript function from within a controller function that I use:
Public Function redirectTo() As JavaScriptResult
Return JavaScript("ToSignUp()")
End Function
in my controller. But the program never goes to the script. I've already checked similar answers but I haven't found any solution to the problem. Can someone assist me with this?
ADDITION 4/3/19 12:41
I use the following for redirection from my controller... but nothing is happening:
Public Function redirectTo() As RedirectToRouteResult
Dim routes As New RouteCollection With {.RouteExistingFiles = True}
Return RedirectToAction("../login/SignUp")
End Function
End Class
ADDITION 4/3/19 23:20
The issue was solved by this way
In the code behind of my .aspx Page and at the proper place I add it the following code:
Dim routes As New RouteCollection With {.RouteExistingFiles = True}
Response.Redirect("SignUp")
The Response.Redirect instruction is not new.
But in order to be functional it needs to add before the following instruction
Dim routes As New RouteCollection With {.RouteExistingFiles = True}
And that is because the MVC did not recognize the existent files which means the property RouteExistingFiles is always False
Thus in order to work the code we need to turn this property to True
Anyway thanks to all for your assistance.
From other examples online (like this one), I would say that if you temporarily changed your function to:
Public Function redirectTo() As JavaScriptResult
Return JavaScript("alert("HERE");")
End Function
It will likely work... so without seeing the JS function contents, it's hard to tell. To the second point, a RedirectToAction call will work if called from the server; if the client is calling this, use 'window.location' instead.

How to resolve 404 error using CodeIgniter?

CSS and jquery does not applied in codeigniter. And it give
error 404 not found
I have tried to load all the class of bootstrap. I used css property.
I strongly suggest building yourself a helper for including your assets so you don't need to keep referring back by direct path with each asset.
You are calling within the controller not outside of it, when I call this stuff I tend to use site_url() and call directly to the public assets folder from this, eg:
siteurl('assets/css/style.php')
This would find, for example: http://localhost/assets/css/style.php
an example of using this in a helper would be a function like:
function assets($var)
{
$CI =& get_instance();
$CI->load->helper('url');
return site_url('assets') . '/' . $var;
}
With this and the helper autoloaded, you could then just call assets('path/inside/assets/folder/')
Use ../../../img/your_imgName in your CSS file

Call Javascript Function before Razor calls my HTML Helper

I've been working on a HTML helper which will hide or show menu items depending on what type of user you are.
For this reason, In one of my controllers I am setting a session variables with values such as "ADMIN"
context.Session["perfil"] = "ADMIN"
The problem I am facing is that the Helper function is being called before the Javascript function which calls the controller that sets the session variables
This is how I call my HtmlHelper (through Razor)
#using XSiteManagerWeb.Helpers
#Html.Raw(Html.MiMenu("../Home/Configuracion", "Configuración"))
From my _Layout.cshtml
But before doing that I'm calling the function
<script type="text/javascript">ObtenerDatosSesion();</script>
Which calls a Controler method through Ajax
...
$.ajax({
url: "../Home/ObtenerDatosSesion",
....
Question: Why is the HtmlHelper being called before ObtenerDatosSesion(); even though I've put it before on the _Layout.cshtml ?
I've also tried calling in on window load doing this:
<body class="Fondoblue" onload="ObtenerDatosSesion();">
among other methods.
I noticed the Helper is being called before everytime after many debuggings. What I can't figure out is why that happens.
I wonder if it has anything to do with the Web.config line one has to put to use html helpers
<add namespace="XSiteManagerWeb.Helpers"/>
So to make it clear, I just want to make my "ObtenerDatosSesion(); method gets called before my html helper!
The razor helpers are executed server side, therefore they will be executed before any JS is rendered/executed on the page.
I would recommend moving whatever logic is in your ../Home/ObtenerDatosSesion endpoint to the same endpoint as ../Home/Configuracion. If it's going to be called more than once, you can put it in its own method.

Async Problems with jQuery & Javascript

I'm going round in circles and can't seem to figure out a solution from the resources currently available here on Stack or Google. There's got to be something obvious that I'm missing, perhaps you might be able to help?
Story summary:
A javascript function launches when clicked and creates a new contact in our database.
Additional functions are then called upon successful creation to toggle some settings where necessary, dependant on a few checkboxes.
Calls are currently being made asynchronously, resulting in only the last function call to successfully update the contact.
I can't, for the life of me, get the call to work one after the other instead.
Each call returns a JsonResult upon successful completion, if that helps at all (needed for other areas of the application.
Code currently looks like:
function CreateClicked(){
Contact.Create(**bunch of params**, function(data){
if(data.success) {
togglePrimary(data.newId);
toggleBilling(data.newId);
toggleTechnical(data.newId);
toggleBalance(data.newId);
toggleSecurity(data.newId);
toggleMarketing(data.newId);
Modal.Load(**loads a modal view**);
}
}
}
The toggle functions then look like:
function togglePrimary(id) {
if ($("#contact_admin_primaryrole").prop('checked'))
{Contact.TogglePrimaryRole(id);}
}
Which calls a controller function that looks like this:
public JsonResult TogglePrimaryRole(int contactId){
try{
var c = new Contact(contactId);
c.IsPrimaryContact = !c.IsPrimaryContact;
c.Update(AuthenticatedUser.Username, !c.IsPrimaryContact);
return Json(JSONResponseFactory.SuccessResponse("Contact updated successfully"));
}
catch (Exception ex){
return Json(JSONResponseFactory.ErrorResponse(ex.Message));
}
}
How should I go about setting this up so that each toggle function doesn't start until the previous one has finished and returned a Json response, regardless of success?
Any ideas?
Cheers,
Dez
Using jQuery promises should help:
togglePrimary(data.newId).then(toggleBilling(data.newId)).then(toggleTechnical(data.newId)
etc.
This will run the next function only if the last one was a success. If you want to call the function irrelevent of the outcome then use always() instead of then()
togglePrimary(data.newId).always(toggleBilling(data.newId)).always(toggleTechnical(data.newId)
This will require jquery 1.6 or higher to be referenced. To reference from the CDN add the following
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
I couldn't seem to get anywhere with promises, or javascript function chaining with callbacks... so I turned the values of each status into an array of strings and parsed it within the controller instead!
Thanks for helping :)

jQuery page-flip animation

I am using a pageflip script called Moleskine Notebook. Inside the jquery.booklet.1.1.0.js file there is a function called next which turns the page. I want to call this function from my html file.
I tried "$mybook.next();" but it didn't work, I think I have to do something with jQuery.data() as it states on jquery.booklet.1.1.0.js file (lines 100-103)
//store data for api calls
b.data('booklet',true);
b.data('id', id);
b.data('total', src.children().length);
Here is the script:
http://tympanus.net/Tutorials/MoleskineNotebook/
Read the API docs:
$('#mybook').booklet('next');

Categories

Resources