How to import path of api.php in frontend - javascript

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

Related

Issue with passing url in Ajax call through Javascript in a Laravel Project

I started learning Laravel a few months ago. First I developed it on my local machine and later tried to move it to my shared dreamhost hosting. While using the ajax calls in the Javascript code in Vue components, I realized that I need to pass full URL for the route. Hence I created a global variable in resources/js/app.js
window.siteURL = (window.location.host.substr(0,9) == '127.0.0.1') ? "http://127.0.0.1:8000/" : "http://example.com/";
And I created url in my ajax calls like this:
$.ajax({
url: siteURL+'client/notesAjax',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
method: 'post',
I am not sure if this was a good scheme, but it worked.
A few days ago, I registered a domain and tried to run my Laravel project on my AWS EC2 server. After a few hurdles, my Laravel project started running of my domain. However, I realized that I need to empty siteURL for the server on AWS EC2, hence I updated window.siteURL as
window.siteURL = (window.location.host.substr(0,9) == '127.0.0.1') ? "http://127.0.0.1:8000/" : "";
However, some of my ajax calls were still not working. For example, I had an ajax call on the client/notes page:
$.ajax({
url: siteURL+'client/notesAjax',
But this was failing (everything was still working fine on my local pc and the site running on my shared hosting on Dreamhost. Then I figured out that the url that this call was going to was like this:
http://myawsdomain.ca/client/notes/client/notesAjax
Looks like that as the call is being originated from the client/notes page, it was being prepended to 'client/notesAjax' (siteURL is empty). As a hack, I created an extra route in routes/web.php
Route::post('/client/notesAjax',[clientController::class,'notesAjax'])->name('client.notesAjax');
// on AWS, it looks for the route /client/notes/client/notesAjax (client/notesAjax is called from client/notes page)
Route::post('/client/notes/client/notesAjax',[clientController::class,'notesAjax'])->name('client.notesAjax');
I have many other ajax calls that originate from the client/notes page. Using that hack on all those calls may not be appropriate. What is the best way to handle my situation?
Thanks.
unless you are putting your application in a sub-folder, you could've have ommited the base URL for all your HTTP request and everything should have worked without any issue moving from one domain to another.
so if your route end-point is something like /client/notesAjax
your http request should also have been like that
$.ajax({
url: '/client/notesAjax',
.
.
another thing you could do is define APP_URL in your .env configuration like APP_URL=https://mydomain.me
then append that value of config variable in your main index file,
something like
#php
$config = [
'baseUrl' => config('app.url'),
];
#endphp
<script>
window.config = #json($config);
</script>
then use it for all your http request
$.ajax({
url: `${window.config.baseUrl}/client/notesAjax`,
I changed my ajax call from
$.ajax({
url: siteURL+'client/notesAjax',
to
$.ajax({
url: '/client/notesAjax',
and everything started working fine.

why 404 and 405 shows on my live laravel project when I use ajax post request

I have developed simple cart system in laravel for my local client, it has no any issue on my local server but when I publish it on my live server which is infinity free hosting it has multiple issues. When I try to add to cart the product on home page it is showing 404 error, I am using ajax request.
JS CODE:
jQuery.ajax({
url: "/add_to_cart",
method: "post",
data: jQuery('#formAddToCart').serialize(),
success: function(result){}
my home page url is "new_shop/" and when I remove the "/" from my js code url it is working perfectly but then it shows error on my product detail page where I am using same function and the url of product detail page is "product-name" like this without "/"; product detail page add to cart is also not working with "url: "/add_to_cart"," this url. I don't know what the confusion is as it is working perfectly on my local server. I think it may be issue of free hosting. Any assistance will be appreciated.
ROUTE WEB.PHP CODE:
Route::post('add_to_cart',[FrontController::class,'add_to_cart']);
You are doing it in a wrong way from js code.
You should use name for your routes like this
Route::post('/add_to_cart',[FrontController::class,'add_to_cart'])->name('cart.add');
Now call it from the js code like this
jQuery.ajax({
url: "{{route('cart.add')}}",
method: "post",
data: jQuery('#formAddToCart').serialize(),
success: function(result){}
})
As I am not sure you have group for your route or not
You can try this also
jQuery.ajax({
url: "{{URL::to('/add_to_cart')}}",
method: "post",
data: jQuery('#formAddToCart').serialize(),
success: function(result){}
})
And make sure that you are passing csrf token in your form data.
This way you don't need to worry about your methodName as well as your url. You just need to provide a name to your routes

How to pass variables in a get request without showing it in the url - nodejs

I want to make a get request to render a page but I need to pass 2 variables to that page. How can I create a ajax request to do this without having the variables show up in my url such as var1=?var2=?.
$.ajax({
async: true,
type: 'POST',
url: '/profile',
data: {
'UID': currentUid,
'Name': user_data.displayName
},
success: function (res) {}
})
I thought of creating a post request and passing the variables that way but then how do I render the page that I want to because my Post request doesn't fetch the page
In express you should get the page using
app.post
instead of
app.get
If you do for example:
var express=require('express')
var app=express()
app.get('/profile')
Your app will not fetch the page using POST method. Only GET method.
This might be your issue.
More info:
App req.METHOD()

send and receive data using ajax express node

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});
}

JQuery $.ajax request returns me "Error 404" even if the resource exists

I'm developing an app with TideSDK and I need to send some data to a PHP script that will create a file to store it on the pc. I'm pretty new to AJAX and to send data I do:
var jsonString = JSON.stringify(GW2.items);
$.ajax({
url: "/assets/scripts/save.php",
type: "post",
dataType: "json",
data: { jsonString: jsonString }
}).done(function(data){
console.log(data);
});
Where GW2.items is a JSON object, "save.php" is my script and jsonString is the variable I want to send.
But, when I try to execute the program it returns me:
POST http://127.0.0.1:52432/assets/scripts/save.php 404 Not Found
And the answer is: Cannot POST /assets/scripts/save.php
This is the PHP script:
<?php
$jsonString = $_GET['jsonString'];
return {};
?>
I checked the path and it's correct so why it can't find my file?
Did you try your path with POST or just GET? It could be exist for GET requests (pasting the url on a browser) but probably not for POST or other HTTP verbs.
You can use REST clients like Postman to be sure, which is also a Chrome extension.

Categories

Resources