0

I am sending a GET request. I process the data and get a link for the redirect. I understand that need to send it back to the client and move from it. The link comes valid. But for some reason, the function does not enter the is_ajax () block.

$(document).on('click', '.top_up_pay', function (e) {
  var post_data;
  e.preventDefault();
  var amount = +$('tr.sum > td.price > span.value').text();
  var products_id = [];
  var products_count = [];
  var products_deliv = [];

  $.each($('.name'), function(){
    var id = $(this).attr('data-product_id');
    products_id.push(id);
    var count = $(this.parentNode.parentNode.parentNode).find('input[name="count"]');
    products_count.push(count.val());
    var deliv = $(this.parentNode.parentNode.parentNode).find('.delivery');
    products_deliv.push(deliv.val());
  })

  var new_post = $('.new_post > input')
  var ukr_post = $('.ukr_post > input')
  var recipient = $('.recipient > input')
  var phone = $('.phone > input')
  var sum = $('tr.sum > td.price > span.value');

  var data = {
    products_id: products_id,
    products_count: products_count,
    products_deliv: products_deliv,
    new_post: new_post.val(),
    ukr_post: ukr_post.val(),
    recipient: recipient.val(),
    phone: phone.val(),
    sum: sum.text(),
    comment: comment,
    amount: amount
  }

  $.ajax({
    type: "GET",
    url: "/payments/top-up-pay/",
    data: data,
    crossDomain: true,
    success: function(data){
      window.location = data.redirect_to
    },
    error: function(data){
      alert('Error')           //Error
    }
  })
  setTimeout(function () {
    window.location.href = "/products/";
  }, 2000);

views

def top_up_pay(request):
    template = 'payments/top_up_pay.html'
    conf_currency = AppConfig.get_config('subscription_price_currency')    
    if request.method == "GET":
        global req_data
        req_data = get_request_data(request)
        amount = Decimal(req_data.get('amount'))
    if conf_currency:
        req_user = request.user
        invoice = Invoice.objects.create(
            invoice_type=INVOICE_TYPE.TOP_UP,
            user=req_user,
            amount=amount*100,
            currency=conf_currency
        )
        params = {
            "currency": invoice.currency,
            "amount": int(invoice.amount),
            'order_id': str(70),
            "operation_id": str(70),
            "order_desc": "payment",
        }
        integration = FondyIntegration(params)
        redirect_to = integration.checkout_url()
        if request.is_ajax():
            response = HttpResponse(json.dumps({'success': True, 'location': redirect_to}), content_type="application/json")
            return response
        else:
            return redirect(redirect_to)
    return render(request, template, ctx)

Response:

enter image description here

enter image description here

dirkgroten
  • 20,112
  • 2
  • 29
  • 42
  • not sure I understand what's happening. How do you know your view isn't entering the `if request.is_ajax()` condition? What is the response you actually get in your javascript success function? Note your return JSON sets a `location` not a `redirect_to` parameter. – dirkgroten May 20 '19 at 12:47
  • With the help of the debugger, I made sure that this block does not enter. –  May 20 '19 at 12:54
  • At the response I get error function. –  May 20 '19 at 13:07
  • then you don't get any of the paths of your view. somewhere your view is giving an error before reaching `if is_ajax()`. What does your django console show? – dirkgroten May 20 '19 at 13:10
  • And what should it give out? How to check? –  May 20 '19 at 13:20
  • in your browser console, network tab, XHR, you should see the actual response you get (what status? what are the http response headers). In your django console, you should see the request (GET), the status code returned (302 if redirect, 5xx/4xx if error) and if you're in debug mode a full error trace. – dirkgroten May 20 '19 at 13:27
  • Also `is_ajax()` works by checking that `X-Requested-With` header is set to `XMLHttpRequest`. jQuery sets this correctly when using `$.ajax()` so it should be there, but you might want to check it in your browser debug tools, network tab, XHR, check the request headers. – dirkgroten May 20 '19 at 13:29
  • Also since you say you're using a debugger with breakpoints in your python code, what happens when you set your breakpoint at the beginning of your view function and step through your code line by line? Where does it `return`? – dirkgroten May 20 '19 at 13:31
  • @dirkgroten Added request replies –  May 20 '19 at 13:34
  • And the most interesting is that the link is formed correctly (that is, when I copy-paste it into the address bar, the page opens). I just need to make it open automatically. –  May 20 '19 at 13:40
  • I don't see the `X-Requested-With` header in your request headers (is that all? does the box scroll further down after `User-Agent`?). So it looks like either your version of jQuery doesn't add it (i'm using 2.2.4 and it adds the header) or your browser is removing it which would seem odd. – dirkgroten May 20 '19 at 13:54
  • @dirkgroten Box doesn't the scroll further down after User-Agent. I'm use jquery 1.11. –  May 20 '19 at 13:58

2 Answers2

0

Perhaps use HttpResponseRedirect instead of doing it in the Javascript? and if you are sending Json, then use JsonResponse?

Octavio del Ser
  • 378
  • 1
  • 10
0

I'm not going to mark this as duplicate, because "why is Django is_ajax() not seeing my request as AJAX request?" is a totally different question than "Why is my cross-domain ajax request not setting the X-Requested-With-Header".

But that's essentially the reason and here's the answer:

Cross-Domain AJAX doesn't send X-Requested-With header

Also, as far as I can see, you don't need to make this cross-domain anyway, since your AJAX request is to your own site. Redirecting after the successful response is to another domain, but that's not the AJAX call itself.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42