url to fetch with parameter for django view - javascript

I'm facing a problem with my javascript code when trying to use AJAX instead of href link.
I need to hit a django url that looks like this (Django 2.2):
path('one-time/<str:product_url>/', OneTimeProductView.as_view(), name='one_time_product')
the origial code in the django template was:
{{product}}
I now want to use ajax call to make the whole process opened inside of a modal. In my javascript code my fetch function looks like this:
function handleAccess(){
var url = "{% url 'one_time_product' product %}" ;
fetch(url, {
method: "POST",
headers: {
"X-CSRFToken": '{{csrf_token}}',
"Accept": "application/json",
"Content-Type": "application/json"
}
})
.then (response => {
response.json();
})
.then (data => {
console.log(data);
})
};
I know i'm missing something related to the params in the url variable but I just don't know how to add it properly so that i fit the url path.
This is the error that I get when I hit the button
NoReverseMatch at /one-time/ Reverse for 'one_time_product' with no
arguments not found. 1 pattern(s) tried:
['one\-time\/(?P<product_url>[^/]+)\/$']
How should I write the url in the fetch function ?
I will appreciate and anyone can point me into the right direction here.
Thanks

It was a tricky one.
I solved it with the back-end dev.
var url = "{% url 'one_time_product' product_url=0 %}".replace('0', {{ product }}) ;

You have a named parameter in the URL definition (product_url).
On top of my head, you should use the url templatetag like this:
var url = "{% url 'one_time_product' product_url=product.url %}" ;
Change the product.url to the actual url (or slug) from your product model.

Related

How to save model instance in Django through JavaScript in HTML

I am Building a BlogApp and I am stuck on a Problem
What i am trying to do
I made a instance named user_location in model. I accessed it in template and I write JavaScript code to access User's Location using JavaScript BUT i want my model instance to save the JavaScript's Output country in the Database.
The Problem
I don't know how to save model instance through JavaScript.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
full_name = models.CharField(max_length=100,default='')
user_location = models.CharField(mac_length=100,default'')
profile.html
<script>
$.ajax({
url: "https://geolocation-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function(location) {
$('#country').html(location.country_name);
}
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>Country: <span id="country"></span></div>
#This is my model instance.
{{ profile.user_location }}
What have i tried
I also tried THIS. BUT it didn't work for me.
I don't know what to do.
Any help would be Appreciated.
Thank You in Advance.
Use Ajax to send your data to the backend and let django do it's thing.
You can use fetch api from javascript to storing the data from javascript in ur model db like fetch(your website route) where u had created your form for post request.
You can create post request on ur route to save ur db.
Example-url = "your website post request route"
params =
method:'post',
headers:
'Content-Type': 'application/json'
body: data
fetch(url, params).then(response=> response.json())
.then(data => console.log(data)
)*/

Inject html as the result of an API Call Chrome Extension

The Question
How do I take the json result from and API call and inject the result into and html page?
The Context
As part of a web extension I am working on, I call and API for a resulting json.
my popup.html has a button click that calls a call.js file.
call.js (example)
$.ajax({
type: 'GET',
url:body,
headers: headers,
success:function(data) {
console.log(data);
// use return json to update html
// maybe open html for injection here as
// var url = chrome.extension.getURL('location.html')
// chrome.tabs.create({url: url, active: true});
}
Interms of flow, i'm not sure how to pass the result of the api call, in and effective way, to a scrip that will inject HTML into the location.html file.
I tried the following flow
Get API Json -> store json in localStorage -> open location.html url
-> have a content script that runs an injection.js file one https://*location.html* appears -> inject required elements
but the json was to large for local storage, and honestly, I'm unsure if that flow was even correct. Do you have any suggestions on how to resolve this issue? I feel this is a standard functionality of web extensions, but for some reason, I cannot put this piece of the puzzle together.
Thanks!
use massage passing.
in your content script
chrome.runtime.onMessage.addListener(req =>{
if(req.action === "showJSONFromPopup"){
showJSONResult(req.data)
}
})
in your popup script
$.ajax({
type: 'GET',
url:body,
headers: headers,
success:function(data) {
console.log(data);
chrome.tabs.query({currentWindow:true, active:true}, tabs=>{
chrome.tabs.sendMessage(tabs[0].id, {action: "showJSONFromPopup", data})
})
}

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

Laravel route is not working in API, returns page 404

In routes/api.php I have the following route:
Route::post('/session/storeValue', 'HomeController#storeValue');
And in controller I have AJAX function:
<script>
function noviArtikal() {
var data = { name: 'User');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: '/session/storeValue',
data: data,
success: function() {
console.log("Valueadded");
}
});
};
</script>
But keep getting error page not found when sending AJAX call.
What am I doing wrong?
As it is api.php, it automatically adds /api/ to your URL. Try /api/session/storeValue.
From docs:
Routes defined in the routes/api.php file are nested within a route
group by the RouteServiceProvider. Within this group, the /api URI
prefix is automatically applied so you do not need to manually apply
it to every route in the file. You may modify the prefix and other
route group options by modifying your RouteServiceProvider class.
EDIT:
add name:
Route::post('/session/storeValue', 'HomeController#storeValue')->name('custom_name');
Then modify your javascript:
$.ajax({
type: "POST",
url: '/session/storeValue',
data: data,
to
$.ajax({
type: "POST",
url: '{{ route('custom_name')}}',
data: data,
EDIT 2:
And yes, don't send CSRF_TOKEN (check #Yur Gasparyan answer)
For first you dont need to send CSRF_TOKEN to api. There is no sense to check CSRF-TOKEN because it is an api. Also to send request to api you need to add api prefix manualy.
add this code in your route/web.php
Route::post('/session/storeValue', 'HomeController#storeValue');
simply give any name to the route just like this:
Route::post('/session/storeValue', 'HomeController#storeValue')->name('somename');
and in your ajax call just change the url attribute to:
url: '{{ route('somename')}}',
Laravel attach /api to the api routes automatically through RouteServiceProvider and it is found is /Providers folder.
Also you don't need csrf_token when you are making an Api call.

JavaScript URL issue with Permalinks enabled

I am using the following JavaScript function to fetch the data using ajax call
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
It calls the following php file and works fine.
http://127.0.0.1/osclass/oc-content/themes/bender/ajax-test.php
But when I enable SEO friendly Permalinks in my CMS current page URL is appended in start of link and I get the following error in Chrome Console.
GET http://127.0.0.1/osclass/fashion-beauty/oc-content/themes/bender/ajax-test.php?name=Jhon 404 (Not Found)
Anybody tell me how to solve this issue?
The url you've provided in the ajax call is document relative. When you changed the server's url generation scheme, you also caused the url pointed at by the ajax call to change.
Adjust the ajax url, changing:
url: "oc-content/themes/bender/ajax-test.php",
To:
url: "/osclass/oc-content/themes/bender/ajax-test.php",
Why don't you make the URL server-relative? Something like this:
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "/osclass/oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
As you have not posted the php code. I would mention that any url directly navigated through addressbar of browser causes in the GET request and i can see you have a POST request in the ajax, so, it can't work.
Workaround would be to use $_REQUEST super globals at php end. $_REQUEST would work for $_GET/$_POST requests.

Categories

Resources