Link or button that sends a POST but does not navigate - html

I need an anchor tag or button that sends a POST to a URL but doesn't navigate to anywhere.
This might not comply with current standards, but it works in Chrome.
<!DOCTYPE html>
<iframe style="display:none;" name="some"></iframe>
<form method="POST" target="some">
<button class="btn" style="margin:0px 10px 15px 0px;" type="submit"
formaction="http://www.example.org:1234/test?P1=X">Test</button>
</form>

In order to post the data without navigating to another page or refreshing the same page, you need to use Ajax.
From your code, I assume you are using jQuery. In jQuery, there are functions that allow to implement Ajax easily.
I will add a sample code below for your reference.
$("#myLink").click(function(event) {
event.preventDefault();
var url = "http://example.com"; //The url/uri where you want to post the data to
var data = {field1: "data1", field2: "data2"}; //Your data
$.post(url, data, function(data, status) {
//Data and status from server after posting your data
console.log(data);
console.log(status);
});
});
And your a tag will remain the same.
Send

Related

Send POST JSON Data and Receive With Node.js (NO BODYPARSER)

I'm frustrated because I can't send from HTML or receive from Node.js JSON data. I think that I'm near to resolve, but I'm tired trying for hours. Anybody helps me?
As the code below, the responde is null (req.body = null?) in my VSCODE.
When I try from Insomnia, that's ok. When I try from HTML Form, fails. *
I could to use BodyParser, but why to send from Insomnia works and from HTML Form doesn't?
//routes.js
routes.post('/go', (req, res) => {
console.log(req.body)
return res.json({ "Response": req.body })
})
<!DOCTYPE html>
<html>
<head>
<title>API Correios</title>
</head>
<body>
<form id="FrmQuery" action="http://localhost:3333/go" method="POST" enctype="application/json">
<label for="sCepOrigem">Cep Origem</label><br>
<input type="text" name="sCepOrigem" id="sCepOrigem"><br><br><br>
<input type="text" id="jsonData"><br><br>
<button id="send" type="button">Enviar</button>
</form>
<script>
document.querySelector('#send').addEventListener('click', (event) => {
let sCepOrigem = document.querySelector('#sCepOrigem')
var obj = {
"sCepOrigem": sCepOrigem.value,
};
var myJSON = JSON.stringify(obj);
document.querySelector('#jsonData').value = myJSON
document.querySelector('#FrmQuery').submit()
})
</script>
</body>
</html>
In Javascript from web browser you need to send it as raw XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Other possibilities would be jQuery's $.ajax or maybe the new fetch API.
Based on my experience with node js, I believe you have to simply res.send and cut out the return statement.
Hope this helps.

How to open specific user profile based on what is clicked on

At first this sounded very simple, but actually I couldn't find a way to implement this.
I have Spring web app, with rest controllers and database. I have users in my web app and I want to open specific page in which details of that user will be shown. So how do I send information about what is clicked on (link to that specific user's details) to another page where the details about user are being displayed?
This is what I tried and when I load profile page nothing appears on it:
index.html
<html ng-app="app" ng-controller="appController">
<head >
<script src="js/angular.min.js"></script>
<script src="js/App.js"></script>
<p ng-click = "setProfileDetails(john)">profile</p>
profile.html
Here I use the same App.js file so I can read the same controller.
<body ng-controller = "appController">
<div ng-model = "profileDetails">
{{profileDetails.username}}
</div>
</body>
App.js
$sopce.profileDetails = null;
$scope.setProfileDetails = function(username){
$http.get("services/rest/getUser/" + username).then(function(response){
$scope.profileDetails = response.data;
}, function(Response){
});
}
on jsp page:
<form action="user-details/${userid}">
//list of users or whatever you want
</form>
on controller
#RequestMapping("user-details/{userid}")
public String showUserDetails(#PathVariable int userid, Model model) {
model.addAttribute("userDetails",userDAO.getUserDetailsById(userid);
return "/ac_user/user-details";
}
You should expose an endpoint which returns user details provided some user identifier like userId. So, when someone clicks on a user, send the userId to the API and retrieve the response and display it. You just need to make a simple API call. Details about your front-end implementation are missing.

How can i get response coming from web server

i have a form, i am asking customer to enter few details,
<form id="redirectForm" accept-charset="UTF-8" method="post" action="https://test.test.com//api/v1/order/create" >
customerName: <input type="text" name="customerName" value=<%=customerName %> />
customerEmail: <input type="text" name="customerEmail" value=<%=customerEmail %> /><br><br>
customerPhone: <input type="text" name="customerPhone" value=<%=customerPhone %> /><br><br>
signature:<input type="text" name="signature" value=<%=signature %> />
On submit page redirect according to action of form and display a JSON type response(status + payment link).
response is like:
{"status":"OK","paymentLink":"https:\/\/test.test.com\/billpay\/order\/3ackwtoyn7oks4416fomn"}
Help me out with this
i am working in jsp.
thank you in advance.
Since this look like a simple Webservice answer (not a full HTML page), I would use Ajax to send the form and manage the response.
With JQuery, this is easy using $.ajax
$.ajax({
url: //the URL
data: //the form value
method: //GET/POST
success: function(response){
//decode the JSON response...
var url = $.parseJSON(response).paymentLink;
//then redirect / not sure since this could be cross-domain...
window.loacation = url;
},
error: function(error){
...
}
})
The only think is that the form should not be send with a submit input, you need to link a button to a function doing this Ajax call.
This can be done without JQuery but I can write this from memory ;)
If you can edit the JSP creating the response, you could generate an HTML to return the value directly.
<html>
<head>
<script>
window.location.href = '${paymentLink}';
</script>
</head>
<body>
Redirection ...
<br>If nothing happend, you can <a href='${paymentLink}'>click here</a> to be redirected.
</body>
</html>
Where ${paymentLink} is a EL that will print the value of this variable (well the name it has on the server) to complete the script with the URL.
Once it is received by the client, it will be executed.
Of course, this will not be cross-domain on every browser. If this is not, you will need to provide the link to the user with <a href='${paymentLink}'>Redirection</a> itsefl.
Try this...
while submitting the form write one JS function and get the URL value.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function check(){
//here you have to get value using element name or id (val1,val2,val3)
$.ajax({
type:'GET',
data: {customerName: val1, customerEmail: val2,customerPhone: val3},
url:'https://test.test.com/billpay/order/3ackwtoyn7oks4416fomn',// Replace with Your Exact URL
success: function(response){
alert(response);
var json = JSON.parse(response);
var values = json.values;
for(var i in values)
{
var New_redirect = values[i].address;
alert(values[i].address);
}
window.loacation=New_redirect;
}
});
})
}
</script>
</head>
i think you are looking for response message and redirecting to somewhere
if so you can use the following code
if(condition)
{
response.sendRedirect("urpage.jsp");
}
or
if(condition)
{
request.getRequestDispacher("page.jsp");//enter the name of page you want to redirect inside ""
}

Grabbing the current viewer count for youtube live streaming

I am looking to display the current viewer count for youtube live streams, i can do this for youtube video with this code :
<?php
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?
part=statistics&id=videiID&key=APIKey");
$json_data = json_decode($JSON, true);
echo $json_data['items'][0]['statistics']['viewCount'];
?>
but this not display the current viewers count !
UPDATE 2:
YouTube has unfortunately dropped support for this method. Hopefully there will be a new solution in the future without using their API (since it has quote limits).
Try this link: https://www.youtube.com/live_stats?v={videoid}
Find a Live event on YouTube and replace the video id in the link. This should retrieve the number of concurrent views for that particular video.
If so, refresh the page and compare the number with the concurrent viewers on the YouTube page.
UPDATE 1:
Here is an example of how you can add it to your website. You can set up a php file and a html file.
viewers.php:
<?php
$viewers = file_get_contents('https://www.youtube.com/live_stats?v=y60wDzZt8yg');
echo $viewers;
?>
viewers.html:
<!DOCTYPE html>
<html>
<body>
<div id="status" style="color: #666; line-height: 24px; font-size: 19px; font-weight: normal; font: 19px Roboto,arial,sans-serif;"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function update() {
$.ajax({
url: 'viewers.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ display: "none" });
} else {
$("#status").text(parseInt(data) + ' watching now' );
}
}
})
}
update();
var statusIntervalId = window.setInterval(update, 5000);
</script>
</body>
</html>
As you can see, I use the PHP file to retrieve the data from YouTube using the live_stats link. I then use the HTML with jquery to update the data dynamically every 5 seconds.
<div id="status"... is where the data is shown and styled with a bit of css.
<script src="... is where the jQuery library is loaded.
<script type="... is the code function where jQuery retrieves data from the PHP file and displays it in the first div / hides it if there are 0 viewers.
I was thinking that you can embed this inside an iframe which won't refresh the entire page. You can also just embed the html code into the webpage directly without an iframe. If you will embed directly, you will have to set a direct path to the PHP file if it's not in the same relative folder. If there are any errors, just troubleshoot with the developer tools console.
Just a heads up, the number of viewers won't show until the first jQuery interval refreshes the data. In this case, 5 seconds. I updated this so it wouldn't take 5 seconds to first update. It should work right away now.
Here is an image of it working for me:
Hope this helps...
If you want to get current viewers count (concurrent viewers), just include liveStreamingDetails in the part parameter of the request.
Example:
https://www.googleapis.com/youtube/v3/videos?
part=statistics,liveStreamingDetails&id=videoID&key=APIKey
The response will include
...
"statistics": {
"viewCount": "38452",
"likeCount": "95",
"dislikeCount": "12",
"favoriteCount": "0",
"commentCount": "0"
},
"liveStreamingDetails": {
"actualStartTime": "2021-08-03T17:34:09Z",
"scheduledStartTime": "2021-08-03T16:20:00Z",
"concurrentViewers": "95",
}
...
Ref: https://developers.google.com/youtube/v3/docs/videos/list#parameters

How to add a button to jQuery.ajax() to use http delete method

I am trying to send an http DELETE method to a URI. After realizing that I cannot do this with plain old html forms, I was told to use jQuery.ajax. I found a few posts on it and this is the code I found that will supposedly do it:
<script type="text/javascript">
$.ajax({
url: '/groups/dissolve/$org_ID',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
</script>
Please bear with me as I have not used jQuery before. What I am trying to do is replace my html form with this code above but I don't know where to start. How do I place a button in there as I would in a regular form? Thanks and please forgive my ignorance!
Something like:
$("form").on("submit", function() {
$.ajax({
url: '/groups/dissolve/$org_ID',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
});
This will bind the AJAX method to the submit action of your form.
Another option is to use method override. This allows you to specify the method (GET, POST, PUT, DELETE) in a query string parameter or a hidden field in your form. You will need to check with your specific language and web framework, but most support this in some variation.
<input type="hidden" name="_method" value="DELETE" />