Passing checkbox values between asp.net pages - javascript

On one ASP.NET page, I have a DataTable with a list of Investors. The client wanted a feature added that would allow their users to select individual investors from that list and and have an email button that would open up an email page and populate the bcc with the investor emails. So far, I have gotten the checkboxes implemented, and I am successfully going through the checkboxes and grabbing the emails of only the checked boxes. From this point, I am completely lost as to how to send that date over to the next page and have them fill into the bcc automatically. Here is my code so far:
<a onclick="grabEmail()" href="/Settings/EmailSelect" class="button blue" >Email Selected</a>
...
...
...
<script type="text/javascript">
function grabEmail() {
var emails = new Array();
var $checked = $('[#id=investoremails:checked');
$checked.each(function () {
emails.push($(this).val());
alert($(this).val()); //This was just to check to make sure emails
//were grabbed
}
);
$.ajax({
url: '/Settings/EmailSelect/',
type: "POST",
data: emails,
traditional: true,
});
}
Then, on EmailSelect page...
$(document).ready(function() {
$.ajax({
type: "GET",
url: "/Settings/EmailSelect",
error: function (xhr, status, error) {
$("#results").html("An error occurred: " + error).addClass("notification error");
return false;
},
success: function(response) {
if (response != null) {
if (!response.Successful) {
$("#results").html("An error occurred: " + response.Exception).addClass("notification error");
return false;
} else {
$("#bcc").val(response.ReturnVal);
}
}
}
});
});
And for the Controller..
public ActionResult EmailSelect(string[] emails)
{
ViewData["Selected"] = emails;
return View();
}
We have somewhat similar functionality in this program where Investors can be part of user created groups, and there's another email page where the user can select a specific group to email to, and I was trying to base the solution for this problem off that (even though they are inherently different..). If anyone can point me in the right direction, that would be great!

I should have answered this awhile ago, but I forgot to post it.
I did some research on MVC forms and how they interact with the controller, and I was easily able to get this to work by pulling the checkboxes in as a string array into the controller, and then passing them to the next page in ViewData.

Related

CRUD - Add and Delete not working one after other if page is not refreshed

I have one annoying problem that I am not able to solve.
I am generating CRUD operations in my Symfony project. I made an AJAX request for Add method which works as it should.
After that I have created AJAX request for Delete method.
When I add my new entity object the table is reloaded without page refresh.
Problem is that if I click delete after it's added it throws an error that ID is not found.
/**
* #Route("/user/{id}", name="user_delete", options={"expose"=true})
*/
public function delete($id)
{
$em = $this->getDoctrine()->getManager();
$$user = $em->getRepository(User::class)
->findOneby(['id' => $id]);
if (!$user) {
throw $this->createNotFoundException('No User found for id '.$id);
}
$em->remove($user);
$em->flush();
return $this->json(["message" => "SUCCESS"]);
}
So, for example I have added entity with ID = 2 . DIV is reloaded. Now I click in delete of 2 and it's says:
No user found for id 1
Problem is it always fatches the last ID I deleted after page refresh.
Now, if I refresh the page and then try delete it will catch ID = 2 and delete it. Now, I add ID = 3 without refreshing the page and it will throw:
No user found for id 2
I think maybe it has to do with my add form:
Add form:
$('#form-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/subscription/add',
data: $('form#subscription-form').serialize(),
processData: false,
success: function () {
$("#user-table").load(location.href + " #user-table");
$('#addUser').modal('hide');
displayNotif('success', 'check', 'User created successfully');
},
error: function (xhr, status, error) {
var ErrorMessage = JSON.parse(xhr.responseText);
$('#general-error').html(ErrorMessage.message);
}
});
});
Can someone please help?
$(document).ready(function () {
$('.user_delete').on('click', function () {
let removeUrl = $(this).attr('data-remove-url');
$('.remove-user').attr('data-remove-url', removeUrl);
});
$(".remove-user").click(function (e) {
let removeUrl = $(this).attr('data-remove-url');
e.preventDefault();
$.ajax({
url: removeUrl,
type: 'DELETE',
success: function()
{
$("#user-table").load(location.href + " #user-table");
$('#confirmDelete').modal('hide');
displayNotif("danger", "warning", "User deleted successfully");
}
});
});
});
I am adding everything so you can get an idea of what I am doing:
<a href data-toggle="modal" data-target="#confirmDelete" data-remove-url="{{ path('user_delete', {'id':user.id}) }}" class="btn user_delete">x</a>
Option 1:
The click event is not working properly for the delete button.
Try to replace
$(".remove-user").click
With
$(".remove-user").on(“click”
Option 2:
data-remove-url
this attribute is not updated accordingly. Check your DOM to verify

Get data from controller into same view page in php codeigniter

I'm trying to fetch messages when user clicks on a specific chat (you can say div which has hidden input fields for ids) just like messenger. The view is same on which i'm sending the data. First time when inbox opens up a chat list is added at the left side and the right is blank until user clicks on a chat.
Here is my code from which I get id when user clicks on the specific chatlist. I get ids through which i can fetch all messages. I'm using different models as I've different queries for both.
I dont know how to get json data which i got from ajax into php variable so that I've to loop through and display messages.
Attaching codes and pictures for references.
Model
public function get_msg($employer_id)
{
$query1 = $this->db->select()
->where('msg_from_id', $employer_id)
->group_by('msg_from',$employer_id)
->from('inbox')
->get('');
return $query1->result();
}
public function get_all_msgs($msg_from_id,$msg_to_id)
{
$conditions = array('msg_from_id' => $msg_from_id, 'msg_to_id' =>
$msg_to_id);
$query1 = $this->db->select()
->where($conditions)
->from('inbox')
->get('');
return $query1->result_array();
}
Controller:
public function get_all_msgs()
{
$postData = $this->input->post();
$msg_to_id= $postData['msg_to_id'];
$msg_from_id=$postData['msg_from_id'];
$this->load->model('employermodel');
$get_all_msgs=$this->employermodel->get_all_msgs($msg_from_id,$msg_to_id);
if($get_all_msgs!=NULL){
echo json_encode($get_all_msgs);
}
}
public function inbox(){
$emp = $this->session->userdata('user_email');
$emp_id = $this->session->userdata('user_id');
$employer_id=$emp_id;
if($emp_id == NULL){
return redirect('users/index');
}
$this->load->model('employermodel');
$get_msgs=$this->employermodel->get_msg($employer_id);
if($get_msgs!=NULL){
$this->load->view('inbox',['get_msgs'=>$get_msgs,]);
}
}
Javascript/ajax on same view page i.e. "Inbox" :
$('.msgs-ConversationListPane').click(function (e) {
if ($('.msgs-ConversationListPane').hasClass('is-active')) {
$(this).removeClass('is-active');
$('.msgs-ConversationPane').addClass('is-active');
$('.msgs-ConversationPane').removeClass('is-splash');
// $('.msgs-ConversationPane').load('.msgs-Conversation'.href);
$(".msgs-ConversationPane").html($("." + $(this).attr('rel')).html());
var msg_to_id = $('#msg_to_id').val();
var msg_from_id = $('#msg_from').val();
var get_all_msgs;
$.ajax({
type: "POST",
url:'<?=base_url()?>employer/get_all_msgs',
data: {msg_to_id: msg_to_id,
msg_from_id:msg_from_id},
dataType: 'json',
cache: false,
success: function (data) {
// JSON.stringify
get_all_msgs = data;
$("#res").html(get_all_msgs);
// console.log(get_all_msgs);
$(".msgs-ConversationPane").css('display', 'block');
},
error: function(xhr, status, error) {
console.log(error);
},
})
// .done(function(get_all_msgs) {
;
} else if ($('.msgs-ConversationPane').hasClass('is-splash')) {
$(this).removeClass('is-splash');
$(this).addClass('is-active');
$('.msgs-ConversationListPane').addClass('is-splash');
$('.msgs-ConversationListPane').removeClass('is-active');
}
});
You dont want to get the json data into a php variable. Php is executed server side, ajax is executed client side. The benefit of ajax usage is to dynamicly change the content after server execution is finished. You want to update the screen content via JavaScript (So only on the users end).
The next step is to extract the json data and to add a message div to the message container div.

Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.
The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.
Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.
What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)
What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
url: "save.php",
method: "POST",
data: { name: name.value, email: email.value, telephone: telephone.value },
success: $("List").load(" List")
});
}
Thank you in advanced and if I need include further info don't hesitate to ask.
From this comment
as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam
I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)
I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.
Thanks!
(Won't let me mark as answered until 2 days)
I would first create an AJAX call inside a function which runs when the page loads to populate the list.
window.onload = populatelist();
function populatelist() {
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'populate'},
success: function(data) { $("#list").html("data"); }
});
}
Note: #list refers to <div id="list> and your list should be inside this.
I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
success: function() { populatelist(); }
});
}
list.php should look like this:
<?php
if($_POST['function'] == "populate") {
// your code to get the content from the database and put it in a list
}
if($_POST['function'] == "update") {
// your code to update the database
}
?>
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:
PHP:
function doLoadMails(){
//initialize empty variable
$mails;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("");
}
//some select, insert, whatever
$sql = "SELECT ... ... ... ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row, j is counter for rows
$j =0;
while($row_a = $result->fetch_assoc()) {
//for each row, fill array
$mails[$j][0] = $row_a["name"] ;
$mails[$j][1] = $row_a["mail"] ;
$mails[$j][2] = $row_a["language"] ;
$j++;
}
}
//if $mails has results (we added something into it)
if(isset($mails)){
echo json_encode($mails);/return json*/ }
else{
//some error message you can handle in JS
echo"[null]";}
}
and then in JS
function doLoadMails() {
$.ajax({
data: { /*pass parameters*/ },
type: "post",
url: "dataFunnel.php",
success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
console.log(data); //you can check what you get
if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
}
});
Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.
In your solution, you will probably need to echo the return code of the INSERT request.

Trying to pass error message from Controller to View without page reload (MVC)

I'm trying to get my View to display an error message when the ActionResult from my controller fails. (It's triggered when you press a button in the View.)
However, no matter what I try, the ActionResult always redirects to a different page. If I try to return View() it goes to the default yellow ASP.Net error page. If I try to return Content("Error message") it just opens a blank page with that text.
I've saved my canned error message in ViewBag.Error, but the javascript in my View never gets a chance to use it because as soon as you click my button, the ActionResult redirects me somewhere.
How do I get my View to stay put, but still pass a message if the ActionResult fails?
Here is the method I'm calling in the controller:
public ActionResult ElectrodeChecklist(int id)
{
var routeChecklist = _routeService.GetRouteChecklist(id);
// This is where I'm trying to catch this error.
if (routeChecklist.Count == 0)
{
ViewBag.Error = "This route has no checklist steps to print.";
return ???
}
...
blah blah stuff to download a PDF file when everything works
...
return new BinaryContentResult(buffer, "application/pdf", filename);
}
Edit: Here's the view:
... dropdown menu called #dd-route...
Generate PDF
<script type="text/javascript">
$(function () {
$('#dd-route').change(function () {
var $route = $(this).val();
var $url = '#Url.Action("electrodechecklist", "wip")?id=' + $route;
$('#btn-print').attr('href', $url);
});
$('#btn-print').click(function () {
var $error = ViewBag.Error;
if ($error != "") {
$('#alertbar').show();
$('#alert').html($error);
}
})
});
</script>
When the user chooses an item in the dropdown menu, the url to call my ActionResult is fed into the button's href attribute. Then when they click the button, it fires it off with the correct value from the dropdown.
The second part of the JavaScript is my attempt at displaying the error message if they hit that If statement in the Controller.
I'm only writing this because it won't fit comments.
OK so first thing to notice is that it WILL start navigating to the Action ElectrodeChecklist with the id and then do what ever BinaryContentResult does. I cannot see how var $error = ViewBag.Error; could possibly work, but then again I'm not sure how/what BinaryContentResult really does.
If you want the user to see the ViewBag.Error then you need to modify this part
if (routeChecklist.Count == 0)
{
TempData["Error"] = "This route has no checklist steps to print.";
return RedirectToAction("ACTION", "CONTROLLER");
}
as suggested by #StephenMuecke. The ACTION here is the page the user was on in the first place. You could redirect them to any error page and still access the TempData["Error"]. If this still doesn't do what you want let us know.
//What you are trying to do here is awesome
//but I'm not sure if it's even possible as you are moving away from the page when the user clicks the button/link
//I'd like other please comment on this. I could use it too
$('#btn-print').click(function () {
var $error = ViewBag.Error;
if ($error != "") {
$('#alertbar').show();
$('#alert').html($error);
}
})
Check below code for without refreshing you can show the error message on page :
$('#dd-route').change(function () {
var TestModel = {
"id": $("route").val()
}
$.ajax({
url: '/wip/electrodechecklist',
type: "Post",
async: false,
data: JSON.stringify(TestModel),
dataType: "html",
contentType: "application/json;charset=utf-8",
success: function (result) {
var $error = ViewBag.Error;
if ($error != "") {
$('#alertbar').show();
$('#alert').html($error);
}
}
});
});
Hope this will help you !!

Having a hard time understanding redirecting / routing in laravel

I am completely stuck since two hours and definitely need your help. Disclaimer: I am not a coder - just a guy who is trying to mock up an idea.
So my page is actually working fine but I thought about moving content from a modal-popup to an actual sub-page. Meaning: If a user clicks on a button, some data points from the current page are being collected and passed to another view which shall be rendered using the data points as input.
EDIT: For clarification: The button is on /results.php where data is generated dynamically. The method should take some data points from here and generate a new view and render it at /buy.php or maybe at /buy/custom.php
My thoughts:
Normal redirect without parameters: Internal Link
Updating page-content without redirect but with parameters: Ajax
So combining my thoughts -> use ajax and return a new fresh view.
What I tried:
$("body").on("click", ".fa-shopping-cart", function() {
var $para1 = $(this).attr("data1");
var $para2 = $(this).attr("data2");
var $para3 = $(this).attr("data3");
var $para4 = $(this).attr("data4");
$.ajax({
url: "buy",
data: {
a: $para1,
b: $para2,
c: $para3,
d: $para4
},
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
type: "post",
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});});
Routing:
Route::post('/buy', 'PageRouting#buy');
Controller:
public function buy()
{
$para1= $_POST['a'];
$para2 = $_POST['b'];
$para3 = $_POST['c'];
$para4 = $_POST['d'];
// some magic to output $data
return view('pages.buy', compact("data"));
}
buy.blade.php exists and displays $data with help of an foreach-loop.
So, when I first clicked the button the obvious happend:
The view ('pages.buy') is logged / displayed in my console in plain html and not rendered in the browser.
Now I am sitting here since two hours and I have no clue whatsoever. I read some blog post saying that you cannot redirect within an ajax-call. Unfortunately the post did not gave any hint on how to do it instead.
Can someone help me?
All best
If you want to replace entire document with the response you have to use document.write but it's not the best thing to do. Why don't you use normal form submit if you need to return a view?
success: function(response){
document.write(response);
},
P.S. if you want also to change the url, use the history manipulation functions.
https://developer.mozilla.org/en-US/docs/Web/API/History_API
in your buy method -
public function buy ()
{
....//some stuff to get $data
$html = view('pages.buy', compact("data"))->render();
return response()->json([
'success' => true,
'html' => $html
])
}
in your ajax success function
success: function(response){
if(response.success)
{
$('#elementId').html(reponse.html) // or whatever you need
}
},

Categories

Resources