Laravel : How can load named route with dynamic arguments by javascript - javascript

I have a video player, I want after the end the video to run named route with arguments, I used this code. How can it work correctly?
function play_next() {
var orderId = $('#orderId').val();
var savedVidNum = $('#orderVideo').val();
var url = document.getElementById('player').src;
var filename = url.split('/').pop().split('#')[0].split('?')[0];
filename = filename.split('.').slice(0, -1).join('.')
if (filename < savedVidNum) {
alert('just play next');
} else {
// load route here
orderId = orderId.toString();
savedVidNum = savedVidNum.toString();
window.location.href = "{{URL::to('myroute/3/5')}}"-- -- - here I need to put orderId and savedVidNum
}
}

I see there a form tag under another form tag that's why your post method not working. you need to all HTML form element under one form tag and also need to add the #csrf field.

Related

How can you add an email within a URL in multi-step form to a hidden email form field?

I've created a multi-step form in Webflow containing two pages:
Step 1: /get-started
Step 2: /get-started-final
For get-started, I've added the following code before the tag
<script>
Webflow.push(function() {
$('form').submit(function() {
setTimeout(function() {
location.href = 'https://websitedomain.com/get-started-final?email=' + $('#emailget').val();
}, 100);
});
});
</script>
This page is the first page of the form input and only asks for name and email.
Now for Get Started Final, I ask for 4 additional fields, but I also want to pull the email from the URL and add it to a hidden form field in Get Started Final.
<script>
function getParameterByName(url) {
if(!url) url = window.location.href;
var matches = url.match(/[\?|\&]?email=(.+)/)
if (!matches[1]) return '';
return decodeURIComponent(matches[1]);
}
Webflow.push(function() {
$('#emailget').val(getParameterByName('email'));
});
</script>
I have a non-hidden email input in 'Get-Started-Final' to test if the code works, but it doesn't populate the input with the email.
The email input has an ID of emailget. After I validate that it does grab the email, I'll switch it to hidden.
What is wrong with my code?
The issue here is that you are applying the regex match on the url argument, in the function getParameterByName, instead of the actual URL itself, and an error will occur at if (!matches[1]) because there is no matches:
function getParameterByName(url) {
if(!url) url = window.location.href;
var matches = url.match(/[\?|\&]?email=(.+)/)
if (!matches[1]) return '';
return decodeURIComponent(matches[1]);
}
I'm guessing you simply want to get a specific parameter in the URL, so your function could be as simple as this:
const getParameterByKey = key => new URLSearchParams(location.search).get(key);
Full code:
<script>
const getUrlParameterFor = key => new URLSearchParams(location.search).get(key);
Webflow.push(function() {
$('#emailget').val(getUrlParameterFor('email'));
});
</script>

Remove query string on page reload

I have a hyperlink which i am redirecting to a page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/Merging/Index/?workItemID=' + id;
});
My action in the controller page is
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID==null? 0: workItemID.Value) ;
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
return View(mergingVM);
}
So what it does is when i click on the hyperlink it redirects me to the merging page.
After redirecting to Merge page, the drop down fills with id(selected in home page) and correspondingly triggers the button click.
My issue When i reload the merge page the value in the drop down doesn't get clear. I.e if i have redirected from home page to merge page , then the drop down has some value. but when i refreshes it the selected value should go. I understand that the query string still holds the value. But is there any alternative to send parameter to action without using windows.location.href in jquery.
If you are using hyperlink then also you can try it
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
$(this).attr('href','/Merging/Index/?workItemID=' + id)
});
In order to clean the query string you should use redirect to another view.
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID == null ? 0 : workItemID.Value);
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
//to send this model to the redirected one.
TempData["model"] = mergingVM;
return RedirectToAction("CleanIndex");
}
public ActionResult CleanIndex()
{
var model = (MergingVM)TempData["model"] ?? new MergingVM();
// Do something
return View("Index", model);
}
To find alternatives to an send parameter to a method you first need to understand the model Bindding action.
The model bidding searches a value in:
Form Data
Route Data
Query String
Files
Custom (cookies for example)
If your action must need to be HttpGet you lose the Form Data which would be a nice alternative for you.
If I understand correctly... the below worked for me.
If there's an ID appended to the URL, it gets logged to the console as the variable "param". The URL is then replaced (so that if you refresh the page, the ID is removed from the URL).
$(document).ready(function() {
var url = window.location.toString;
var hostname = window.location.hostname;
var pathname = window.location.pathname;
var param = window.location.search;
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/new-page.php?' + id;
});
if ( pathname == "/new-page.php" && param ) {
console.log(param);
window.history.pushState("string", "Title", "http://yourURL.com/new-page.php");
//Do something with param...
}
});
This assumes that if there is no ID appended to the URL, the drop-down won't do anything. You also would need to update the URLs to the correct ones (I ran this on my local server).
I think you should use POST where you don't want to presist workItemID.
I mean all places where you have links you should use somethink like this:
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="1" /> <-- your Id
<input type="submit" value="Link to workItemID 1!" /> <-- your link
</form>
This way you will get your View but without workItemID in URL. But you should change css to make your POST link look like <a> tags.
Here is with your table:
#if (#Model.DataSetList[i].StateID == 43)
{
<td>
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="#Model.DataSetList[i].Workitem_ID" />
<input class="lnkMerging" type="submit" value="Merging" />
</form>
</td>
}
else
{
<td>
<text style="color:darkgrey" contenteditable="false">Merging</text>
</td>
}
You can save the parameter in local storage api of html5, and then use those parameters in Page load of index page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
localStorage.setItem("workItemID",id);
window.location = '/Merging/Index/;
});
On page load of index you can retrieve it using getItem
localStorage.getItem("workItemID"); and use it as per your requirement.
On page load of Merge page, you have to explicitly set the selected option like below and then remove the value from local storage.
$(document).ready(function(){
if(localStorage.getItem("workItemID")!=null){
$("#mydropdownlist").val(localStorage.getItem("workItemID"));
localStorage.removeItem('workItemID');
}
});
Make sure in var id = $(this).attr('data-id'); id should get same value as you have in the options on the merge page.

Display results from api after user input

I'm learning JS and I need some help figuring out why my info isn't getting populated in the html. I'm just trying to get the basic functionality to work, so that I can continue to expand on it.
User is supposed to input a 3 digit route value, which will then return all the route information from an api call. I was able to get the route info to display earlier when I got the api call set up, but I'm struggling to figure why it's not displaying now that I tried adding in a feature to allow the user to input the route. See attached pen
HTML
<div class='container'>
<h1 id='header'>Route Info</h1>
<input id="input" type="text" placeholder="Enter 3 digit route ex 005" >
<input type="button" value="Get Route" onclick="getRoute()">
<br>
<p id = 'p'><span id="routeInfo"></span></p>
</div>
Javascript
$(document).ready(function() {
var route = $('#input');
getRoute.click(function() {
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&callback=myCallback&Route=" + route;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
var myCallback = function(data) {
var myarray = Array.prototype.slice.call(data);
document.getElementById("routeInfo").innerHTML = JSON.stringify(myarray);
}
});
});
It looks like you are jumping through a lot of hoops you don't need to. As long as you are using Jquery, you should look into getting the api data with an ajax request. It's much easier and more intuitive. Also you have a few problems such as trying to get the input value with var route = $('#input'); which return the actual input element. You are also processing the returned data in a way that won't work.
Here's a basic example to get you going on (IMO) a better track:
function getRoute() {
var route = $('#input').val();
var url = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&Route=" + route;
$.ajax({url: url, success: function(data){
var retValue = "";
var i = 0
for(i; i< data.length; i++) {
retValue += data[i].BridgeName + "<br>"
}
document.getElementById("routeInfo").innerHTML = retValue;
}});
}
If you intend functionality in the getRoute.click callback to run, you need to rewrite that as a method function getRoute(), or get the button element via jQuery and assign that to the variable getRoute. As it stands, you have the click method wired via the markup to a function named getRoute which does not exist. In the JS you are trying to register a click event to a jQuery object named getRoute which does not exist.
getRoute needs to be a global function for it to be called from html :
getRoute = (function() {
Also, myCallback needs to be a global function for it to be called from your loaded script (just remove the var):
myCallback = function(data) {

Show image after button click

I have a controller method that returns image in byte array, from MongoDB, and I want to show it in my view:
<HttpPost()>
Function ShowImage(id As String) As FileContentResult
Dim Handler = New MongoDBHandler()
Dim newString = id.Replace(vbLf, "").Trim().Replace("""", String.Empty)
Dim byteArray = Handler.ReadImage(newString)
Return File(byteArray, "image/png")
End Function
I have the javascript function:
function postCardNumber(elm) {
var CardNumber = $(elm).closest("tr").find(".card-number").html();
var $img = $('<img>');
$img.attr("src", "/MyController/MyMethod/CardNumber");
$("#myModal").append($img);
}
The Table:
When the "Show" button click, on the table, the "No." cell (and is data) is sent to the JS function, and pass to the controller, then i try to create new image element with, and add it to my popup modal for show.
The problem is i cant get the controller response, and spent hours in google search for it, any solutions please?
try following and check if it work. Please verify that the controller name you are specifying in following URL is correct.
I am not sure that your controller name is "MyController". check it and change if it is wrong.
If following code doesn't work, send me the url it generated in comment
function postCardNumber(elm) {
var CardNumber = $(elm).closest("tr").find(".card-number").html();
var $img = $('<img>');
$img.attr("src", "#(Url.Action("ShowImage","CreditCard"))/" + CardNumber);
$("#myModal").append($img);
}

global site variable js

I am new to javascript, i am trying to make a small site with two HTML pages (A and B) and a global js file.
So lets say i have selected certain items in page A, the list-preview on Page A gets updated.
But if i want to see the list in detail i have to go to page B.
Page A and B bith use the same .js file, the selected items are saved in a array.
How do i make sure the selected items still stay in the array, and the array doesn't get flushed when i go from page A to page B ?
what i thought of was ...
var selectedProductsName = new Array();
in OwnJS.js
the adding items to the preview list works.
i'm only struggling to keep the array unflushed when i go to page B from page A.
HTML5 introduces a new thing called localStorage. It's basically some kind of storage that is persistent between all pages of your website as well as between user sessions. It can be accessed as a simple key/value store:
var selectedProductsName = localStorage.getItem("selectedProductsName");
And to set:
localStorage.setItem("selectedProductsName", []);
Here's an article about getting started with localStorage, if you want to be able to do more things like checking browser compatibility for localStorage and watching the storage event, among others.
You could use the HTML5 local storage. It lets you tell the browser to save data on the user's machine. (There's also session storage, valid only for the current session.)
Save (in Apply.html)
IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl","headline","industry","location:(name)","positions:(title)","emailAddress"])
.result(function(result) {
profile = result.values[0];
// save all keys to local storage
for (f in profile) localStorage[f] = fields[f];
// more stuff ...
});
to Retrieve (in personal_Info.html)
// retrieve first name from local storage
var firstName = localStorage["firstName"];
if (firstName !== undefined) {
$("#textfield1").attr(value, firstName);
}
Source Page
The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, the values of the Name TextBox and the Technology DropDownList is set as QueryString Parameter and then the page is redirected to the Destination page (Page2.htm).
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Page
On the Destination page (Page2.htm), inside the jQuery Page Load event handler the URL of the page is first checked to determine whether it has some QueryString Parameters being received, this is done by checking the window.location.search property. If it has some QueryString Parameters then loop is executed and each QueryString Key and Value Pair is inserted in an Array and finally the values are displayed on the page using the HTML span.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>

Categories

Resources