how to call controller with jquery ajax magento - ajax

I have created custom module in magento, I want to access controller using jquery ajax but I am not finding correct method for doing this.
Ajax code in template is
jQuery(".deleteAttrKeyId").on("click",function(){
var baseUrl="<?php echo Mage::getBaseUrl();?>";
var idArr=this.id.split("-");
attrKeyId=idArr[1];
alert(this.id);
jQuery.ajax({
type: "POST",
dataType: "JSON",
data :{'id':attrKeyId},
url :baseUrl+"groupprice/adminhtml_grouppricebackend/index",
complete:function(){alert("completed");
},
success:function(result){
alert(result);
}
});
});
Block code in layout is
<groupprice_adminhtml_grouppricebackend_index>
<reference name="content">
<block type="groupprice/adminhtml_grouppricebackend" name="grouppricebackend" template="groupprice/grouppricebackend.phtml"/>
</reference>
</groupprice_adminhtml_grouppricebackend_index>
Controller code is
<?php
class Group_GroupPrice_Adminhtml_GrouppricebackendController extends Mage_Adminhtml_Controller_Action
{
public function indexAction()
{
echo __FILE__;
}
}

use this
<script type="text/javascript">
function callController(){
new Ajax.Request("<?php echo $this->getUrl('groupprice/adminhtml_grouppricebackend/index') ?>", {
method: 'Post',
parameters: {"parameter_name":"value"},
onComplete: function(transport) {
alert(transport.responseText);
}
});
}

add this code in phtml
<button type="button" onclick="callController()" title="submit" class="button">submit</button>
<script type="text/javascript">
function callController(){
new Ajax.Request("<?php echo $this->getUrl('module/controller/action') ?>", {
method: 'Post',
parameters: {parameter_name:value},
onComplete: function(transport) {
alert(transport.responseText);
}
});
}
</script>

Related

Ajax post calling wrong url

Good day.
I want to know why is my project calling the wrong url? The code is:
SCRIPT
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
CONTROLLER
public class ApplicationController : Controller
{
public ActionResult Franchise()
{
return View();
}
}
I even tried changing the url by 'Url.Action("Franchise", "Application")' but still the system kept on bringing me to http://localhost:49267/Home/Franchise.
I can't understand what is wrong here. Is there a bug in jquery ajax url post?
Thanks in advance.
UPDATE
<button class="btn btn-success" type="button" id="btnCapture">Submit</button>
#section Scripts{
<script src="~/Scripts/webcam.min.js"></script>
<script src="~/Scripts/webcam.js"></script>
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<script language="JavaScript">
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('results').innerHTML =
'<img id="base64image" src="' + data_uri + '"/>';
} );
}
</script>
<script>
$(document).on("click", ".open-camera", function () {
var myBookId = $(this).data('id');
$(".modal-body #franid").val(myBookId);
})
</script>
<script>
$(function(){
$('#btnCapture').on('click', function(){
var file = document.getElementById("base64image").src;
var franid = $("#franid").val();
var sendInfo = {
Imagee: file,
FranIDD: franid
};
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
});
});
</script>
}
This is all my code.
Ok. So I found my problem. It was in my controller.
In my controller I tried adding return RedirectToAction("Franchise", "Home"); after the save command. As soon as I commented this, everything worked.
Thanks for the help again guys.
Please use the browser to access directly, not from within the IDE directly access, from the localhost:49267 should be from the IDE access, and you will write URL as http://www.google.com try.

Codeigniter ajax pass variable class

My AJAX in view
<script type="text/javascript">
$(document).ready(function(){
$('.calendar .day').click(function(){
var day_data= $(this).find('.content').html();
if($(this).find('.content').html()!=null){
$.ajax({
url: "<?php echo base_url('calendar/pass_name')?>/",
method:"POST",
data:day_data,
success:function(data){
alert(data);
}
})
My controller
function pass_name(){
$name=$this->input->post('.calendar .day');
echo $name;
return $this->load->model('calendar_model')->get_description($name);
}
My model
function get_description($name){
$query=$this->db->select('description')->from('calendar')->where('name'==$name);
return $query;
}
What I would like to do is pass this variable through ajax, run a db query and return the result in a popup box.
Thanks in advance for any tips.
Try This code:
<script type="text/javascript">
$(document).ready(function(){
$('.calendar .day').click(function(){
var day_data= $(this).find('.content').html();
if($(this).find('.content').html()!=null){
$.ajax({
url: "<?php echo base_url('calendar/pass_name')?>/",
type:"POST",
data:{day_data:day_data},
success:function(data){
if(data==1)
{
$('#response').html(data);
}
}
})
</script>
Changer IN Your Controller
function pass_name()
{
$name=$this->input->post('day_data');
if($this->load->model('calendar_model')->get_description($name)==TRUE)
{
return 1;
}
}

ajax call with jquery asp.net mvc

I have a button with the class "btn" and span with id "ajaxtest". When I click on the button I want to put text "test" in my span tag. And this to be done in ASP.NET MVC.
In the View I have the following ajax call:
<span id="ajaxtest"></span>
<input type="submit" class="btn" name="neverMind" value="Test BTN"/>
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/MyController/MyAction",
dataType: 'string',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
In MyController I have the following code:
public string MyAction()
{
return "test";
}
I know how Ajax works, and I know how MVC works. I know that maybe the error is because we are expecting something like this in the controller:
public ActionResult MyAction()
{
if (Request.IsAjaxRequest())
{
//do something here
}
//do something else here
}
But actually that is my problem. I don't want to call some partial View with this call. I just want to return some string in my span and I'm wondering if this can be done without using additional partial views.
I want to use simple function that will only return the string.
Change dataType: 'string' to dataType: 'text'
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/login/MyAction",
dataType: 'text',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
I check it my local it will work for me

submitting an asp.net MVC 3 form using jquery ajax

I am working on ASP.NET MVC 3 application and I have a jquery dialogue with Ok button. On click of OK I want to submit a form using jquery AJAX.
My ajax call looks like this:
$("#free-trial").dialog({
autoOpen: false,
autoResize: true,
buttons: {
"OK": function () {
if (notvalid()) {
$(".ui-dialog-titlebar").hide();
$("#dialog-freetrial-insufficientdata").dialog({ dialogClass: 'transparent' });
$("#dialog-freetrial-insufficientdata").dialog("open");
}
else {
$('#frmCreateTrialAccount').live('submit', function (e) {
e.preventDefault();
$.ajax({
cache: false,
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (data) {
alert(data);
}
});
});
jQuery(this).dialog('close');
}
}
},
open: function () {
$('.ui-dialog-buttonset').find('button:contains("OK")').focus();
$('.ui-dialog-buttonset').find('button:contains("OK")').addClass('customokbutton');
}
});
where as form looks like this:
#using (Html.BeginForm("CreateTrialAccount", "Home", FormMethod.Post,
new { Id = "frmCreateTrialAccount" } ))
{
}
and controller action looks like this:
[HttpPost]
public JsonResult CreateTrialAccount(FormCollection form) {
return Json("dummy data");
}
but form is not submitted on this method.
I have these files included in layout page:
<link href="#Url.Content("~/Content/css/smoothness/jquery-ui-1.10.0.custom.css")" rel="stylesheet" type="text/css" media="screen"/>
<script src="#Url.Content("~/Scripts/jquery-1.9.1.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.10.2.custom.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Please suggest me solution to this.
Oh sorry for that comment I made, your issue is that you are binding the form's submit action where you should have been submitting it already. If you want to bind the form's submit then declare it outside $("#free-trial").dialog({. Then you can have the ajax post method in a separate function so you can call it in both the binding code and in the $("#free-trial").dialog({.
var form = $('#frmCreateTrialAccount');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data);
}
});
So just to make it clear remove the following lines of code:
$('#frmCreateTrialAccount').live('submit', function (e) {
e.preventDefault();
// and the ending
});

How to call ajax only once

I call function from this code :
<div id="header-button-news" class="header-button-info">
<div class="new">2</div>
</div>
My function is
function showNews()
{
//other js which show block
jQuery("#loader").show();
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function(data) {
jQuery('#top-info-news').html(data);
},
complete: function(){
jQuery('#loader').hide();
},
});
}
How can I make only once ajax call? so when content is loaded and page was not refresed not to load ajax? I tried to do boolean variables but nothing, I suppouse it is because I call everytime function. Please give me an idea how to do.
thank you
When you want to do something on that event.
Identify when you have already loaded your data.
var loaded = false;
function showNews() {
//other js which show block
jQuery("#loader").show();
if(loaded) return;
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function(data) {
jQuery('#top-info-news').html(data);
},
complete: function(){
jQuery('#loader').hide();
},
});
loaded = true;
}
Or use one. when you want to call it once.
jQuery('.showNews').one('click', function() {
// your code
});
"Attach a handler to an event for the elements. The handler is executed at most once per element."
reference
Use the .one() function :
Attach a handler to an event for the elements. The handler is executed at most once per element.
I have added an id attribute to the anchor to allow an easier bind, but you could use $("#header-button-news a").one
$(document).ready(function () {
$('#shownews').one('click', function (evt) {
evt.preventDefault(); // prevent default click action
jQuery("#loader").show();
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function (data) {
jQuery('#top-info-news').html(data);
},
complete: function () {
jQuery('#loader').hide();
},
});
});
});
Also used event.preventDefault() to prevent the default action on the anchor from being followed
<div id="header-button-news" class="header-button-info">
<a id="a_news" title="Новости"></a>
<div class="new">2</div>
</div>
In JS:
$(function(){
$('a#a_news').one('click',showNews);
})

Resources