404 not found when sending post request to controller - javascript

I am calling a controller name batch_processor with the method parseFile defined.
I have a script as:
<script>
$(document).ready(function() {
$('#xmlfile').multi();
});
let parseFile = (update) => {
var xml = $('#xmlfile').val() || [],
payload = {xmlfiles: xml};
if(update) {
payload['update'] = 'y';
}
$.post('/batch_processor/parseFile/1', payload,
function(data, textStatus, xhr) {
var res = JSON.parse(data);
$('#xml').val(res.xml);
$('#parsed').val(JSON.stringify(res.parsed, null, '\t'));
$('#manifest').val(JSON.stringify(res.manifest, null, '\t'));
$('#report').val(JSON.stringify(res.report, null, '\t'));
}
);
};
So, when ParseFile Button is clicked this script is invoked. I have defined parseFile method inside batch_processor controller. Still I am getting

404 means the resource you are trying to access on server doesnt not exists

Why is there the "/1" in your url ? I think you can try to remove them. try again

check whether you have defined the parameter in function (parseFile($file_id)). For that check the same without parameter**(/batch_processor/parseFile)** . If it is working then it can be the issue with parameter.
If that doesn't work check whether you have defined htaccess to avoid index.php from url. if not add it.

Error 404 is thrown when URL you are trying to send your data to doesn't exist.
Check if /batch_processor/parseFile/1 doesn't have any typo in it (I can see mixed naming conventions - maybe that is it?) and if it has valid route to proper controller.

Related

AngularJS, ngResource - Unexpected token Error

EDIT:
I got the mistake but no solution. It seems that 'isEditable', 'isOnline' and 'isRecycled' are not sent as booleans but as strings. Therefore my Validaton did not pass and the Error-Response was not valid JSON.
But why does the .save() call sents the booleans as string?
Original Post
Can anyone tell me why following function throws
SyntaxError: Unexpected token '
at Object.parse (native)
at fromJson (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js:1072:14)
As my postData is logged correctly, I think there is a mistake in my resource-save. On the server side I have a simple selfmade php-framework made using Symfony2 components and the $save call of the resource adds a new row in my database and returns this row as a JSON object.
$scope.createStructure = function($event, createdStructure){
$event.preventDefault();
if(createdStructure.copy != null){
copyId = createdStructure.copy.id;
} else {
copyId = 0;
}
postData = {
'title': createdStructure.title,
'id': copyId,
'isEditable': false,
'isOnline': false,
'isRecycled': false
}
console.log(postData);
Structure.save({}, postData, function(response){
console.log(response);
console.log(newStructure);
});
}
PHP can't tell what data type is being passed in. The POST data is seen as a string. Check this previous answer out. I believe it covers the issue you are having.
PHP also has FILTER_VALIDATE_BOOLEAN, which is also covered in the answer I linked. I think it'll help you.
For example:
$isEditable= filter_var ($_POST['isEditable'], FILTER_VALIDATE_BOOLEAN);
That should make $isEditable a boolean.

Rendering mongodb database results from POST request in .ajax jquery wrapper in node js

I am creating a basic piece of functionality to allow users to send their location to a server which then queries a database and returns locations near to them. I am using the below jQuery .ajax wrapper to POST data to the server. This takes the form of a latlon point which is then used as the basis for a geosearch in MongoDB using nodejs and express on the backend. The results of the search are then intended to be returned to the client and rendered by the createMapListings function.
The /find page is initially rendered through a GET request to the database via mongodb separate from the below code. However subsequent to initial rendering, I then want to return results dependent on the location provided.
The POST method works fine and the location is posted to the server, with the search results being returned as I can print contents out through the console log.
However, I then want to render the results on the client-side. As mentioned, the results of the search render in the console, but when I attempt to pass through to the client, I can render the data itself (in the form of an array of objects) in the #output div, but the createMapListings function does not seem to catch the data.
In fact, the below function appears to be called but prints out over a thousand rows with the data that should be caught described as 'undefined'. I have tried to use res.render and res.redirect, but in the first case, the view renders in the div (which I suppose is expected) and the redirect fails.
The createMapListings function works fine when a simple GET request is made to the server, for example, for all objects in a collection, using ejs template. However, I think the issue here may be a combination of a POST request and then wanting to pass the results back to the AJAX request using the complete callback.
I apologise if the below code is somewhat obtuse. I’m definitely what you would call a beginner. I appreciate the above functionality may not possible so if there is a better way, I would of course be open to it (res.direct perhaps).
Here is the relevant client side script:
$(document).ready(function(){
$("#geolocate").click(function(){
navigator.geolocation.getCurrentPosition(geolocate, function(){
});
});
});
function geolocate(pos){
var latlonpt = [];
var x = pos.coords.latitude;
var y = pos.coords.longitude;
latlonpt.push(x);
latlonpt.push(y);
var obj = {
userlocation: latitudelongitudept
};
$.ajax({
url: "/find",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(obj),
complete: function (data) {
$('#output').html(data.responseText);
$('#infooutput').children().remove();
createMapListings(data.responseText);
}
});
};
function createMapListings(maps) {
for (var i = 0; i < maps.length; i++) {
var url = maps[i]._id;
var fullurl = "<a href='/show?id=" + url + "'>Route</a></div>";
var title = "<div>" + maps[i].title + " - " + fullurl +"";
$('#infooutput').append(title);
};
};
</script>
Here is the relevant route used in a basic express app to handle the post request made by the above .ajax wrapper.
exports.findbylocation = function(req, res) {
console.log(req.body.userlocation);
var userlocation = req.body.userlocation;
Map.ensureIndexes;
Map.find({loc :{ $near : userlocation }}, function(err, maps) {
if (err) {
console.log(err)
}
else {
var jmaps = JSON.stringify(maps);
console.log(jmaps);
res.send(jmaps);
}
});
};
By convention, the data variable name in an $.ajax callback signature refers to the parsed HTTP response body. Since your callback is on complete, we're actually passed the XMLHttpRequest used, by convention called xhr. You rightly grab the responseText property, but this needs parsing to be useful. So long as we take care over our Content-Type's and don't explicitly disable processData, jQuery will do the encoding/unencoding for us - we just deal with objects. This is a good thing, since the transport format isn't usually of any particular importance to the application logic. If we use res.json(maps) in place of res.send(jmaps), we can write our call more simply:
$.ajax({
url: '/find',
type: 'POST',
data: obj,
success: function(data) {},
error: function(xhr, text, err) {}
});
Here data is a Javascript object already parsed and ready to use. We also use a default application/x-www-form-urlencoded request rather than explicitly setting a contentType. This is the same as far as express is concerned: it will just be parsed by urlencoded instead of json.
Assuming you solved your client-sie problem.
As you are using express there is no need for JSON.stringfy,
you can use res.json(maps).

Backbone.js - prevent PUT/POST on model.validate failure

Using the following as an example:
var Case = Backbone.Model.extend({
initialize: function(){
this.bind("error", function(model, error){
console.log(error)
});
},
url: function() {
return '/api/kase?id=' + this.get("id");
},
validate: function(attrs) {
return "An error";
}
});
In this case the validate method does not get called:
var kase = new Case();
kase.save();
In this case the validate method does not get called either:
var kase = new Case({subject: null});
kase.save();
In this case the validate method does get called, but the POST request is still made on save:
var kase = new Case();
kase.set("subject",null);
// An error
kase.save();
// POST http://localhost.local/api/kase?id=undefined 404 (Not Found)
Is this the expected behaviour? Am I missing something with regard to 'cancelling' the POST/PUT request when client side validation fails? Or should I be checking for a valid model before hitting the save method? (think the penny may have just dropped).
Any guidance would be most appreciated.
A set that fails won't update the model data while a call to save without parameters will post/put the current state of the model to the server (empty in your case). On the other hand, if you call your save method with the data to be validated, it will stop if the validation fails:
var kase = new Case();
kase.save({subject:null});
should log an error and stop before posting to the server.
Do you have code elsewhere that is calling save on the model?
Backbone does not call the server when setting a model's attributes; even if the validation fails.

AJAX call not going to the server

i am using ajax to populate a drop down but the call is not going to the server. getting the following error in fire bug
POST 0
status 404 not found
my code is:
function selectChildCategory(parent,child){
var url = "<?php echo url::site('admin/video/showSubCategory/')?>";
if(parent != "")
{
if(child != 0){
url = url+parent+"/"+child;
}else{
url = url+parent+"/"+0;
}
$.ajax({
url: url,
type:"POST",
success: function(select)
{
//alert(select);
$("#sub_category").html(select);
}
});
}
}
the parammeters are showing correct values....but call is not going to the server. The URL is correct
please advise.
404 Error code means that the page your are trying to call does not exists.
You are buildng a HTTP path using your parent and child variables but if the formed url does not exists (or is not captured by any mod_rewrite) a 404 error is shown.
For example, for parent "0" and child "0" the url /admin/video/showSubCategory/0/0 exists?
Also if you are using something like mod_rewrite is really correctly configured?
Try first calling the URL manually to check if the url generated by javascript really exists.
Have you checked that the URL is available via a POST request?

JSON with jQuery and PHP

I have a script for updating a database table. I need to return a JSON array and to update some tables with JQUERY.
my php script:
$update = mysql_query("UPDATE PLD_SEARCHES SET STATUS = 1, TOTAL_RESULTS = ".$scrapper->getTotalResults().",RESULTS = $resultCounter WHERE ID = ".$searchId);
$output = array("status"=>"COMPLETED","results"=>$resultCounter,"totalResults"=>$scrapper->getTotalResults());
echo json_encode($output);
jquery code:
$("button").live("click", function(event) {
event.preventDefault();
$.getJSON("startsearch.php", {
searchId: $(this).val()
}, function(data) {
alert(data[0].status);
});
now ...the problem is that if i use $.post("startsearch.php",{ searchId: $(this).val() }, function(data)) the script gets executed and i get a nice alert with value undefined. if i add the parameter "json" the script doesn't get executed anymore. I tried to use getJSON but again the same problem.
Anybody has any ideas? I am desperate...this has been bugging me for almost a week and I still haven't managed to solve it.
In your php file make sure to set the correct content type:
header("Content-type: application/json; charset=utf-8");
so that jquery can correctly eval the response into a json object.
You can get to your response data as follows:
alert(data.status);
alert(data.results);
alert(data.totalResults);
please don't use alert, install firebug into your firefox or enable the javascript console in chrome or safari. after that you can use console.log(data);
my guess is that data isn't an array. also have a look at the each() exmaple on the jquery docs http://docs.jquery.com/Ajax/jQuery.getJSON
Well, I'm trusting json2.js to parse the json data returned from AJAX request. You can download it from http://json.org. This library provide a better way to parse any string, and will throw an exception if the sting is not in json.
I always write my AJAX request like this:
$.post(URL,
{ PARAM },
function(data){
try {
var r = JSON.parse(data);
//this for your code above
alert (r.status); //should be 'COMPLETED'
}
catch (e) {
//data is not in json format, or there are another exception in try block
//do something about it
alert('Exception occured, please check the data!');
}
});
When processing json, the array in php will become a variable member in json. So if in your php it is $output['status'], then in json, it will be r.status.

Categories

Resources