jQuery Ajax returning 404 when method = post - javascript

So I have an ajax script that runs, it looks like this:
jQuery.ajax({
url: 'http://localhost/?page_id=104256',
type: 'POST',
data: { name : 'name2' },
success: function (data) {
alert(data);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details0: " + desc + "\nError:" + err);
},
});
This runs fine but returns a 404 from the page set as the 'url'
If I remove 'type: post'

Here your method: 'Post', Type is something what you want to get in return like text
jQuery.ajax({
url: 'http://localhost/?page_id=104256',
method: 'POST',
data: { name : 'name2' },
success: function (data) {
alert(data);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details0: " + desc + "\nError:" + err);
},
});

If type: 'POST' is omitted, jQuery is treating it like a GET request, which it defaults to see the docs, where the resource may not exist therefore resulting in a the 404 you're seeing.

It turns out I forgot to add the name="" parameter in my input types. Doh!

Related

Ajax Call not being accessed in most pages

This is a very weird problem but I will provide as much detail as possible. This Javascript function is in a separate .js file and referenced into various HTML pages in a Cordova application. When a push notification, with 2 parameters: id, type, is received into the device, a function called LaunchFromNotif is executed with these 2 parameters passed as arguments.
function LaunchFromNotif(id, type) {
try {
var ebyidurl = url + "ReturnEByID";
var nbyidurl = url + "ReturnNByID";
if (type != null) {
if (type == "n") {
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code here
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "e") {
$.ajax({
type: 'GET',
url: ebyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "a") {
combined(id);
}
}
} catch (exception) {
//window.location = "Warning2.html";
}
}
Combined(id) is another function with 2 Ajax calls. I used when and then, to make sure that the first ajax call completes before starting the second.
function combined(id) {
alert("combined");
$.when(
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
alert("success of first ajax");
},
error: function (xhr, status, error) {
alert('Error 1: ' + error);
}
})
).then(function () {
$.ajax({
type: 'GET',
url: Verifytempurl,
data: { Username: localStorage.getItem('user') },
success: function (data) {
alert("success of second ajax");
},
error: function (xhr, status, error) {
alert('Error 2: ' + error);
}
});
});
The problem is that this is working well in only one HTML page. In 3 other pages in which I tried, it shows the "combined" alert and seems to never access the Ajax call. The logic seems to make sense, especially since it is in working order in one page. What could normally go wrong in something of the sort? I am left with few debugging possibilities, especially since this is a Cordova app and being tested on mobile devices.
Thanks in advance!

Sending variable to PHP with AJAX, receiving JSON back

Using the following jQuery, how can I read through the values of the JSON that's returned? With it how it is, the jQuery doesn't even run as there is an error in: alert("A" + obj.sender[0]);
var session_id = $(this).find(".session_id").val();
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: {sesh_id: session_id},
success: function (response) {
var obj = jQuery.parseJSON(response);
alert("A" + obj.sender[0]);
},
error: function (response) {
alert("Err: " + response.status);
}
});
The value of response is:
[{
"sender":"email#example.com",
"details":"details1",
"date":"2017-01-04 16:11:04"
},
{
"sender":"someone#example.com",
"details":"details2",
"date":"2017-01-04 16:11:05"
},
{
"sender":"blah#example.com",
"details":"details3",
"date":"2017-01-04 16:11:06"
}]
The issue you have is that your index accessor is in the wrong place as obj is an array, not the sender property, so it should be obj[0].sender.
You also don't need to call JSON.parse() on the response, as jQuery does that for you automatically as you specified dataType: 'json'. Try this:
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: { sesh_id: session_id },
success: function (response) {
console.log("A" + obj[0].sender);
},
error: function (response) {
console.log("Err: " + response.status);
}
});
Finally, note that console.log() is much more preferable when debugging over alert() as it doesn't coerce data types.

Load D3 Url With API key

I am trying to load a dataset from the URL "https://data.raleighnc.gov/resource/5ccj-g2ps.json" but it requires an API key. I have had no luck with D3 or Jquery.
How would I go about doing this so that I can load the dataset in Json format?
I have the following:
$.ajax({
url: "https://data.raleighnc.gov/resource/xce4-kemu.json",
type: "GET",
data: {
"$limit" : 5000,
"$$app_token" : "YOURAPPTOKENHERE"
}
}).done(data) {
alert("Retrieved " + data.length + " records from the dataset!");
console.log(data);
});
It says I have a misplaced "{" but I don't see where.
There are a lot of mistakes in your code...
$.ajax({
url: "https://data.raleighnc.gov/resource/xce4-kemu.json", // didn't you want to get another URL??!?
type: "GET",
dataType: "json",
data: {
"$limit" : 5000, // Does the API require the dollar signs? Looks weird.
"$$app_token" : "YOURAPPTOKENHERE" // Did you actually replace with your API key?
},
success: (data) => {
alert("Retrieved " + data.length + " records from the dataset!");
console.log(data);
},
error: (xhr, textStatus, errorThrown) => {
// error
}
});
Should be working.

Get entire html page as response with javascript

I am doing an Ajax post to a specific page where I either can get an ID as response if everything went as expected or I could get a random html page and a http 400 as response if something went wrong. In the error case I want to open up the entire html page in a new window. I have tried the following but it is not working - it sets the variable data to [object Object] instead of the intended html page.
$.ajax({
type: "POST",
url: postUrl,
    data:'message=' + message + '&' + 'title=' + title,
statusCode: {
400:function(data) {
var newWin = open('','windowName','height=300,width=300');
newWin.document.write(data);
},
},
success: function(json) {
alert("Post success");
},
    error: function(jqXHR, textStatus, errorThrown) {
        alert("Error connecting to page.");
    }
});
Specify dataType : 'html' and change the success function variable. Example:
$.ajax({
type: "POST",
dataType: 'html',
url: postUrl,
data:'message=' + message + '&' + 'title=' + title,
statusCode: {
400:function(data) {
var newWin = open('','windowName','height=300,width=300');
newWin.document.write(data);
},
},
success: function(html) {
alert("Post success");
$("#myDiv").html(html);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error connecting to page.");
}
});

Descriptive error messages

I have the following jQuery which does not give the most descriptive error messsages...
url: 'server_page.aspx',
type: 'POST',
data: { intID:$(this).attr("id"), strState:"1" },
error: function() { alert('Error'); },
success: function() { }
How do I get more descriptive error messages if it is possible?
EDIT:
This is the full javascript:
$(document).ready(function(){
$("input:checkbox").change(function() {
var that = this;
if($(this).is(":checked")) {
$.ajax({
url: 'favorite_on_off.aspx',
type: 'POST',
data: { strFavoriteID:$(that).attr("id"), strState:"1" },
timeout: 1000,
error: function(xhr, status, error)
{
alert("values: strFavoriteID: " + $(that).attr("id") + " strState: " + "1");
alert('Error: ' + status + '\nError Text: ' + error);
},
success: function() { }
});
} else {
$.ajax({
url: 'favorite_on_off.aspx',
type: 'POST',
data: { strFavoriteID:$(that).attr("id"), strState:"0" },
timeout: 1000,
error: function(xhr, status, error)
{
alert("values: strFavoriteID: " + $(that).attr("id") + " strState: " + "0");
alert('Error: ' + status + '\nError Text: ' + error);
},
success: function() { }
});
}
});
});
These are the error messages:
values: strFavoriteID: c:\folder\document.doc strState: 1
Error: error
Error Text: undefined
You can use all of the arguments passed to the error callback, for example:
error: function(xhr, status, error) {
alert('Error: ' + status + '\nError Text: ' + error);
},
The second argument provided to the error callback is textStatus, which should contain a description of the error:
error: function(xhr, textStatus) { alert(textStatus); }
Note that you should probably not provide this information to your users. Parse the message using Javascript and give them a nice friendly message explaining the error.
I have this method:
function HandleAjaxError(request, status, error) {
var ex = eval("(" + request.responseText + ")");
$('body').addClass("ui-widget-overlay");
alert(ex.Message);
$('body').removeClass("ui-widget-overlay");
}
$.ajax({
type: "POST",
url: window.location.pathname + "/DoStuff",
data: "{}",
success: Success,
error: HandleAjaxError
});
This way, I can gracefully handle the error message (and possibly the status code) on the ASP.NET side. I usually log the original error, then throw a custom/descriptive one for the client.

Categories

Resources