POST route in Leaflet map giving errors - javascript

Is there any way to use a form in leaflet mapping to open another page?
I'm using a post route for this and have even tried embedding it in an tag but to no avail.
At the moment the form data is in a for loop like so
map_data.forEach(element => {
console.log('program=' + element.program + ', lat=' + element.gps_lat + ', long=' + element.gps_lon);
data[i] = L.marker([element.gps_lon, element.gps_lat], {icon: redIcon}).addTo(map);
var url = '{{ route("opentraining", ":training_id") }}';
var alt_url = '{{ route("opentraining") }}';
url = url.replace(':id', element.id);
data[i].bindPopup(
'<strong>' + element.program + '</strong>'
+ '<br />'
+ '<b>Location:</b> ' + element.location + ', ' + element.district + ', ' + element.province
+ '<br />'
+ '<b>Description:</b> ' + element.description
+ '<br /><br />'
+ '<form onsubmit="' + alt_url + '" method="POST" class="formEditTraining">#csrf<input type="hidden" name="training_id" value='+ element.id + '>'
+ '<button type="submit" value="submit" class="btn btn-primary trigger-submit">View Record</button>'
+'</form>'
).openPopup();
i++;
});
Even when use the route directly within the form it makes no difference all I get is an error saying POST method isn't supported.. What could I be missing ?

You're using the wrong attribute for the URL in your <form> tag. onsubmit is for specifying a JS function to run before the form is submitted. To specify the URL you want to submit the form to, use action. Since you are not specifying action at the moment, it's posting it back to the same URL that the form is on, which evidently is not set up to receive POSTs.

Related

Replace javascript href content with php link

I need to replace one link from javascript with php link.
javascript line:
'<a href="' + res.attachment.guid + '" target="_blank">
php :
echo '<a href="' . wp_get_attachment_url($value->ID) . '" target="_blank">
javascript context:
if (res.success) {
$('.no_file_upload').remove();
var template = '<li class="attachment-' + res.attachment.ID + '">' +
'<p>' + res.attachment.post_title + '<span>' +
'<i class="fa fa-cloud-download" aria-hidden="true"></i>' +
'<i class="fa fa-times" aria-hidden="true" data-post-id="' + res.attachment.ID + '" data-project-id="' + res.attachment.project_id + '" data-file-name="' + res.attachment.post_title + '"></i>' +
'</p></span>' +
'<span>' + res.attachment.post_date + '</span>' +
'</li>';
I tried this way but fail:
<?php echo '<a href="' . wp_get_attachment_url($value->ID) . '" target="_blank"> ?>
So my Wordpress site is uploading all the files to Amazon S3 using WP Offload S3 Lite plugin. I had to alter some of the template files to manage to show the proper Amazon S3 link on website, I had change href links with wp_get_attachment_url($value->ID). The only thing left is one javascript file with that content that is still loading wrong download link. I need to make it work.
I think better you use file name instead of attachment url. get_attached_file( $data->ID )
https://developer.wordpress.org/reference/functions/get_attached_file/
also you can use https://wordpress.org/plugins/amazon-s3-and-cloudfront/ for correct url
for 1.
when you have file name you can generate your own link with a custom function.
Please let me know if there is any issue.
javascript line
<a href="' + cloudfront_url + res.attachment.guid + '" target="_blank">
Complete Javascript
var cloudfront_url = 'https://your_unique_id.cloudfront.net/'
if (res.success) {
$('.no_file_upload').remove();
var template = '<li class="attachment-' + res.attachment.ID + '">' +
'<p>' + res.attachment.post_title + '<span>' +
'<i class="fa fa-cloud-download" aria-hidden="true"></i>' +
'<i class="fa fa-times" aria-hidden="true" data-post-id="' + res.attachment.ID + '" data-project-id="' + res.attachment.project_id + '" data-file-name="' + res.attachment.post_title + '"></i>' +
'</p></span>' +
'<span>' + res.attachment.post_date + '</span>' +
'</li>';
}
You're trying to mix Javascript & PHP code. That is possible but let me explain how it works. PHP code is executed on server side & Javascript is executed on client side.
So, if you write down any php code in the javacsript code, it'll be executed at the time the HTML page is sent by the server to the user. Once the page is loaded, you can't call any PHP function inside the javascript code.
The PHP code is executed in the server before executing the JavaScript client side, the only way in your case is by using AJAX call to get the download link from the server.
In the other hand, there is an option to write JavaScript inside PHP, but not the inverse.

CanĀ“t get the output using jQuery with rest

I am using jQuery with REST in my application and I want to get the ouput mentioned below using the jQuery within my webpage .
I used the code below to search by get a company by id (each company has id, name other info supplier and buyers) but the result does not show up for me with my code, any suggestion on what have I missed?
REST is a concept for HTTP request exchange, so you're making RESTful request calls (e.g. 'get') against the REST-API you implemented on server side.
<input name="find" type="text" maxlength="300" id="find"/>
<button onclick="findId()"> Find By ID </button>
<div id="info"></div>
<script>
function findId()
{
var id = document.getElementById("find").value;
$("#info").html("");
$.getJSON("http://localhost:8080/company/" + id, function(data)
{
for (var i in data) {
$('#info').append("<p>ID: " + data[i].id + "</p>")
$('#info').append("<p>Name: " + data[i].name + "</p>")
$('#info').append("<p>Other Info: " + data[i].otherInfo + "</p><br>")
$('#info').append("<p>Supplier: " + data[i].suppliers + "</p><br>")
$('#info').append("<p>Buyers: " + data[i].buyers + "</p><br>")
}
});
}
When I type http://localhost:8080/company/ into my browser I get the following output:
[{"id":1,"name":"Test 1","otherInfo":"Test 1","suppliers":[{"id":1,"name":"Test 1","address":"Test 1","buyers":[{"id":1,"name":"Test 1","address":"Test 1"}]},{"id":2,"name":"Test 2","address":"Test 2","buyers":[{"id":3,"name":"Test 3","address":"Test 3"},{"id":2,"name":"Test 2","address":"Test 2"}]}]},{"id":2,"name":"Test 2","address":"Test 2","suppliers":[{"id":3,"name":"Test 3","address":"Test 3","buyers":[{"id":4,"name":"Test 4","address":"Test 4"}]}]}]
If i type http://localhost:8080/company/1 into my browser i get
{"id":1,"name":"Test 1","otherInfo":"Test 1","suppliers":[{"id":1,"name":"Test 1","address":"Test 1","buyers":[{"id":1,"name":"Test 1","address":"Test 1"}]},{"id":2,"name":"Test 2","address":"Test 2","buyers":[{"id":3,"name":"Test 3","address":"Test 3"},{"id":2,"name":"Test 2","address":"Test 2"}]}]}
Is it a cross domain request? If so you can get around it by using jsonp instead of json.
function findId()
{
var id = document.getElementById("find").value;
$("#info").html("");
$.getJSON("http://localhost:8080/company/?callback=?" + id, function(data)
{
for (var i in data) {
$('#info').append("<p>ID: " + data[i].id + "</p>")
$('#info').append("<p>Name: " + data[i].name + "</p>")
$('#info').append("<p>Other Info: " + data[i].otherInfo + "</p><br>")
$('#info').append("<p>Supplier: " + data[i].suppliers + "</p><br>")
$('#info').append("<p>Buyers: " + data[i].buyers + "</p><br>")
}
});
}

Javascript REST API Post Form

I am new to REST and I am trying to add a variable to the JSON body so I can have an input form for the values.
I have also tried using getElementID along with this HTML form after wrapping the the script in a function, but I am having no success.
var requestBody = "{'companyid':'getElementById('companyid')','knowledgeid':'getElementById('knowledgeid')','source_code':'getElementById('source')','article_title':'getElementById('title')'}";
var client=new XMLHttpRequest();
client.open("post","<URL>");
client.setRequestHeader('Accept','application/json');
client.setRequestHeader('Content-Type','application/json');
client.setRequestHeader('Authorization', 'Basic '+btoa('admin'+':'+'admin'));
client.onreadystatechange = function() {
if(this.readyState = this.DONE) {
document.getElementById("response").innerHTML=this.status + this.response;
}
};
client.send(requestBody);
Here is the form:
<form enctype="application/json" action="<URL>" method="post">
Title:<input id="title" type="text"></input>
Company:<input id="companyid" type="text"></input>
KnowledgeID:<input id="knowledgeid" type="text"></input>
HTML:<input id="source" type="text" ></input>
<input type="button" value="Send" onClick="restRequest()"></input>
When defining the value of requestBody you don't want to get the element itself, but it's value. You also have that single quoted so it's not going to get evaluated.
var requestBody = "{'companyid': '" + document.getElementById('companyid').value + "', 'knowledgeid': '" + document.getElementById('knowledgeid').value + "', 'source_code': '" + document.getElementById('source').value + "', 'article_title': '" + document.getElementById('title').value + "'}";
you need to be careful when constructing a body use proper concatenations see following with alertbox
var requestBody = "{companyid: " + document.getElementById(companyid).value + ", knowledgeid: " + document.getElementById(knowledgeid).value + ", source_code: " + document.getElementById(source).value + ", article_title: " + document.getElementById(title).value + "}";
alert(requestBody);
I will recommend take some time and look at JQuery framework. It will make your life lot easier

How to append a string variable in Jquery html elememt attribute

Please , I have a JQuery code when appends data to a div element sucessfully like this
$('#conversation').append('<div id="receiver"><p><b>' + username + ':</b> ' + data + '</p></div><br>');
Now supposing I want to have an anchor tag which will have a hyperlink inside as an atrribute and I want to pass a variable to that href attribute not the link itself since I don't know the kind of link that will be sent. I have problems tring to append this.
$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +"></a></p></div><br>');
This does not work. Any idea how to go about this.
This is my whole code snippet
socket.on('updatechat', function (username, data) {
//showing username and the message sent
var checkifdataisalink=data;
var check=checkifdataisalink.split('://')
if((check[0]=='http')||(check=='https'))
{
$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +"></a></p></div><br>');
}else{
$('#conversation').append('<div id="receiver"><p><b>' + username + ':</b> ' + data + '</p></div><br>');
}
});
Apart from the missing quote, your or part of the if condition was missing [0]. See below.
//For demo purposes only
var check = ["http", "other-part-of-the-url"];
var username = "user";
var data = "data";
// --;--
if(check[0] == 'http' || check[0] == 'https') {
$('#conversation').append('<div id="receiver"><p><strong>' + username + ':</strong> <a id="link" href="' + data + '">' + data + '</a></p></div><br/>');
} else {
$('#conversation').append('<div id="receiver"><p><strong>' + username + ':</strong>' + data + '</p></div><br/>');
}
Demo#fiddle
Change
$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +"></a></p></div><br>')
into:
$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +'"></a></p></div><br>');
Just one ' was missing after data

email message with changing information

I am trying to create email templates just using an html file. This file will display a list of mailto links that, when clicked, will open a template with message. I got it working for the most part but some of these templates use prompts to add information to the message before creating it. The problem is that it doesn't seem to work right. Here is my code.
function sendReport(emailName, addresseList){
document.writeln('<a onClick="setPrompt(this,\'' + addresseList + '\')" href="mailto:' + addresseList + '?subject=' + 'Report' + '&body=' + 'Here is the report.' + '">' + emailName + '</a><br />');
}
function setPrompt(obj, addresseList){
var reportName = prompt("Report name","");
obj.attr('href', ='mailto:' + addresseList + '?subject=' + reportName + '&body=' + "Here is the report."); //<-- this is the line that is giving me trouble.
}
You have a typo in the last line and there is no .attr() built in function in Javascript. This should fix it:
obj.setAttribute('href', 'mailto:' + addresseList + '?subject=' + reportName + '&body=' + "Here is the report.");

Categories

Resources