Ajax post problem

78 views
Skip to first unread message

willyhakim

unread,
Apr 17, 2014, 4:07:02 PM4/17/14
to django...@googlegroups.com
Hi everyone?

I am trying to use ajax to do the following

1)User inputs a number.
2) I use ajax to return a query list into the same page.

Here is my code
and I keep getting this error

Using the URLconf defined in exportAbroad.urls, Django tried these URL patterns, in this order:

  1. ^$ [name='index']
  2. ^about/$ [name='about']
  3. ^pricing/$ [name='pricing']
  4. ^market_research_tool/$ [name='market_research_tool']
  5. ^newmarkets/ ^$ [name='index']
  6. ^newmarkets/ ^search/$ [name='search']
  7. ^admin/
  8. ^accounts/
  9. ^static/(?P<path>.*)$

The current URL, newmarkets/search/ method=, didn't match any of these.


views.py
def index(request):
context = RequestContext(request)
return render_to_response('newmarkets/index.html', context)

def search(request):
if request.is_ajax() and request.method=='POST':
UserHSnumber = request.POST['UserHSnumber']
country_list = Imports.objects.filter(hs_number= UserHSnumber)[1:11]
hsdescript = Products.objects.get(hs_number=UserHSnumber) 
data = {'markets': country_list, 'hsdescript': hsdescript}
mimetype='application/json'
else:
raise Http404
return HttpResponse(json.dumps(data), mimetype)


HTML

{%block body_block%}
<div style="min-height:600px">
 <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h2 class="page-header">What is your product's H.S number?</h2>

        <form action="{% url "search" %}" method="post">  
         {% csrf_token %}          
          <input type="text" id = "hs" placeholder="4 digit HS number..."/>
          <button class="btn-default">Submit</button>
        </form>  
</div>
</div>
<hr>
<hr>
<div id="top-countries">


ajax.js

$(document).ready(function() {

$('#hs').click(function(){
$.ajax({
type:"POST",
url:"/newmarkets/search/",
data:{"userHSnumber":$("#search").val()},
dataType: "json",
success:function(data){
alert(data.message);
}
});
});

    // CSRF code
    function getCookie(name) {
        var cookieValue = null;
        var i = 0;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (i; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        crossDomain: false, // obviates need for sameOrigin test
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    }); 
});





Joseph Mutumi

unread,
Apr 17, 2014, 4:25:13 PM4/17/14
to django...@googlegroups.com
You could try using $("form").serialize() to get the form inputs in
the ajax data. But from the URL it looks like your HTML is somehow
rendering badly. The form action is coming out as '/newmarkets/search/
method='

Kind regards

On 4/17/14, willyhakim <will...@gmail.com> wrote:
> Hi everyone?
>
> I am trying to use ajax to do the following
>
> 1)User inputs a number.
> 2) I use ajax to return a query list into the same page.
>
> Here is my code
> and I keep getting this error
>
> Page not found (404) Request Method: GET Request URL:
> http://127.0.0.1:8000/newmarkets/search/%20method=?csrfmiddlewaretoken=VkKvStx1qGZOM1YxzM8xenGDbYRBnMPA
>
>
> Using the URLconf defined in exportAbroad.urls, Django tried these URL
> patterns, in this order:
>
> 1. ^$ [name='index']
> 2. ^about/$ [name='about']
> 3. ^pricing/$ [name='pricing']
> 4. ^market_research_tool/$ [name='market_research_tool']
> 5. ^newmarkets/ ^$ [name='index']
> 6. ^newmarkets/ ^search/$ [name='search']
> 7. ^admin/
> 8. ^accounts/
> 9. ^static/(?P<path>.*)$
>
> The current URL, newmarkets/search/ method=, didn't match any of these.
>
> *views.py*
> def index(request):
> context = RequestContext(request)
> return render_to_response('newmarkets/index.html', context)
>
> def search(request):
> if request.is_ajax() and request.method=='POST':
> UserHSnumber = request.POST['UserHSnumber']
> country_list = Imports.objects.filter(hs_number= UserHSnumber)[1:11]
> hsdescript = Products.objects.get(hs_number=UserHSnumber)
> data = {'markets': country_list, 'hsdescript': hsdescript}
> mimetype='application/json'
> else:
> raise Http404
> return HttpResponse(json.dumps(data), mimetype)
>
>
> *HTML*
>
> {%block body_block%}
> <div style="min-height:600px">
> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
> <h2 class="page-header">What is your product's H.S number?</h2>
>
> <form action="{% url "search" %}" method="post">
> {% csrf_token %}
> <input type="text" id = "hs" placeholder="4 digit HS number..."/>
> <button class="btn-default">Submit</button>
> </form>
> </div>
> </div>
> <hr>
> <hr>
> <div id="top-countries">
>
>
> *ajax.js*
>
>
>
>
>
> *$(document).ready(function() { $('#hs').click(function(){ $.ajax({
> type:"POST", url:"/newmarkets/search/",
> data:{"userHSnumber":$("#search").val()}, dataType: "json",
> success:function(data){ alert(data.message); } }); }); // CSRF code
> function getCookie(name) { var cookieValue = null; var i =
> 0; if (document.cookie && document.cookie !== '') { var
> cookies = document.cookie.split(';'); for (i; i <
> cookies.length; i++) { var cookie =
> jQuery.trim(cookies[i]); // Does this cookie string begin
> with the name we want? if (cookie.substring(0, name.length +
>
> 1) === (name + '=')) { cookieValue =
> decodeURIComponent(cookie.substring(name.length + 1));
> break; } } } return cookieValue;
>
> } var csrftoken = getCookie('csrftoken'); function
> csrfSafeMethod(method) { // these HTTP methods do not require CSRF
> protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }
>
> $.ajaxSetup({ crossDomain: false, // obviates need for sameOrigin
> test beforeSend: function(xhr, settings) { if
> (!csrfSafeMethod(settings.type)) {
> xhr.setRequestHeader("X-CSRFToken", csrftoken); } }
> }); });*
>
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/2132e3e5-9795-416d-9306-0b09a1698c6b%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

Jonathan Querubkna

unread,
Apr 17, 2014, 5:27:42 PM4/17/14
to django...@googlegroups.com
Or:

var dataForm = new FormData( $("form")[0] );

That way you can send even file fields. Serialize do not support file fields AFAIK

Jonathan
Diretor de Tecnologia
+55(12)98864-1594

Sent from my iPhone
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAN5idp_ENtkVOapK6QjaGPhGUUfbAC8CWxnOg%2BpQFbgZOuMRmQ%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages