Calling same function multiple times with different arguments jquery - javascript

I am dynamically creating html elements like this
<li> Schedule</li>,
titleObj.id and titleObj.profile_id are data from ajax response
The created elements will look like the below one.
<li> Schedule</li>
The above anchor tag calls scheduleInterview(id,profile_id).
scheduleInterview() gets the parameters and stores it to pass to ajax function and open a modal(has a form) to get more form input values which will also be passed to the same ajax function along with the parameters value. Now the issue is, modal form action is set to the same function scheduleInterview() cause i need both parameters and form input values.
function scheduleInterview(id,profile_id){
console.log("The student id is "+id);
console.log("the profile id is "+profile_id);
$('#myModal').modal('show');
var candidate_id = id;
var profile_id = profile_id;
var inter_name = $('#inter_name').val();
var date = $('#inter_date').val();
var time = $('#inter_hr').val();
var meridian = $('#inter_mr').val();
candidate_id = $("#m_can_id").val();
profile_id = $("#m_can_p_id").val();
var dataString = 'inter_name=' +inter_name+ '&inter_date=' +date+ '&inter_time=' +time+ '&inter_meridian=' +meridian+ '&candidate_id=' +candidate_id+ '&profile_id=' +profile_id;
console.log(dataString);
$.ajax({
})
}
The above method log the id and profile_id as 15 and 22 exactly. After that it opens the modal which has a form whose action points to the same function but without parameters.
<form action ="javascript:scheduleInterview()" method= "post" id = "sche_inter_form">
</form>
So it overrides parameters value to undefined. But I need the parameters value along with the form input values of the modal. I really don't know how to go about this. Finally after modal submission i have dataString value like this
inter_name=Jonathan&inter_date=12/06/1995&inter_time=02:30&inter_meridian=AM&candidate_id=undefined&profile_id=undefined

Related

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.

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

How can I change an element's text without changing its current element?

$.ajax({
type: "GET",
url: "my url" + x,
datatype: "html",
success: function(data){
//alert(x);
//var Content = data;
var sendId ;
var data = $.parseJSON(data);
var jsonArray = data.result;
// var data2 = $.parseJSON(jsonArray);
var jsonArray3 = jsonArray.oilFilter;
$.each(jsonArray3,function(i1,js2){
var proname = js2.productName;
var mrp = js2.mrp;
var deliveryStatus = js2.deliveryStatus;
var oilid = js2.productId;
$(".oilid").val(oilid);
$(".deliveryStatusOil").html(deliveryStatus);
$(".mrpoil").html(mrp);
$(".oilprodetail").html(proname);
});
<label id="oilprodetail" class="oilprodetail"></label><br/>
<label id="mrpoil" class="mrpoil"></label><br/>
<a onClick="ajax_cross(this);" id="oilid" class="oilid" >View</a>
If you go through the code I am assigning values to label tag with id oilprodetail and mrpoil and i am doing the same thing to oilid as well,
My requirement is to send oilid value to a tag and retain view there,
Please help? I am new to ajax..
In the above picture i need to do the right part of the pic that is view,,
but when i send the data it changes to left part of the pic like it changes from view to the value that is sent
You can use data attribute to keep innerHTML of "a" tag. Like :
$(".oilid").attr('data-oilid',oilid);
There are several issues with your code:
You misspelled datatype, which should be dataType;
Even if correctly spelled, you then wrongly identify the data type as HTML: you really expect JSON, which is something different;
Without the dataType property (which is your case), jQuery will guess the data type, and probably will guess it to be JSON. In that case, $.parseJSON will fail, because jQuery will already have decoded the JSON string and present the result as the data argument;
You use the .html(...) method to set the content of some elements to some text. html() should only be used when the content really is HTML, but otherwise (which I think is your case), you should .text(...);
An a element does not have a value property, so calling .val() on it does not have the desired effect;
You want to pass the oilid value to the ajax_cross function, but provide it this, which is an HTML element (the a), not the value.
As you iterate the array, you are setting the content of the exact same elements in each iteration over and over again, which means only the last iteration determines what the content will be. You should put each text in the proper element, avoiding to overwrite the previous written value.
The HTML you have shared, only has space for writing the result of the first array element to -- there should be similar elements for the second row, third row, etc.
To solve all this, you could get inspiration from this code:
$.ajax({
type: "GET",
url: "my url" + x,
dataType: "json", // corrected spelling and type
success: function(data){
// Don't parse as JSON string any more, data alread is object;
// Don't name your variable jsonArray, it is neither of those
var result = data.result;
var jsonArray3 = result.oilFilter;
$.each(jsonArray3, function (i1, js2) {
var proname = js2.productName;
var mrp = js2.mrp;
var deliveryStatus = js2.deliveryStatus;
var oilid = js2.productId;
// bind onclick handler with oilid argument bound to it:
// use `get()` to select the next element of the same class:
$(".oilid").get(i1).off('click').on('click', ajax_cross.bind(null, oilid));
// use text(), not html()
$(".deliveryStatusOil").get(i1).text(deliveryStatus);
$(".mrpoil").get(i1).text(mrp);
$(".oilprodetail").get(i1).text(proname);
});
}
});
<label id="oilprodetail" class="oilprodetail"></label><br/>
<label id="mrpoil" class="mrpoil"></label><br/>
<!-- remove onclick attribute, we bind the handler dynamically -->
<a id="oilid" class="oilid" >View</a>
<hr><!-- repeat elements for second row -->
<label id="oilprodetail" class="oilprodetail"></label><br/>
<label id="mrpoil" class="mrpoil"></label><br/>
<!-- remove onclick attribute, we bind the handler dynamically -->
<a id="oilid" class="oilid" >View</a>
<hr><!-- repeat elements for third row -->
<label id="oilprodetail" class="oilprodetail"></label><br/>
<label id="mrpoil" class="mrpoil"></label><br/>
<!-- remove onclick attribute, we bind the handler dynamically -->
<a id="oilid" class="oilid" >View</a>
The above is still not ideal, as you would better create the elements dynamically as you iterate through the Ajax results, so you would have just as many as you would need.

Calling an Action Method based on the value of DropDownList and the model

I have a dropdownlist in my View. I need to enable the user to select a value from the dropdownlist and click a button/ActionLink to call another action method in the same controller. The values that needs to be passed to the new ActionMethod are the ID of the selected Value from the dropdownlist and also the ID of the model which is being passed into the View. The model and the Dropdownlist are not linked together by any means.
I have tried onchnage = document.location.href to set the path of the action method and pass a single value to the action method. But the issue with document.location.href is that it appends the url to the existing url which is not appreciated; i.e, the final url turns out be localhost:port/controller1/action1/controller1/action2 which should have been simply localhost:port/controller1/action2
I am looking for a way where it could be done without using javascript as I have already tried it.
Code in the View
#using (Html.BeginForm("Copy","SetValues",FormMethod.Post))
{
<p>
#Html.DropDownList("OptionValueID", null, "Select")
<input type="submit" value="Copy" />
//This is the preferable method though
#*#Html.ActionLink("Copy", "Copy", "SetValues", new { #OptionValueID = #ViewBag.id,#CopyID = CopyDDL.SelectedValue},null)*#
</p>
}
The copy function is going to take two arguments: Id of the selected item and ID that is being passed through ViewBag.id
The View that is being returned by View would a different View
JavaScript that I have tried
<script language="javascript" type="text/javascript">
function copy(_OptionValueID)
{
var url = "/SetValues/Copy";
$.ajax({
url: url,
data: { copyid: _OptionValueID},
type: "POST",
success: function (data) { }
});
response();
}
</script>
It doesn't evaluate at all.
Action Method that calls this View
public ActionResult Index(int id)
{
var ov = db.OptionValue.Include(x => x.Option).FirstOrDefault(x => x.OptionValueID == id);
var opid = ov.OptionID;
var op = db.Option.Include(x => x.TechnicalCharacteristic).FirstOrDefault(x => x.OptionID == opid);
var tcid = op.TechnicalCharacteristicID;
var tc = db.TechnicalCharacteristic.Include(x => x.TcSets).FirstOrDefault(x => x.TechnicalCharacteristicID == tcid);
var tcset = tc.TcSets;
var opv = db.OptionValue.FirstOrDefault(x => x.OptionValueID == id);
ViewBag.OptionValue = opv.OptionVal;
ViewBag.Option = opv.Option.OptionName;
ViewBag.Lsystem = opv.Option.Lsystem.LsystemName;
ViewBag.FamilyName = opv.Option.Lsystem.LsystemFamily.FamilyName;
ViewBag.OptionValID = id;
ViewBag.OptionID = opv.OptionID;
var setValue = db.SetValue.Where(x=>x.OptionValueID==id).OrderBy(x=>x.TcSet.SetName);
ViewBag.OptionValueID = new SelectList(db.OptionValue.Where(x=>x.OptionID==opid), "OptionValueID", "OptionVal");
return View(setValue.ToList());
}
I ahve checked most question relating to this, but none had the overhead of passing two parameters without using a model.
UPDATE: making it more clear
public ActionResult copy(int OptionValueID,int CopyID)
{
//do Something
return View("Error");
}
Above is the Copy Method
OptionValueID = ViewBag.OptionValID //Got from the Action Method Index of SetValues
CopyID = Value from the DropDownlist
Edit Based on Answer
#using (Html.BeginForm("Copy","SetValues",FormMethod.Post))
{
<p>
#Html.DropDownList("CopyID", null, "Select")
<button type="submit" id="Copy" data-id="#ViewBag.OptionValID"> Copy </button>
</p>
}
now the page is being redirected but the no parameters are being passed. Should I be adding routevalues?
You cannot do it without javascript. Your ActionLink() method is parsed on the server before its sent to the client, so any route values are the initial values in the controller, not any edited values the user makes in the view. In order to respond to client side events you need javascript.
You can use ajax to post the values to the server method.
Include a button and handle its click event
<button type="button" id="Copy" data-id="#ViewBag.id">Copy</button>
Script
var url = '#Url.Action("Copy", "SetValues")';
$('#Copy").click(function() {
var optionID = $(this).data('id');
var copyID = $('#OptionValueID').val();
$.get(url, { OptionValueID: optionID, copyID : CopyID }, function(response) {
// do something with the response
});
});
or alternatively if you wanting to redirect, then replace the $.get() with
location.href = url + '?OptionValueID=' + optionID + '&CopyID=' + copyID;
Edit
Based on revised question and comments, if you wanting to post and redirect, there is no need for any javascript or the link. The dropdownlist needs to be #Html.DropDownList("CopyID", null, "Select") so that its selected value is bound to method parameter int CopyID and since the OptionValueID is not edited, then either add its value as a route parameter in the form
#using (Html.BeginForm("Copy", "SetValues", new { OptionValueID = ViewBag.OptionID }, FormMethod.Post))
or add a hidden input for the value
<input type="hidden" name="OptionValueID" value="#ViewBag.OptionID" />

Oracle APEX & JavaScript - Passing name of textfield in function NOT value

I have a function that will need the Name of a textfield, like P12_ACCOUNT_ID But when I call a function on that page with: callMyFunction('P12_ACCOUNT_ID'); it will pass the value of this textfield on to the function.
Is there a way to create a link to URL which will be javascript, and make P12_ACCOUNT_ID a varchar?
Just to be clear: I want my function to work with the varchar: 'P12_ACCOUNT_ID' and not with the value of that textfield.
This is the function to be called in which I want my page item to be loaded.
The link to this function now is: javascript:callMyPopup('P12_ACCOUNT_ID') but when it retrieves the content of this textfield and doesn't pass the string on by itself.
<script language="JavaScript" type="text/javascript">
function callMyPopup (paramItem) {
var hiddenField = document.getElementById(paramItem).value;
var url;
url = 'f?p=&APP_ID.:3:&APP_SESSION.::::P3_HIDDEN:' + hiddenField;
w = open(url,"winLov","Scrollbars=1,resizable=1,width=800,height=600");
if (w.opener == null)
w.opener = self;
w.focus();
}
</script>
As provided by Jeffrey Kemp but he didn't post an answer and I do want to close this question:
In Apex you can get the value of an item using $v(paramItem).

Categories

Resources