Django - Ajax: sending url params in data - ajax

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 ?

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!

Related

How to get a ajax call with get request not throwing erros

I am trying to make an ajax call on the below url
http://postalpincode.in/api/postoffice/tindivanam
which works fine with chrome address bar.
but if i use
city = 'Tindivanam';
jQuery.ajax({
url: 'http://postalpincode.in/api/postoffice/'+_.toLower(city),
method: 'GET',
success:function(response){
console.log(response)
}
})
I am getting this

javascript: how to make AJAX call based on the avaiable cURL request

Currently in my web app project, I need to parse the content of a web page, and after some searching, I found that Mercury Web Parser API is quite suitable for me.
And I have some experience with such kind of third party APIs, generally speaking I can get my desired result.
But for this API, I can't find documentation about the API usage on the official website.
Based on the my study, it provide two methods:
first is cURL as following:
curl -H "x-api-key: myapikey" "https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed"
the myapikey is the API key I get from the website. Then I can get the result in JSON format, which is the main content of the web page specified by the url parameter. It works well for me, I mean the cURL method.
And on the website, it said that the second method is HTTP call, which is just what I need:
GET https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed
Content-Type: application/json
x-api-key: myapikey
So based on my understanding, I use jquery AJAX method to do this as following:
var newurl = "https://mercury.postlight.com/parser?url=http://www.businessinsider.com/joel-spolsky-stack-exchange-interview-2016-12&x-api-key=myapikey"
$.ajax({
url: newurl,
dataType: "jsonp",
success: function(data){
console.log(data.title);
}
})
here I made JSONP request because of the Cross origin issue.
But now I face 401 error message (401 Unauthorized. The request has not been applied because it lacks valid authentication credentials for the target resource)
For now my guess is that the apikey is not correctly passed to server. So based on the cURL's successful call, can I get the correct format for AJAX call?
Update:
Based on the following answers ,I tried to set the request header as following:
$.ajax({
url: newurl,
dataType: "jsonp",
beforeSend: function(xhr){
console.log(apiKey);
xhr.setRequestHeader('x-api-key', apiKey);
},
/*
headers: {
"x-api-key": "M1USTPmJMiRjtbjFNkNap9Z8M5XBb1aEQVXoxS5I",
"contentType": 'application/json'
},
*/
success: function(data){
console.log("debugging")
console.log(data.title);
},
error: function (error) {
console.log(error)
}
})
I tried both beforeSend and headers. But still can't work and get the following trackback error message:
send # jquery.js:8698
ajax # jquery.js:8166
addNewArticle # topcontroller.js:18
fn # VM783:4
e # angular.js:281
$eval # angular.js:147
$apply # angular.js:147
(anonymous) # angular.js:281
dispatch # jquery.js:4435
elemData.handle # jquery.js:4121
And for the last send function, still 401 error.
But the ajax error handling part shows that the readyState:4 and status: 404 result. So what's going here.
For your question, the curl request is sending a header which you have attached as part of the query string in your $.ajax request.
Try the following instead (using beforeSend + xhr) :
// broke this string down so you don't have to scroll
var newurl = "https://mercury.postlight.com/parser?" +
"url=http://www.businessinsider.com/" +
"joel-spolsky-stack-exchange-interview-2016-12";
// set your api key
var apiKey = "<your api key>";
$.ajax({
url: newurl,
dataType: "json",
beforeSend: function(xhr){xhr.setRequestHeader('x-api-key', apiKey);},
success: function(data){
console.log(data.title);
}
})

admin-ajax.php call returns 404 error as soon as an object with value 'varchar' is being passed

I have the following issue with wordpress ajax call.
Whenever I send a parameter that contains the string "varchar" it results in 404 Not Found error.
When I would change it to for instance "varchar1" it returns 200 Success
The following ajax call returns 404:
$.ajax({
url: ajaxurl,
type: 'post',
data: {
action: 'send_email',
data: 'varchar'
},
But this ajax call returns 200:
$.ajax({
url: ajaxurl,
type: 'post',
data: {
action: 'send_email',
data: 'varchar1'
},
I also tried to change the parameter key "data" to something else, this does not make any difference.
I use both the actions for the ajax call: wp_ajax_ and wp_ajax_nopriv_
Because I can't think of anything else, my question is: Could this be a server setting of some sort?

Ajax returning 404 error on ASP MVC3 site

This Ajax code works perfectly is I'm running the program on my local machine. However, once we put this out on a DEV server we get a 404 error. The site is an ASP MVC3 site that communicates with a SQL database, and the rest of the site has no problem doing so. I'm brand new to Ajax so I'm not quite sure where to look. Could this be an issue with IIS as well?
Ajax code
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { 'programName': pgmname },
dataType: 'text',
success: function (data) {
console.log(data);
alert(data);
//$('#data').dialog('open');
},
error: function (data) {
console.log(data)
alert("Unable to process your resquest at this time.");
}
});
Chrome's Console error message:
POST http://insideapps.dev.symetra.com/BatchPrograms/PopDetails 404 (Not Found)
send jquery-1.8.3.js:8434
jQuery.extend.ajax jquery-1.8.3.js:7986
GetProgramDetails BatchDashboard:51
onclick BatchDashboard:165
Chome's Network error message
Name (Path) Method Status (Text) Type Initiator Size Time (Latency)
PopDetails POST 404 Not Found Text/Html jquery-1.8.3.js:8434 1.8KB 21ms
/BatchPrograms Script 1.6KB 17ms
Try modifying url to
url: '#Url.Action("PopDetails", "BatchPrograms")'
Try using the Url.Action() helper to get the route from the Table Routes defined in your application.
var request = $.ajax({
type: 'POST',
url: '#Url.Action("PopDetails", "BatchPrograms")',
data: { 'programName': pgmname },
dataType: 'text',
success: function (data) {
$('#data').dialog('open');
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});

Why is this basic json call not working?

The following JSON call always hits the AJAX error handler, and I can't figure out why:
$.ajax({
type: "GET",
url: '<%= Url.Action("MyTest", "Detail") %>',
dataType: "json",
error: function (xhr, status, error) {
alert(xhr + " | " + status + " | " + error);
},
success: function (json) {
alert(json);
}
});
All I get is Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost:4497/Detail/MyTest?_=1320681138394
When I set a breakpoint in the controller, I can see that it's being reached, so I'm not sure where the request is falling down. Here's the action in the DetailController:
Function MyTest() As JsonResult
Return Json("Hello")
End Function
Any ideas?
The jQuery error handler is fired because it failed to parse the returned page as valid JSON. Since you get 500 internal server error, the page most likely doesn't contain valid JSON.
Load this page in your browser and fix it until it gives valid json:
http://localhost:4497/Detail/MyTest
After it is giving valid json in the browser, try the jQuery ajax call.
I have no idea of even the basic functionality of VB.NET but can you make so that the only thing that is printed on http://localhost:4497/Detail/MyTest is like:
print( '{"message":"hello"}' );
If the only thing the page is outputting is {"message":"hello"} then json error handler will not fire

Resources