Im new to MVC and I need to know How to invoke Action Methods from a view's buttons. And i need to clarify the difference between button and submit
Thanks
The buttons usually belong to a form tag. A form has a submit url. When the button <input type="submit" value="Submit"> is pressed you are redirected to the url written in form submit. Action Method is tied to a web page. For example if you go to www.eample.com/home/hello you execute Hello action in Home controller.
You can use jQuery to fire AJAX calls to specific pages (for example /home/process) and change the data on the page. To do that you should bind onclick javascript event on the button and there perform ajax call.
Example of AJAX call when page is loaded:
function loadContent() {
$.ajax({
type: 'get',
url: 'Page.html',
contentType: 'application/html; charset=utf-8',
dataType: 'html',
beforeSend: sendContent,
success: successContent,
error: errorContent
});
}
function sendContent() {
////loading
}
function successContent(data, status) {
$("#content .main").html(data);
$("#content").show();
}
function errorContent(request, status, error) {
////error
}
$(function () {
loadContent();
});
Related
In a custom prestashop module, I am trying to dynamically show children categories in a dropdown.
This is the code I add in the hook before calling the template:
$subcatObj = new Category("24");
$subcatObj2 = $subcatObj->getSubCategories($this->context->language->id);
$this->context->smarty->assign('seriesCategories', $subcatObj2 );
This is how I use this in the template:
<select id="series_dropdown" class="selectpicker" data-style="btn-primary">
{foreach from=$seriesCategories item=seriesCategory}
<option value="{$seriesCategory.id_category}">{$seriesCategory.name}</option>
{/foreach}
</select>
What I need is to invoke this getSubCategories with different values from JS, to dynamically populate the dropdown. So instead a hardcoded 24, I would like to use a JS variable.
$subcatObj = new Category(******** JAVASCRIPT VARIABLE *********);
$subcatObj2 = $subcatObj->getSubCategories($this->context->language->id);
What shall be done to achive this? -It is sort kind of AJAX web service-
Prestashop 1.7.1
You need create a php file in your module to handle the ajax request, eg:
/modules/your_module/ajax.php
<?php
require_once(dirname(__FILE__).'/../../config/config.inc.php');
$subcatObj = new Category((int)Tools::getValue('id_category'));
$subcatObj2 = $subcatObj->getSubCategories((int)Context::getContext()->language->id);
die(Tools::jsonEncode($subcatObj2));
Now in JavaScript inside the .tpl, or by a .js file loaded there:
$.ajax({
url: '/modules/your_module/ajax.php',
type: 'POST',
dataType: 'JSON',
data: { id_category: $('#series_dropdown').val() }
})
.done(function(data) {
console.log(data); // 'data' should contain the response of corresponding sub-categories
})
.fail(function() {
console.log('An error has occurred!');
});
PD. This is a basic example, you should add some security token in the ajax.
I'm using the Twitter Bootstrap modal as a login window, and would like it remains open if user put wrong login info. My Page refreshed after submitting the form.Is there a way after refresh page modal open again and I an show the message there that Login Failed:Please try again.
You will have to trigger the modal when there is an error after a post back.
You could have the server print out some javascript to trigger the modal after a post back ONLY on an error condition. You didn't mention what server side technology you are using, so here is some psuedo server side code:
if (hasAuthenticationErrors)
<script type="text/javascript">
$('#myModal').modal('show');
</script>
end if
That bit of javascript would have to be rendered AFTER the modal is initialized with a show:false option
$('#myModal').modal({ show: false})
see: How can I trigger a Bootstrap modal programmatically?
The scenario is certainly possible, but not even necessary. You should use the preventDefault in order to withhold the form from submitting the page. That is, if you use AJAX, which looks to be the perfect place for it.
An example would be
$(function () {
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
});
I am trying to dynamically retrieve the url after clicking on an item in a list.
The objective is to open the html page corresponding to clicked element.
Here is the code used:
Ext.define('FirstApp.view.Details',{
extend:'Ext.Panel',
xtype:'details',
requires: ['Ext.Ajax'],
config: {
listeners: {
activate: 'onActivate'
},
url: 'MyHtml.html' // Work fine if statically
url: '{link}', // But this doesn't work dynamically
tpl:'<h1>{link}</h1>' // However the desired data is displayed right here
},
onActivate: function(me, container) {
Ext.Ajax.request({
url: this.getUrl(),
method: "GET",
success: function(response, request) {
me.setHtml(response.responseText);
},
failure: function(response, request) {
me.setHtml("failed -- response: " + response.responseText);
}
});
}
Do you have an idea?
Thanks in advance for your help.
{link} works in tpl because the tpl property handles the string like an XTemplate. Your (custom) url property is just handled like a string.
Where exactly is {link} coming from? Since you are using a standard panel, I can only assume you are setting the data property on the panel with this link value. If so, just set the url at the same time via setUrl. Otherwise add a listener on updatedata, so that whenever your template data changes the listener is called and you can update the url.
i want to create very simple sample to uploading a file by client side in mvc4 by jquery and java script.
i Google it and found many samples and many plugins on internet but i prefer to do not have any dependency on any extra plugin or library like "uploadify"
for this i create a simple mvc4 application and in my view i attach my script file that contains method bellow until user click a button on this view start to uploading.
i do not know how to change bellow method to pass file to controller(in client side) ?
function uploadimage() {
$.ajax({
url: "/Uploader/FileUpload",
type: 'POST',
dataType: 'json',
data:null,
contentType: 'application/json; charset=utf-8',
success: function (msg) {
},
error: function (xhr) {
}
});
}
in my view
<input type="file" id="fileToUpload" name="file" />
<input type="button" value ="Upload" onclick="uploadimage()"/>
my controller
public ActionResult FileUpload(HttpPostedFileBase file)
{
//do somethings with file
}
file upload is not possible through ajax. You can upload file, without refreshing page by using IFrame.
I am preparing a mvc 4 application and I am pretty new to it. I would like to implement a functionality like by double clicking a row of mvc 4 webgrid I should call an action method in ajax. But unfortunately I could not find how to implement double click on mvc 4 web grid.
Can you please help me on that?
You could use the .dblclick() event in jQuery. For example:
<script type="text/javascript">
$(function() {
$('table td').dblclick(function() {
$.ajax({
url: '#Url.Action("SomeAction", "SomeController")',
type: 'POST',
success: function(result) {
// do something with the result from your AJAX call
}
});
});
});
</script>
Obviously there are lots of improvements that could be done to this code. For example you could use HTML5 data-* attributes on your grid to specify the url to the controller action that needs to be invoked and then externalize this script in a separate javascript file. You might also need to adjust the jQuery selector to match your WebGrid element.