Controller Can Not Detect Ajax Requests

Controller can not detect ajax requests

I can not believe that I have lost so much time in trying to understand why the simple_form is not working as expected.

Finally, it appears that I have done everything in the right way and the issue was caused because:

AJAX can not be used for file uploads.

In order to solve my problem I simply have to add the following gem into my Gemfile and run the bundle install command:

gem 'remotipart', '~> 1.0'

Then add the following line in my application.js file:

//= require jquery.remotipart

More information about:

  1. remotipart gem
  2. How to upload multiple files using jQuery

My controller don't receive the IDs of an AJAX request

I changed my code based on a friend's code and it works. It's look like this:

namespace WebAppImaginario.Models
{
public class ItemCarrinho
{
public int idLivro { get; set; }
[DisplayName("Quantidade do Produto")]
public int qtdProduto { get; set; }
[DisplayName("Nome do Produto")]
public string nomeProduto { get; set; }
[DisplayName("Descrição do Produto")]
public string descProduto { get; set; }
[DisplayName("Preço do Produto")]
public decimal precProduto { get; set; }
[DisplayName("Desconto da Promoção")]
public decimal descontoPromocao { get; set; }
[DisplayName("Imagem")]
public byte[] imagem { get; set; }
}
}

Controller:

[HttpPost]
public ActionResult Carrinho(string hidCarrinho)
{
List<ItemCarrinho> listaCarrinho = new List<ItemCarrinho>();

if (hidCarrinho != null)
{
var itens = JsonConvert.DeserializeObject<List<ItemCarrinho>>(hidCarrinho);

foreach (var item in itens)
{
var qtd = int.Parse(new string(item.qtdProduto.ToString().Where(char.IsDigit).ToArray()));
if (qtd > 0)
{
var idLivroNumerico = int.Parse(new string(item.idLivro.ToString().Where(char.IsDigit).ToArray()));
var resultado = db.Produtos.Where(m => m.idProduto == idLivroNumerico).FirstOrDefault();
ItemCarrinho prod = new ItemCarrinho();
prod.idLivro = idLivroNumerico;
prod.qtdProduto = qtd;
prod.nomeProduto = resultado.nomeProduto;
prod.descProduto = resultado.descProduto;
prod.precProduto = resultado.precProduto;
prod.descontoPromocao = resultado.descontoPromocao;
prod.imagem = resultado.imagem;
listaCarrinho.Add(prod);
}
}
}

return View(listaCarrinho);
}

JavaScript:

function setValueEnviar() {
$("#hiddenInputContainer").empty();

for (var i = 0; i < carrinho.length; i++) {
var newInput = document.createElement('input');
newInput.type = "hidden";
newInput.value = JSON.stringify(carrinho[i]);
newInput.name = 'data';
$("#hiddenInputContainer").append(newInput);
}
}

$('#formCarrinho').submit(function (e) {
e.preventDefault();
$('#hidCarrinho').val(JSON.stringify(carrinho));
document.formCarrinho.submit();
})

Those IDs are a form on my page and hidden input. I don't know if it is clear, but it works to me.

Thank you for all support.

Ajax Request not accessing Controller, Laravel

There are at least 2 possible problems.

  1. Are you create it manually through your text editor or copied from another controller? if so, then I could suggest to composer dump-autoload your project so that it will renew its autoloaded files.

  2. Laravel's Controller uses different Request class than the one used in the routes.php file, so I also suggest when you to change if(Request::ajax()){ to if($request->ajax()){ in your controller method

Do let me know if one of these solution fixed your problem. If it still having problem, show the error message shown in your ajax result. Hope it answer your question.

Is there a way to detect why an Ajax call does not make it to a controller in MVC?

The issues of your request

  • Not correct data format somePara = "111" => JSON.stringify({ somePara: "111" }),

  • Did not defined dataType

    contentType: "application/json; charset=utf-8",
    dataType: "json",

  • Action did not return JSON format.

Controller action

  [HttpPost]
public JsonResult MyMethod(int somePara)
{
return Json("it worked", JsonRequestBehavior.AllowGet);
}

AJAX

 $("button#test").on("click", function () {

$.ajax({
type: "POST",
url: "/Home/MyMethod", // i try home controller
data: JSON.stringify({ somePara: "111" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Error")
}
});
});

Update: the action should change to MyMethod(int? somePara) to prevent somePara : "" cant cast to int.

Detect AJAX request in OpenCart Controller

actually OpenCart doesn't remove the $_SERVER vars. It just passes them to $this->server. The issue is that 'HTTP_X_REQUESTED_WITH' is only set if there was an AJAX call. Otherwise, it will give an error.

you can test if any of your requests have been made via AJAX by adding this code to file system/library/request.php on line 32

after $this->server = $this->clean($_SERVER); add:

if(isset($this->server['HTTP_X_REQUESTED_WITH'])){
echo '<script>console.log(' . json_encode($this->server['HTTP_X_REQUESTED_WITH']) .')</script>';
}

then open your OpenCart frontend and visit any product page and you should see in your Browser console XMLHttpRequest

like so
http://joxi.ru/MAjo6vWTjZZjBr

this is because on the product page the reviews are loaded via AJAX. On homepage there are no AJAX calls, so you shouldn't see anything in the console.

I hope this helps.

Ajax request not passed to controller

It is because variable httpRequest should be defined outside getStates() function. Otherwise processRequest() cannot see it.



Related Topics



Leave a reply



Submit