Change view with ajax or jquery in mvc - javascript

I am trying to send data and change view. I put breakpoint, second view worked but not show to me. I don't want to use Html.BeginForm because I am working with hmtl and javacript.
public ActionResult Second(int id)
{
List<Properties> users = GetData(id);
return View(users);
}
$('select').on('change', function (e) {
//var id = $(this).find(":selected").val()
var id = this.selectedIndex;
var targetUrl = '/Home/Second/' + id.toString();
$(this).load(targetUrl);
});

I Fix that
$('select').on('change', function (e) {
var id = this.selectedIndex;
var targetUrl = '/Home/Second/' + id.toString();
location.href = targetUrl;
});

Related

ajax.post returns index html but not the html that I should get after a post

So I'm trying to build a JS script that allows me to automatically enroll in courses in uni once they're available, and what I've gotten so far is filling the boxes with course IDs and then clicking submit but then I realized using ajax to post would be a better way than simulating a click.
The problem is, the returned html after a post is just a normal html with no success msg on enrolling neither failure. Here is my code:
const courses = ['56895', '56712', '56812']
function findnewreg() {
var index = 0
courses.forEach(element => {
index++;
var ind = "crn_id" + index;
document.getElementById(ind).value = element
form = document.getElementById(ind).form
});
var regbtn = document.getElementsByName('REG_BTN')
regbtn.forEach(element =>{
if(element.value=='تنفيذ التغييرات'){
//element.click();//<form action="/PROD/xwckcoms.P_Regs" method="post" onSubmit="return checkSubmit()">
submitForm()
console.log("clicked")
document.addEventListener("DOMContentLoaded", function(event){
if (document.body.textContent.includes("لقد قمت بإجراء العديد من المحاولات لتسجيل هذا الفصل الدراسي، اتصل بمكتب التسجيل للحصول على مساعدة. ")) {
console.log('⛔️ error retrying...');
//history.back();
findnewreg()
}else{
console.log('✅ success');
}});
}
})
}
function submitForm(){
var form = form = document.getElementById("crn_id1").form
var href = '/PROD/xwckcoms.P_Regs'//form.getAttribute("action");
var formData = {};
jQuery(form)?.find("input[type=text]").each(function (index, node) {
console.log(index, node)
formData[node.name] = node.value;
});
// formData = jQuery(form).serialize() //also tried this, same result
jQuery.post(href, formData).done(function (data) {
prompt('DATA:' , data)
findnewreg();
});
}
findnewreg();

UPDATED: redirect url pass parameter from another page

I'm would like to do a 2 step process without the user knowing. Right now when the user click on the link from another page.
URL redirect to run some JavaScript function that updates the database.
Then pass the variable to view a document.
User clicks on this link from another page
Here is some of code in the JavaScript file:
<script type="text/javascript">
window.onload = function(){
var auditObject ="";
var audit_rec = {};
var redirLink = "";
if(document.URL.indexOf('?1w') > -1 {
redirLink = "https://www.wikipedia.org/";
auditObject = redirLink;
audit_rec.action = "OPEN";
audit_rec.object = auditObject;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
window.open(redirLink);
} else {
audit_rec.target = /MyServlet;
audit_rec.action = "OPEN";
audit_rec.object = TESTSITE;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
}
function audit(audit_rec) {
var strObject = audit_rec.object;
strObject = strObject.toLowerCase();
var strCategory = "";
if (strObject.indexOf("wiki") > -1) {
strCategory = "Wiki";
} else if strObject.indexOf("test") > -1) {
strCategory = "TEST Home Page";
}
//Send jQuery AJAX request to audit the user event.
$.post(audit_rec.target, {
ACTION_DATE : String(Date.now()),
DOMAIN : "TESTSITE",
ACTION : audit_rec.action,
OBJECT : audit_rec.object,
OBJECT_TYPE : audit_rec.object_type,
STATUS : audit_rec.status
});
}
//TEST initial page load.
audit(audit_rec);
}
</script>
Can someone help? Thanks
You could give your link a class or ID such as
<a id="doclink" href="http://website.com/docviewer.html?docId=ABC%2Fguide%3A%2F%2F'||i.guide||'">'||i.docno||'</a>
then use javascript to intercept it and run your ajax script to update the database. Here's how you'd do it in jQuery:
$('#doclink').click(function(e) {
var linkToFollow = $(this).attr('href');
e.preventDefault();
yourAjaxFunction(parameters, function() {
location.href = linkToFollow;
});
});
where the function containing the redirect is a callback function after your ajax script completes. This stops the link from being followed until you've run your ajax script.
if your question is to hide the parameters Here is the Answer
you just use input type as hidden the code like this
'||i.docno||'

How get values variable javascript from razor?

i have soure code :
$("#yes-modal").click(function (e) {
var img = $("#url").val();
window.location = '#Url.Action("DownloadImages", "Hrd", new { id = *value variable img* })';
});
i want get value img, but i have error.
How can do it ? thank you.
Below syntax should work.
window.location = '#Url.Action("DownloadImages", "Hrd", new { id = ' + img + '})';
Let me know if you face any issue.
The razor syntax is a serverside code. It is evaluated while rendering the page from server. But the javascript is evaluated at the client side (browser). So you have to split it like below code.
$("#yes-modal").click(function (e) {
var img = $("#url").val();
var loc = '#Url.Action("DownloadImages", "Hrd")';
var loc += '?id=' + img;
window.location = loc;
});

Know which Form is submitted

I have eight Forms in a page (Form0, Form1, Form2 and so on). When a form is submitted, data is handed by JS and send to ReassignPreg.php, which search data in DB and send it back with json. Then the proper divs on the page are updated.
The code below is doing its job. But I have eigh copies of almost the same code, one for each Form (I only copy two of them for brevity). Newbie and amateur as I am, I wander which would be the way for synthesize this code (get Form name, and then pass that to only one function).
<script type="text/javascript">
$(document).ready(function(){
$("#Form0").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});
});
$(document).ready(function(){
$("#Form1").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox10").html(imagen)
$("#PregBox11").html(obj.Clase)
$("#PregBox12").html(obj.Dificultad)
$("#PregBox13").html(obj.Tipo)
});
return false;
});
});
</script>
A little more modularity helps a lot
$(document).ready(function () {
$("[id^=Form]").on('submit', function (e) {
e.preventDefault();
var _form = this.id.slice(-1); // 0, 1, etc
var cadena = $(this).serialize() + '&form=' + _form;
$.get('ReassignPreg.php?cadena=' + cadena, function (row) {
var image = $('<img />', {
src : "../ImageFolder/" + row.File + ".png",
width : 530
});
$("#PregBox"+_form+"0").html(image);
$("#PregBox"+_form+"1").html(row.Clase);
$("#PregBox"+_form+"2").html(row.Dificultad);
$("#PregBox"+_form+"3").html(row.Tipo);
}, 'json');
});
});
now you'll have a form key on the server containing the number of the form, for instance in PHP you'd get that with $_GET['form'] etc.
you could add an hidden field to each form with an ID/name and use that to identify the form submitting
You may need to assing classes to your PregBox elements and then target them accordingly to the form's ID.
$('form').submit(function(){ // listen to all form submissions.
var formID = $(this).prop('id'); // get the form ID here and do what you like with it.
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});

Trying to refresh page using Jquery post and ActionResult

I've been trying to make the "RedirecttoAction" statement work here but it doesn't budge. Here is the method:
[HttpPost]
public ActionResult UpdateTech(int tech, int id)
{
Callout callout = db.Callouts.Find(id);
callout.TechnicianId = tech;
callout.TechStatus = "ASSIGNED";
db.Entry(callout).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("CalloutAdmin/Index/");
}
And it is called by the following JQuery, which works perfectly:
$(function () {
$(".techdropdown").change(function () {
var recordToUpdate = $(this).attr("id");
var selectedTech = $(".techdropdown option:selected").val();
window.alert(selectedTech);
$.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate);
});
});
The only thing that does not happen is the page being refreshed, which was what the redirect should do. Can anyone advise?
UPDATE
What I am trying to do is update this Callout object, without redirecting to another view. I choose a technician from a dropdownlist and it automatically sets the callout's technician value to the one I chose from the dropdown.
You're returning the redirect to the AJAX request, and the AJAX request is loading the page in the background. If you want to have the entire page redirect you probably want to use the success callback in jQuery
$.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate, function() { document.location = "CalloutAdmin/Index/"; } );
If you want to have the action control the location of the redirect, you probably want to use the return a JsonResult or ContentResult from your action with the URL outputted from there have jQuery's success callback redirect the user.
Assuming that UpdateTech and Index both belong to CallOutAdminController then change your UpdateTech Method to look like:
[HttpPost]
public ActionResult UpdateTech(int tech, int id)
{
Callout callout = db.Callouts.Find(id);
callout.TechnicianId = tech;
callout.TechStatus = "ASSIGNED";
db.Entry(callout).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index","CallOutAdmin");
}
Then make you jQuery function like this:
$(document).ready(function(e) {
$(".techdropdown").change(function () {
var recordToUpdate = $(this).attr("id");
var selectedTech = $(".techdropdown option:selected").val();
window.alert(selectedTech);
window.location = "/CallOutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate
});
});

Categories

Resources