laravel named route in ajax url is not interpreted - ajax

when I do this ajax call :
$.ajax({
url : '{{ route("showposts") }}',
type: 'GET',
success: function (response) {
console.log(response)
}
});
the url request is sent like this :
http://127.0.0.1/bao/public/%7B%7B%20route(%22showposts%22)%20%7D%7D
but the url I want is :
http://127.0.0.1/bao/public/postes
this what my route looks like :
Route::get('/postes', 'HomeController#showPosts')->name('showposts');
Note :
when I put the URI hard coded in ajax url it work fine

Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.
You can't use that syntax in a javascript file, it just won't work. You have to move the script to a blade file.

Related

Pass $_GET variable through ajax call's php file

I have an jQuery AJAX call that lists records from database based on $_GET variable called "website_identificator". Imagine the main file is called "index.php" (where the AJAX call is presented) and the PHP script file that is called by the AJAX is called "phpscript.php". Now also imagine that I'm using the $_GET "website_identificator" to decide what to show on this page, but this $_GET "website_identificator" is beneficial for the PHP script file so it can filter the records and show the right ones. How to I use this $_GET variable in "phpscript.php", because when I try to use it like this:
<?php $getVar = $_GET['website_identificator']; ?>
PHP understands it like "phpscript.php?website_identificator=STRING" but not "index.php?website_identificator=STRING" despite the fact that I called the file through AJAX call.
I understand that you call index.php with the query parameter website_identificator? You have to include that value in the AJAX request and pass it on to phpscript.php. There is no magical way to retrieve the query parameters from another script, both are standalone.

Laravel Routes - Possible to reuse ajax route call from one form on different form?

I have an existing route I created to perform an ajax call for a chained select:
Route::get('add/{id}','AddAssetController#getModel');
The above queries the db for models belonging to each manufacturer.
The url part of the ajax call (man_ID is the id of the manufacturer from the select):
url: 'add/' + man_ID,
The above works perfectly on the main form where I am using it. However, I've found that I need this chained select on more than one form. Is there a way to be able to use the same route for two different pages? I've tried calling it from a different page and in the console, I'm getting a 404 error.
Am I missing something? Is this possible?
You are probably calling the script from the differently nested pages, thus add/ is ultimately calling different path.
I would strongly advise you name your routes, and generate links like that:
Route::get('add/{id}','AddAssetController#getModel')->name('get-model');
and in your blade file
url: '{{route('get-model', ['id' => $id])}}',
if you still set on using paths to call your script, use them relative to your root:
url: '/add/' + man_ID,

Django - AJAX - Why do I need url parameter?

It's my first time using AJAX and I don't understand why I need to specify url parameter in a JS Ajax call.
{% block javascript %}
<script>
$("#id_username").change(function () {
$.ajax({
url: '/some_new_url/',
data: {
'something': ...
},
success: function (data) {
if (data.is_taken) {
alert("Data is already in DB");
}
}
});
});
</script>
{% endblock %}
To my understanding, AJAX is used to do something on the server side without refreshing a page. So it shouldn't redirect to a new url upon sending a data to the server, and stay on the same url. And yet AJAX call requires url parameter.
And I don' really like this, because setting a new url means I have to add another url pattern in my app/urls.py.
re_path(r'^create/$', views.Some_View.as_view(), name='create'),
And as a consequence, make another view in my views.py
class Some_View(ListView):
model = SomeModel
fields = '__all__'
But, I already have a CBV that generates form fields on the user side and accepts user inputs. I only want to make my existing CBV to save data to DB using AJAX call.
Since I don't understand what the purpose of the url is, I don't know how to set up my new url pattern, and CBV. Can I get some explanation here?
++ This is just a bonus question, but my ultimate goal is to generate multiple form fields, and multiple Submit buttons that sends the respective form input data to the server using AJAX. If there's any advice on how to tweak AJAX code, I would appreciate it.
An AJAX request is just a regular HTTP request to a url on the server. The only difference between an AJAX request and a request made by an ordinary browser GET or POST is that with AJAX, the results that come back from the server are returned to your javascript function and then you get to decide what to do with those results.
So there's no automatic updating of anything.
If you want to save something on the server, you need a view there on the server which is capable of understanding the data you are sending in the AJAX request, saving it, and then sending back a response which, again, your javascript code needs to be able to understand.
But if you already have a view which is capable of doing what you want, you can use it for your AJAX request, you just have to send a request with everything in it that the view requires.

Cannot POST strings containing fragmented HTML tags

I'm making an ajax call to POST a string to a shared hosting server I rent from Namecheap.com. I cannot seem to POST a stirng that contains some fragmented HTML tags such as <b><b, <tag><tag<tag. When I do this, I get a 403 Forbidden error. I tried the same thing using the escape function from Underscore.js, but the result was the same.
Here is the code I am using.
JavaScript
$.ajax({
type: 'POST',
url: '/test.php',
data : {
pass : '<b><b' // pass : _.escape('<b><b') gives the same result
}
})
.done(function (res) {
console.debug(res);
})
.fail(function (err,textStatus,errorThrown) {
console.debug('failed');
});
PHP
<?php
$password = $_POST['pass'];
echo $password;
?>
I tested this on XAMPP Linux on my local machine and this did not happen. Why is this happening?
You are almost certainly running into some sort of ill-conceived "security" feature of your web host. Contact their support staff.
For anybody who has the same issue, I fixed (See EDIT) this by double escaping the text as in _.escape(_.escape('<b><b')). This will output &lt;b&gt;&lt;b.
Sam Deufel also suggested me to use base64 encoding. I think this will work, too.
EDIT: I found that JavaScript statements such as alert() or document.write() are also not allowed to be POSTed via ajax on Namecheap hosting servers. So double escaping it does not always work. Using base64 or similar methods is probably better.

CodeIgniter routing problem. (appends ajax route to existing url)

I'm trying to perform an AJAX-request in a view, the user gives some input which is sent to the server with AJAX and the function it's supposed to go to is routed with CodeIgniters routes.
This is the view I'm currently standing in while making the request.
http://localhost:8888/companies/list
In my route config I've set this route below to handle the AJAX-request, which should be able to come from any view and still be able to go to the route I've specified.
$route['test_ajax'] = "ajax/test_ajax";
So the request should go to the "ajax"-controller and use the function "test_ajax", which should make the POST-url look like this.
POST http://localhost:8888/test_ajax
But instead what I get is the current URL I'm standing at, and the route I've specified appended to the URL crashing my response from the AJAX-request completely since it didn't even go close to the function it's supposed to. The POST-url I get looks like this.
POST http://localhost:8888/companies/test_ajax
Notice how the parameter of /companies was removed. The argument /list was lost somewhere, al though if I add a trailing slash after the list I get the list argument in the URL as well.
So what just happened is that the POST tries to go to the companies-controller and look for the function test_ajax which is defined in the ajax-controller and not in the companies-controller. This error keeps occuring no matter what URL I'm at, and it always follows the same pattern. It keeps appending my route-URL to the existing URL instead of routing correctly.
So what could be causing the routing to behave this way, is there any setting that's accidently enabled or anything? Because I know I've got this to work hundreds of times in previous projects.
Thanks in advance.
It is because your Javascript is using the current directory as the base, and appending the AJAX URL to it. Because you are (to the client-side at least) in the companies directory, it appends your URL onto this.
The solution, if your Javascript is inline, is to just use the base_url() PHP function wihtin the code ...
var url = '<?= base_url(); ?>test_ajax/'
If your Javascript is not inline, you can declare a global variable at the top of your HTML document using the PHP function...
var BASE_URL = '<?= base_url(); ?>'
And use it everywhere else in your Javascript ...
var url = BASE_URL + 'test_ajax/'
Alternatively, you could just hardcode your base URL, but that could get real messy real quick.
Turns out, CodeIgniter interpreted this as a relative link due to the fact that there was no heading slash. CodeIgniter User-Guide states that no heading or trailing slashes should be written in the routes config.
What solved this though was adding a heading slash in the java-URL.
$.ajax({
url: "/test_ajax",
type: "POST",
data: data,
success: function(data){
console.log(data);
}
});
This forces CI to interpret this as a absolute URL and gives me the URL I was looking for.
POST http://localhost:8888/test_ajax

Resources