In a asp.net mvc project i have this on top of my index.cshtml file
$.ajax({
url: '#Url.Action("getLoggedUser", "Home")',
dataType: "html",
"async": true,
type: "GET",
success: function (data) {
},
});
And the method it uses is this one, that is on HomeController
public async Task getLoggedUser()
{
try
{
BenchesService benchService = new BenchesService();
UserTest LoggedUser = new UserTest();
string name = Request.RequestContext.HttpContext.User.Identity.Name;
name = name.Substring(name.LastIndexOf('\\') + 1);
LoggedUser = await benchService.getCurrentUser(name);
role = LoggedUser.role;
ViewBag.LoggedUser = LoggedUser.role;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
This does a GET to the server with getCurrentUser(name); and that returns a json with user info, that i use to fill a UserTest object (i checked with break and the LoggedUser is filled correctly).
I want to save the user Role, to use in the html / javascript part
Then again on my index.cshtml i have this other script
$(document).ready(function () {
setTimeout(function () {
console.log("TIMER!");
userRole = '#ViewBag.LoggedUser';
alert(userRole);
}, 5000);
My problem is that the alert shows a empty message, like the ViewBag.LoggedUser has nothing. am i using ViewBag wrong?
Are you reloading your page? If not, your ViewBag has the same content like in the moment when page was rendering. Razor render text from ViewBag only on creation of html page, and if you are not reloading page, it will be always empty. You have to return your data in some object (ex. json) to ajax request and then you can use it.
Related
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.
I have an Epi server page template with following property:
[Display(
Name = "Selection Box",
GroupName = Global.GroupNames.Contact
)]
public virtual bool SelectionBox { get; set; }
In the view I have something like this:
#if (PageEditing.PageIsInEditMode)
{
#Html.CheckBoxFor(modelItem => Model.CurrentPage.SelectionBox,
new
{
#class = "toggle",
#data_url = Url.Action("UpdatePage", "DefaultPage"),
})
<script>
$(function () {
$('.toggle').change(function () {
var self = $(this);
var url = self.data('url');
var value = self.prop('checked');
$.ajax({
url: url,
data: { selected: value },
type: 'POST',
success: function (response) {
alert(response);
}
});
});
});
</script>
}
Basically what it does, it when I change checkbox value, it sends request to controller and updates the value on the page. What I'm missing is that when this sucesfully happens, I would like the page reload but I can't find a way to do it.
I'm not using OOTB on page editing here, as I'm looking for a way to give editors some adavnced editing for the component, yet I don't want to build a dojo widget. Any ideas how to make this work?
There is a chapter on "On-page editing with client-side rendering" in the developer guides, see https://world.episerver.com/documentation/developer-guides/CMS/editing/on-page-editing-with-client-side-rendering/
The purpose of using Ajax is to design a SPA (single page application) where no page reload is required. If you are looking for a page reload, you can probably do
window.location.reload();
But a page reload might cause you to lose data return by the Ajax call.
This is the site.js code I am using to insert the PartialView into the main View.
$("#btn2").click(function () {
$.ajax({
url: "/Home/RefreshDoors",
datatype: "text",
type: "POST",
success: function (data) {
$('#DoorBox').html(data);
},
error: function () {
$("#DoorBox").html("ERROR");
}
});
});
I want to place the resulting table inside a box (div with the id="DoorBox") however as a result I get a raw view of the returned Door-Json-Objects:
(imgur-link to screenshot)
This is the div-code inside the view:
<div id="DoorBox">
</div>
This is the code from the HomeController I use to render the PartialView:
[HttpPost]
public PartialViewResult RefreshDoors()
{
return PartialView("_Doors", RefreshDoorsFunction().Result);
}
How do I get the code to insert the PartialView (just a table with the properties of the door-model displaying the doors)) to render within the div-box (without refreshing the page)?
Edit: Here is the code from the RefreshDoorsFunction():
public async Task<List<NewDoor>> RefreshDoorsFunction()
{
string token = await _auth.GetTokenAsync();
_doorList = SecureRestCall.GetDoorListAsync("https://exampleapi.azurewebsites.net", token);
return _doorList.Result;
}
I got the answer. Turns out I'm just stupid: I used the wrong button to test the ajax function (wrong id assigned to the button). It works now. Sorry for wasting some people's time.
How to auto refresh a partial view?
public PartialViewResult Chat(string people)
{
if (User.Identity.IsAuthenticated)
{
var model = new MessageVM()
{
realReceiver = people,
messageList = db.messages.Where(x => x.sender == User.Identity.Name || x.sender == people).ToList().Take(30)
};
return PartialView("_Chat", model);
How to auto refresh this partialview
Just to test quickly, change your controller action for Chat from POST to GET. Then call it by pasting the address in your browser address bar. You can include the value for people parameter like this at the end of the URL:
?people=valueForPeople
Check the returned HTML and ensure that is what you are expecting. Once you have confirmed the action is returning the HTML you want, then you can change back to POST if you prefer. Then use the jQuery code below.
One option is to setup a timer on the client side which will call your controller and then you can do whatever you need with the returned data.
window.setInterval(function() {
// send get request to server
$.ajax({
url: '/Chat',
type: "POST", // or use GET
data: whateverYourArgumentsAre, // people
success: function (partialViewHtml) {
$("#divLt").html(partialViewHtml);
});
},
error: function () {
alert('Something went wrong');
}
});
}, 5000); // Every 5 seconds, 5000 ms
Html.Action("Messages","Chat", new { people= "give some data"})
I am trying to update a value in my database. When the user presses the update button this script is called.
View Code:
<script>
function scr_UpdateQuote(field) {
var r = confirm("Are you sure you want to update your quote?");
if (r == true) {
var textBox_UserTitle = document.getElementById(field);
*CODE TO POST METHOD HERE*
}
}
</script>
In the controller, the value is then revived and saved into the database. A message is sent back to let the user know their quote was updated.
Controller Code:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
*REPLACE QUOTE IN DATABASE*
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}
I am having difficulty finding out how to write the code described between the **'s
(For the database part I have a user-id that can be used to identify the row)
You can use form posting like this:
$("#YourForm").submit(function() {
$.post("/YourController/UpdateQuote", $("#YourForm").serialize())
//this will serialize your form into:
// newQuote=someValue&&someOtherVariable=someOtherValue etc.
.done(function(data) {
// do what ever you want with the server response
});
})
or you can use an ajax post:
$.ajax({
type: "POST",
url: "/YourController/UpdateQuote",
data: {newQuote: document.getElementById(field)},
dataType: "json",
success: function(data) {
// do what ever you want with the server response
},
error: function(){
// error handling
}
});
For using the data, assuming you have an DbContext called MyDbContext:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
// get userID somehow, either from session, or pass as another parameter here
using (var dc = new MyDbContext)
{
var quoteToUpdate = dc.QuotesTable.FirstOrDefault(q => q.UserID == userID)
quoteToUpdate.quoteColumn = newQuote;
dc.SaveChanges();
}
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}