How to pass data from a html page to another? - javascript

I have two pages:
choose.html
create.html
In the choose.html I can choose an entry from a listview. I can click on such entries in the listview and I want to pass the ID of that entry so that I can use the ID on the html page create.html.
ID is a number.
I have done:
When I clicked on an entry, I get the ID:
function postID(id) {
alert(id);
}
This functions so far.
Then I tried this code with a GET on the create.html:
POST:
function postID(id) {
$.ajax({
url: "create.html",
type: "POST",
dataType: "text",
data: id,
success: function () {
document.location.href = "create.html";
},
error: function (jqXhr) {
alert("Error");
}
});
}
GET:
try {
$.get("chooseAddress.html", function (id) {
alert(id);
});
}
catch (e) {
alert();
}
But nothing happens. Can you help me?
Thanks

So many work for so simple problem. Use a hidden field or use a Session variable.

Use create a hidden field and give value as your Id.
<form action='create.html'>
<input type='hidden' value='id'>
</form>

Related

I can't pull data from database because of $(this).data(temsilci_mail)

'I can't pull data from database because of $(this).data(temsilci_mail). I want to use email address as id'
$(document).ready(function() {
// Temsilci Listesi Modal
$('.temsilcibilgi').click(function() {
var userid = $(this).data('temsilci_mail');
$.ajax({
url: 'ajax-modal/temsilci-listesi-modal.php',
type: 'post',
data: {
userid: userid
},
success: function(response) {
$('.modal-body').html(response);
$('#temsilcilistesimodal').modal('show');
}
});
});
});
I suppose the $('.temsilcibilgi') selector return an array of button elements and you set up a temsilci_mail data to all of theses earlier. Because if you use $(this).data('temsilci_mail') you need to put the mail as a data before.
You can check if temsilci_mail data exist by logging button element like console.log($(this)) or by looking at the inspector and check that data-temsilci_mail attribute exist in each button.
If your problem is not that userid is undefined, then please give more precise information about your problem.

create onclick event for multiple ids

I have written a js function:
$(document).on('click', '#id1', function () {
$.ajax({
type: "POST",
url: "/url",
data: { uInput: 'id1' },
success: function (response) {
some code....
},
error: function (error) {
console.log(error);
}
});
});
Problem is, since I have more clickable objects with various IDs, i wanted to create a single script/function that would accept onclick event from not only #id1, but also #id2, #id3 etc...
I tried following advice found here: https://stackoverflow.com/a/18508894/11271927
and here https://stackoverflow.com/a/18508907/11271927
but whenever I would edit the code to acomodate my code structure, it wouldnt work.
var options = {
id1: 'id1',
id2: 'id2',
id3: 'id3',
id4: 'id4'
};
$('.options').click(function () {
$.ajax({
type: "POST",
url: "/url",
data: options[this.id],
success: function (response) {
some code....
},
error: function (error) {
console.log(error);
}
});
});
Essentially, this code doesnt do anythign on click.
If you know what I have missed or done wrong, please help.
If you want to have one function that will have a click listener on several elements (for example by class) you can try it like this:
<button class="button" id="id1">A</button>
<button class="button" id="id2">B</button>
<button class="button" id="id3">C</button>
<script>
$(document).on('click', '.button', function () {
$.ajax({
type: "POST",
url: "/url",
data: {
uInput: this.getAttribute('id'),
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
});
</script>
You can set a single click event listener on the document and use a conditional inside its function to apply the same statement block to any groups of elements.
For example, you could filter for targets that have id begining with the string "id" like this (core js):
document.addEventListener('click', event => {
if (event.target.id.indexOf('id') == 0) {
// commands to apply to those elements;
} // end if #id* click;
// any number of other groups or individual elements can be added, each with a conditional to filter the required ones.
}); // end event listener
If you require more specificity, refine the conditional, for example (inside the document event listener function):
const id=event.target.id;
if (id == "id1" || id == "id3" || id == "somethingElse") {
// relevant statements;
};
I generally use document event listeners by default, there is no extra computational cost and I find the single event listener easier to maintain.

How to retrieve the elements of a dropdownlist in jquery and send it with ajax to an MVC Controller in ASP.Net?

I have a select item as follows:
<select id="id_category">
<option> </option>
</select>
In run time there is a tree view used to fill up the select menu as follows:
<script>
$(document).ready(function () {
$('#data').jstree({
"plugins": ["checkbox"]
});
$("#data").on("changed.jstree", function (e, data) {
if (data.selected.length) {
$("#id_category").empty();
$(data.selected).each(function (idx) {
var node = data.instance.get_node(data.selected[idx]);
var s = document.getElementById('id_category');
s.options[s.options.length] = new Option(node.text, '1');
});
}
else
$("#id_category").empty();
});
});
</script>
and the html for the tree is not important now as it works well.
Now, I want when a user click on a button with HTML as follows:
<input id="btn3" type="button" value="Test 3" />
an ajax will be run to send all the items in the select to a controller in MVC as follows:
$("#btn3").click(function () {
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: $.map($('#id_category')[0].options, function( elem ) { return (elem.value || elem.text); }),
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
and the controller:
[HttpPost]
public string Test03(Object str1)
{
// call with two parameters and return them back
this.myRetrievedData = str1;
return str1.ToString();
}
The above did not work with me, when I click on Test3 button nothing happened.
I am not sure how to pass the retrieved items to the function in the controller. Could anyone tell me how to do that?
The below logic must work for you. Many thanks to Mr.Stephen Muecke for assistance.
$("#btn3").click(function () {
var optionsData= $.map($('#id_category')[0].options, function(elem) {
return (elem.value || elem.text);
}); // create a variable to hold all the options array.
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: JSON.stringify(optionsData), //pass this variable to post request as 'options'
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
Then you can have your controller as below.
[HttpPost]
public string Test03(IEnumerable<string> options ) // change here to this
{
//your logic goes here
}
I think it's because you have not added [HttpPost] attribute in your controller function

How can I pass a Django template context variable to JS function

I am trying to create a simple web link toggle for following or unfollowing a question in my app. I got close using the info My Own Like Button: Django + Ajax -- How? but am not quite there.
My problem is that I cannot dynamically pass question.id to my JS function as the answer in the above link implies. Ie
The hard-wired JS code below DOES work. It passes '12' as a valid param for the view tied to /question/follow-unfollow-inline/. But when I try to replace '12' with a context variable '{{ question.id }}' from the template that calls this JS code, my function passes the string '{{ question.id }}' back to /question/follow-unfollow-inline/ rather than it's value. How do I fix this?
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': '12' },
success: function (e) {
alert('Success!');
}
});
});
});
For now, I'm using #csrf_exempt on my view, but I know I should pass it as data.
You could define it on your anchor tag with data- attribute:
Template:
<a id="follow_unfollow_toggle" href="#" data-qid="{{ question.id }}">Like</a>
Js file:
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': $(this).data('qid') },
success: function (e) {
alert('Success!');
}
});
});
});

MVC3 AJAX passing data to controller. It's being submitted twice

So I have a table that gets transformed to an array using:
var result = $("#enrolledStudents").sortable('toArray');
But when I go a head an pass that into my controller like so:
$("#update-enroll").click(function () {
var result = $("#enrolledStudents").sortable('toArray');
$.ajax({
url: '#Url.Action("Enrollment", "Classroom")',
data: { students: result },
type: 'POST',
traditional: true
});
});
My debugging breakpoint gets set off twice, causing issues to arise. What is the proper way to submit data to my controller on POST?
Per my comments, there are a couple things that could be causing this.
You have have the unobtrusive file(s) loaded multiple times
Your form has an action method defined, and your button is inside the form tag as a submit button. This will submit the form, and then the click will also submit the form - see example
Example
<form action="/somerowout/someaction">
<input type="text" id="text1"/>
<input type="text" id="text1"/>
<input type="submit" />
</form>
If you need to validate a value on your form before posting, don't hook up an additional Ajax call. Your javascript will look something like:
$(document).ready(function () {
$("form").submit(function(){
var result = $("#enrolledStudents").sortable('toArray');
if(result == null){
//do something to show validation failed
return false;
}
return true;
});
});
And your form code would then look something like:
#using (#Ajax.BeginForm(new AjaxOptions { })) {
<input type="text" id="text1"/>
<input type="text" id="text1"/>
<input type="submit" />
}
If you want to use Ajax rather than the Html Helpers, use a div instead of a form, and you won't get a duplicate post. Here's how you could achieve this:
<div id="enrolledStudents">
<--! your elements -->
<button id="saveStudents">Save</button>
</div>
JavaScript
$(document).ready(function () {
$("saveStudents").click(function(){
var result = $("#enrolledStudents").sortable('toArray');
if(result !== null){ /* do some kind of check here. */
$.ajax({
url: '#Url.Action("Enrollment", "Classroom")',
data: { students: result },
type: 'POST',
traditional: true,
success : function(data) {
if (data.status) {
window.location = data.route;
}
}
})
} else {
/* notify ui that save didn't happpen */
}
});
});
Example Controller Action
When posting your data using Ajax, here's an example of how to pass the route
[HttpPost]
public ActionResult SomethingPost(SomeModel model) {
if (Request.IsAjaxRequest()) {
var json = new {
status = true,
route = #Url.RouteUrl("MyRouteName", new { /* route values */ })
};
return Json(json, JsonRequestBehavior.AllowGet);
}
}
Are you sure you are preventing the default behaviour (form POSTING) of the submit button ? use preventDefault to do so.
$("#update-enroll").click(function (e) {
e.preventDefault();
//rest of the code
});
EDIT : As per the comment
To do the redirect in the ajax handler, you need to return the URL to be redirected in a JSON Response back to the calle.
[HttpPost]
public ActionResult Classroom(string students)
{
//do some operaton
if(Request.IsAjax())
{
//This is an Ajax call
return Json(new
{
Status="Success",
NewUrl = Url.Action("Index","Home")
});
}
else
{
//Normal request. Use RedirectToActiom
return RedirectToAction("Index","Home");
}
}
Now in your ajax call check the JSON result and do the redirect.
$.ajax({
url: '#Url.Action("Enrollment", "Classroom")',
data: { students: result },
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if(data.Status=="Success")
{
window.location.href = data.Newrl;
}
else
{
alert("some error");
}
}
});
Check if you don't have the jquery files loaded twice. I had this behavior and the problem was files loaded twice.

Categories

Resources