send and receive data using ajax express node - javascript

I am new to node Express. I am trying to upload a file using ajax.. but I don't know the best method to do so. I have seen many tutorials.
some are written post code to the app.js file and some in routes/index.js some say directly writing in the app.js file is not a good approach. I wasn't able to run it using routes kindly tell me which is the better approach to do so. and how to do it.
thanks
Ajax Call
var formData = new FormData($('#cover_file_form')[0]);
$.ajax({
// url: '/cropImg',
url: 'http://localhost:3000/cropImg',
data: formData,
//contentType: 'application/json',
type: 'POST',
success: function(data){
alert(data.file_name);
},
error:function(dat){
alert('error'+dat.file_name);
}
});
App.post()
app.post('/cropImg',function(req,res){
// get the temporary location of the file
var tmp_path = req.files['file_browse_cover'].path;
//i have skipped the extra code
es.send({file_name: req.files['file_browse_cover'].name});
}

Related

Laravel: I have some problem posting data with Ajax

Im new to using ajax and I have another post here about my code and they said it was correct.
However Im still facing issues
My code:
body[circle.id] = {id: currentid-1, x: event.offsetX, y: event.offsetY};
// Ajax
for(let i = 0;i < body.length;i++){
$.ajax({
url: 'get.php',
type: 'post',
data : {
data: body[i],
},
dataType: 'json',
});
}
The error:
[Error][1]
I cannot comment.
From the title I guess you are using Laravel.
I see you are hitting the file directly, but looks like you are showing only half the setup. In case Laravel.
What is the route setup?
And if the setup is like Route::get try Route::any.
How are you debugging the issue? Do you have any logs?
Can you check the logs of "web server"?
Either artisan serve or php -S should give at least some hints what your ajax is hitting.
According to the error image you have posted, The error says that the method only accepts the GET request but you are trying to make POST request in your AJAX method, Change your request type to GET like this,
$.ajax({
url: 'get.php',
type: 'get',
data : {
data: body[i],
},
dataType: 'json',
});
I fixed it.The problem was in url and routes

Laravel ajax url not working on production server

I have this ajax request on my Laravel Project (this is a simple version but it is working):
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: '/admin/lessons/addMember/licenseMemberId', // This is the url we gave in the route
data: {'licenseMemberId' : id},
success: function(response){
console.log(response);
if ($.trim(response)) {
var actualMembers = document.getElementById("actual-member");
}
$('#membersModal').modal('hide');
},
});
When I work locally and I use php artisan serve the ajax call works, but when i deploy to my production server doesn't (because the path /admin/lessons/addMember/licenseMemberId is not the full path in the server).
The best way shoud be using the route, but I don't know how.
This is the routing table:
web |
| | POST | admin/lessons/addMember/{licenseMemberId} | lessons.addMember | App\Http\Controllers\admin\LessonController#addMember
Is there a way to use the laravel route with the paramether? If not, how can I do?
You shouldn't use URLs in Laravel the way you use it in vanila php or html, use the URL function, this function ensures that your route is pointing currectly to the project root, in your case you can do something like this
$.ajax({
method: 'GET',
url: '{{URL::to('/admin/lessons/addMember/')}}' + id,
// Laravel will print the url and you just need to concat your id to it
success: function(response){
console.log(response);
if ($.trim(response)) {
var actualMembers = document.getElementById("actual-member");
}
$('#membersModal').modal('hide');
},
});
Notice that im using GET as you seem to be retrieving data and not POSTING it, however if you need to post it, the MisaGH answer is the way to go
Do not receive the parameter in route.
URL should be : /admin/lessons/addMember
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: '/admin/lessons/addMember', // This is the url we gave in the route
data: {'licenseMemberId' : id},
success: function(response){
console.log(response);
if ($.trim(response)) {
var actualMembers = document.getElementById("actual-member");
}
$('#membersModal').modal('hide');
},
});
And the controller:
$member_id = request('licenseMemberId');
The real route is
admin/lessons/addMember/{licenseMemberId}
so in javascript you need to call
'/admin/lessons/addMember/' + id
where id is a variable. In the controller you can use the id getting
Input::get('licenseMemberId') or $request->get('licenseMemberId');

How to import path of api.php in frontend

Here is one sample post request which is in script.js.I want to send data from this request and store in beckend.So i have created api.php file which has All routes associated with controllers.
In api.php , My reqeust route is..
Route::post('/task/create/{task_id}','TasksController#create');
Request in script.js..
var request = $http({
method: "POST",
url: "/api/task/create/1", //// Changes will made here
data: {id: index, title: $scope.title},
headers: {'Content-Type': 'application/json'}
}).catch(function(data){
alert("error");
});
I am running this files on local server.
http://127.0.0.1:8000/api/task/create/1
I guess I am inserting the wrong url and i dont how to import that api.php file here and call after making request.So please suggest me to do that.
To call php script you should use
http://127.0.0.1:8000/api.php?taskid=1
inside PHP script you should use
$taskid = $_GET['taskid'];
As far as I get you try use Express based syntax inside php. If you are using php script to generate JS then you can do that only for front-end

API Expose (NodeJS/ExpressJS)

I'm writing a website on Express. Handling routes using express router. I have some routes: registration, login, upload, and so on. As upload route expects files, in front-end I use ajax to upload files to upload route. The question is: am I allowed to reveal route names in front end. As in front end:$.post('upload')...
Yes, you can call routes with ajax, somelike this...
$.ajax({
type: 'POST',
data: JSON.stringify(data),
cache: false,
contentType: 'application/json',
url: '/route',
success: function(ret) {
// here its possible to get the return of res.send() from server
}
});
But, one tip for to use upload with express: search for formidable and formidable-upload for facility your work, somelike this =]

Implementing Ajax calls for a REST API

I have built a back end REST API using Slim Framework and followed the REST format as close as I could.
Once I started working on the Front End I realized that AJAX works great with parameters and not paths
(param file?param=value , paths file/object/method/id)
I am planning on out sourcing or building an APP with xamarin or other 3rd party to consume the API, but for now a Alpha test will be done with HTML and AJAX calls.
Example call example.com/user/test or example.com/advertiser/2
So how do I query the API, do I just concat URL strings?
.ajax({ ... url : 'example.com/user/'+user ...});
EDIT:
Yes I know AJAX is domain sensitive, and Yes I am using verbs GET,POST,PUT and DELETE.
What is going on is the following :
When passing variables in an AJAX request they get appended as
PARAMS example.com/users/?user=Pogrindis
in an REST API at least as far as I read it goes
example.com/users/Pogrindis that's a path
reference parse.com/docs/rest#general-quick
Ajax has set definitions how to do this : https://api.jquery.com/jQuery.ajax/
Your passing user as a param, over get // post method and you are specifying what you expect back.
If i understood the question correctly you are looking at something like:
$.ajax({ url: 'example.com/user/',
data: {user: user}, // Params being sent
type: 'post',// Or get
dataType: 'json' // Or whatever you have
success: function(output) {
//.. do what you like
}
});
There should be no problem.
The data being passed into it will append to the url for GET-requests, i think thats what you mean.. Your data object can be constructed before sending via ajax.
There needs to be a route to query for data. Unless you define some flag on the server to point to the correct location, then you could pass through a route param but you need to have a pointer URL. Building the route can be painful, and subsequent calls will be more challenging but you can do it ?
After doing some research here is a solution used
FRONT END
$.ajax({
url: '/user/'+getid,
data: getdatastring,
type: 'GET',
datatype: 'json',
cache: false,
success: function(data) {
data = JSON.parse(data);
}
});
BACK END
SLIM PHP FRAMEWORK
$app->put('/user/:id', function($id) use ($app,$_pdo) {
$obj = new dbModel($_pdo);
$objApi = new Controller($obj);
$arrParams = json_decode($app->request()->getBody(),true);
$arrUser= $objApi->getUserInfo($id,$arrParams);
print json_encode($arrUser);
});

Categories

Resources