ajaxdjangogeturlconf

Django - Ajax: sending url params in data


I am trying to send a "GET" and "POST" requests to Django server via Ajax. First, I provide the URLConf:

url(r'^write_to_file/(?P<file_name>.*)/(?P<content>.*)/$',generalFunctions.write_to_file, name ='write_to_file'),

Now, the AJAX part. Previously, I used to do it this way (avoiding sending params in data)

$.ajax({
        type: "GET",
        url: '/write_to_file/' + file_name + '/' + content ,
        data: {},
        success: function(data){ 
            alert ('OK');
        },
        error: function(){
            alert("Could not write to server file " + file_name) 
        }
    }); 

Up to a certain moment, I was satisfied by this method, but now it is important for me to pass on file_name and content via the "data" variable and for some reason I get 404 Error.

$.ajax({
        type: "GET",
        url: '/write_to_file/',
        data: {'file_name':file_name, 'content':content},

        success: function(data){ 
             alert ('OK');
        },
        error: function(){
            alert("Could not write to server file " + file_name) 
        }
    });

Error on server-side:

Not Found: /write_to_file/
[15/Apr/2016 14:03:21] "GET /write_to_file/?file_name=my_file_name&content=my_content HTTP/1.1" 404 6662

Error on client-side:

jquery-2.1.1.min.js:4 GET http://127.0.0.1:8000/write_to_file/?file_name=my_file_name&content=my_content 404 (Not Found)

Any ideas why? Is it something wrong with the ajax syntax or it has somehow to do with the URLConf ?


Solution

  • url(r'^write_to_file/(?P<file_name>.*)/(?P<content>.*)/$',generalFunctions.write_to_file, name ='write_to_file'),
    

    is now wrong, the url you are sending the post request to is: /write_to_file/

    url(r'^write_to_file/$',generalFunctions.write_to_file, name ='write_to_file'),
    

    is what you'd want i think!