Get data from controller into same view page in php codeigniter - javascript

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.

Related

How to auto refresh a partial view?

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

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 !!

How to use ajax to save re-ordered node in Drupal 7?

I use the Jquery .sortable() function to let the site admin re-order some list elements on the start page on a Drupal 7 site. Then I want the admin to be able to save the node to keep this new sort order. In order to do this I added a Save button with js on the client side. When clicked on I have this so far:
$('a.save').on('click', function () {
// get the current nid
var nid = Drupal.settings.mymodule.currentNid;
var data = [];
// copy the re-ordered html list
data['body'] = $('.field-name-body').clone()
$.ajax({
// after reading the ajax api documentation I am more than confused about the url to use
url: '??',
type: 'post',
dataType: "html",
data: {
nid: nid,
body: data['body'].html()
},
success: function(data) {
if (data == false) {
alert('Not saved, access denied.');
} else {
alert('Changes saved');
}
}
});
So in the normal world I would write a php script that saves the data in the node with the specified node id. And the url should point to that script... But I am stuck in the Drupal 7 documentation on how to do this... All examples i can find describes how to pull html from the server side to the client side, but I want to copy html from the client side and save it in the specfied node on the server side. Should I write a function to recieve the ajax request in a custom module? Can anyone point me in the right direction?
PARTIALLY SOLVED:
I finally found the solution about the url which became like this:
url: Drupal.settings.mymodule.ajaxUrl + "/" + nid,
I have now written a custom module where I successfully can save content in a certain node field with this code:
function save_node_init() {
drupal_add_js(array('save_node' => array('ajaxUrl' => url('save_node/ajax'))), 'setting');
drupal_add_js(drupal_get_path('module', 'save_node') . '/save_node.js');
}
function save_nod_menu() {
$items['save_node/ajax/%'] = array(
'page callback' => 'save_node_ajax_callback',
'access callback' => 'user_access',
'access arguments' => array('administer users'),
);
return $items;
}
function save_node_ajax_callback() {
$html = isset($_POST['body']) ? $_POST['body'] : null;
$nid = isset($_POST['nid']) ? $_POST['nid'] : null;
$node = node_load($nid);
$node->body['und'][0]['value'] = $html;
node_save($node);
//ajax_deliver($html);
drupal_exit();
}
As you can see I put the html in the body of the node and then saves it. My final problem is now that I don't want to replace the whole content in the body field. Just the ul and its list elements. Any suggestions would be much appreciated!

Calling a HTTP POST method in a MVC Controller from the View's Javascript & Database saving

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

using ViewBag - asp.net mvc

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.

Categories

Resources