Hi i am making my project in MVC, i which i want to add the control from the drop-down selection on right side div, (the black rectangle part in the image).
Now i have two requirements
Get the inner html or .html() of the right side div, and save this in the database along with the left side form values
I have another view details where i want to display the values of left side fields and render the inner html on right side, (i have the container div in my details view )..
i am getting the html with following button click function
$('#SaveCone').click(function () {
var a = $('#NewData').html();
console.log(a);
});
tell me please if you want another details, thanks for your kind help
this is nice question
If you want to store your html into the database, simply use ajax ,
$('#urbutton).click(function () {
var a = $('#yourForm).html();
$.ajax({
type: 'POST',
url: '/UrController/Uraction',
data:
$('#MyForm').serialize() + "&par2=" + a,
success: function (data) {
// ` alert(data);
}
});
});
your controller looks like this
public ActionResult Create(Table table, string par2)
{
using (urcontext cntxt = new urcontext ())
{
if (ModelState.IsValid)
{
table.data = par2;
cntxt.SaveChanges();
}... so on
this will store your data into database
How to render the Html from database to the view
simply use
<div id="container">
#HTML.Raw(model.data)
< /div>
Hope this will help you man
Related
I am trying to render a Blade template in Laravel that contains an HTML table with data obtained via AJAX, and need to manually paginate the results using Laravel's LengthAwarePaginator.
I have a main blade file called reports.blade.php which contains an AJAX call to a controller method called SalesController#get_sales_forecast. Within that controller, I am fetching some data from a MSSQL database and rendering a partial view called sales-forecast-table that puts the data in an HTML table. That is all working successfully.
However, I am now trying to paginate those results because the data set is very large.
In my main blade file (reports.blade.php), the AJAX call looks like this:
$.ajax({
type: 'POST',
url:'{{action('SalesController#get_sales_forecast')}}',
data: {
_token: $('meta[name="_token"]').attr('content'),
start_date: $('#txtStartDate').val(),
end_date: $('#txtEndDate').val()
},
success:function(data) {
$('#table-sales-forecast').html(data.html);
}
});
Furthermore, reports.blade.php includes a partial view:
<div class="table-responsive" id="table-part-forecast-annual">
#include('sales-forecast-table')
</div>
The AJAX call goes out to SalesController#get_sales_forecast, which looks like this:
public function get_sales_forecast(Request $request) {
//Get data from Sales model
$sales_forecast = Sales::getSalesForecast($start_date, $end_date);
//Get current page
$current_page = LengthAwarePaginator::resolveCurrentPage();
//Create new collection
$item_collection = collect($sales_forecast);
//Define how many items to show per page
$page_limit = 25;
//Slice the collection to get the items to display in current page
$current_page_items = $item_collection->slice(($current_page * $page_limit) - $page_limit, $page_limit)->all();
//Create paginator
$paginated_items = new LengthAwarePaginator($current_page_items, count($item_collection), $page_limit);
//Set URL path for generated links
$paginated_items->withPath($request->url());
//Render the view as an HTML string
$html = view('sales-forecast-table')->with(['sales_forecast' => $paginated_items])->render();
//Return the HTML
return response()->json(compact('html'));
}
And the view being rendered from the AJAX call (sales-forecast-table.blade.php) looks like this:
#if(isset($sales_forecast))
{!!$sales_forecast->links()!!}
<table class='table table-hover table-striped table-bordered'>
#foreach($sales_forecast as $record)
<tr>
<td>{{$record->id}}</td>
<td>{{$record->location}}</td>
<td>{!!$record->customer!!}</td>
<td>{!!$record->forecast!!}</td>
#endforeach
</table>
#endif
At this point, the table does render and the page links even appear. The table only displays the first 25 rows as expected (per the $page_limit = 25 line) with page 1 selected, but when I click on any of the other page links, I simply receive a "No message" error. The error message is so vague that I'm not quite sure where to go from here. Perhaps I am using AJAX within Laravel in an overly complicated way? I was trying to stick to the conventions of the framework as much as possible, but I am open to trying it a different way if that would make this problem easier.
I am assuming that getSalesForcast is a scope so it should return a collection. I would recommend using forPage. I am not 100% sure how you are getting your start date and end parameter in the request, but given those values this should work. Also, I am assuming you are using timestamps.
const $page_limit = 25;
public function get_sales_forecast(Request $request) {
//Get current page
$current_page = LengthAwarePaginator::resolveCurrentPage();
//Get data from Sales model
$sales_forecast = Sales::where('created_at','>',$request->input('start_date'))
->where('created_at','<',$request->input('end_date'))
->forPage($current_page,self::$page_limit)
->get();
//Create paginator
$LengthAwarePaginator = new LengthAwarePaginator($sales_forecast, $sales_forecast->count(), self::$page_limit);
//Set URL path for generated links
$paginated_items->withPath($LengthAwarePaginator->url($current_page));
//Render the view as an HTML string
$html = view('sales-forecast-table')->with(['sales_forecast' => $LengthAwarePaginator->items()])->render();
//Return the HTML
return response()->json(compact('html'));
}
So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.
I would like to have a page that would contain:
hyperlik "Add new country".
After clicking this link by user, dropdown list with names of countries should appear. However this hyperlink should stay on this page. When user click this hyperlink once again, second dropdown list with exactly the same names should appear. This should be repeat as long as user clicks hyperlink.
It is important that this page shouldn't be reloaded.
Does anyone has any idea how can it be made?
The typical way to achieve this is to have your Add new country link trigger an ajax call out to a page you create which will provide the data for your list.
The preferred method these days seems to be having that page you call build up a JSON response, then your callback on the ajax method where you called it can populate that data into a drop down.
The page you call from AJAX could be something simple like this:
protected override void Render(HtmlTextWriter writer)
{
Dictionary<string, int> myStuff = new Dictionary<string, int>();
myStuff.Add("country1", 1);
myStuff.Add("country1", 2);
JavaScriptSerializer jss = new JavaScriptSerializer();
Response.Write(jss.Serialize(myStuff.ToList()));
Response.ContentType = "application/json";
}
Use this jQuery on your main page:
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
getCountries();
});
});
function getCountries() {
$.ajax({
url: "ApiPage.aspx",
dataType: "json",
success: function (data) {
for (var i in data) {
$("#myDropDown").append($('<option></option>').val(data[i].Value).html(data[i].Key));
}
}
});
}
</script>
Tested and working. (in a simplified example) I did have to convert from Dictionary to List for the json serializer to make it an array as desired. See the updated Serialize call. There is also some validation, e.g. did the ajax call return real data?, that would need added to a real life implementation.
It looks like you are doing it a least approximately right.
in the HTML if you have some tag that surrounds the area you want the drop down box to then it is simple.
for example:
in HTML:
Add new country
<div id="dropdownarea"></div>
in javascript:
function addDD(){
document.dropdownarea.innerHTML += "HTML code for the drop down that you want";
}
I have a form, with 2 fields, that are select lists.
I need to select an option from select_list_1 that then populates select_list_2
I have the following in my template:
<script type="text/javascript">
$(document).ready(function() {
$('select#sf_guard_user_profile_corp_id').change(function() {
$.ajax({
url: "updateAreaManager?corp_id=" + this.value,
dataType: "text/html",
success: (function(data) {
$('select#sf_guard_user_profile_area_manager_id').html(data);
})
});
});
});
</script>
This calls the executeUpdateAreaManager method, which currently is simply:
public function executeUpdateAreaManager(sfWebRequest $request)
{
$id = $request->getParameter('corp_id');
}
Would someone be able to help me get the data I need into the second select list?
Thanks
I am guessing that since you have a corp_id being passed to your action, you are trying to get a list of Managers based on a corp_id value.
In your action, you can query your database in order to get a result set, by doing something like:
$q = Doctrine_Query::create()->from('Manager m')->innerJoin('m.Corps c')->where('c.id=', $id);
$results = $q->execute();
You then can pass the results to your javascript, whatever way you want. I suggest straight HTML at this point. Your code will ressemble something like this (still in your action.class.php file):
echo "<p>Hi, I came from an action.</p>";
return true;
At this point, your javascript should be displaying that HTML on your page. Make it generate what you n eed, assuming an HTML form in your case.
I'm trying to figure out how to use AJAX to create a Twitter-like feed that displays user's posts on the same page immediately after they push the submit button. It would be an infinite-feed site that would have a "more" button at the bottom.
All I'm trying to make is a simple page containing a textarea box with a submit button and to have user submissions appear below the box as they are submitted.
If possible, a walk through or discussion of the script needed to do this would be great.
Thanks so much
All you need is a server-side script with an SQL query that would return newer posts.
have your javascript store a variable of the date or of the last post id (used PHP for clarification):
result = mysql_query("SELECT ID,POST FROM POSTS WHERE DATE>" . $_GET['date']); //or use WHERE ID> $_GET['id']
while(rows[] = mysq_fetch_array(query));
print json_encode(rows);
now you have a server-side script that will return new posts, so all you have to do is write javascript function for the more button:
updatePosts = function () {
$.ajax({
url: 'serversiderUrl?lastId=' + last_id, //last_id is global variable for the id of the last post on the page
success: function(data){
data = JSON.parse(data);
for(i in data){
$('#posts_container').append(data[i].post); //do your appending functions here
last_id = data[i].id;
}
}
}
now for posting new entries create a server-side script of your favorite language that handles new posts:
result = mysql_query("INSERT INTO POSTS VALUES(''," . urldecode($_POST['POST']) . ")");
now for the client side:
submit_post = function(){
$.ajax({
type: 'POST',
url:'yourposturl',
data: "post=" + encodeURIComponent($('#textArea').text()),
success: function(){
updatePosts(); // call the function that update the posts so the new entry is now added to the page
}
});
}
Now bind the functions to the appropriate buttons when the document is fully loaded:
$(document).ready(function (){
$('#moreButtonId').click(updatePosts);
$('#submitButtonId').click(submitPost);
});
There are many ways such as the submit button kept sending it to the database while we'd append text to a container underneath. Or we can update the container underneath to create a container (page) that are similar, after the ajax response is successful then we append the data to the container beneath
$.post(url,function(data){
//Here you can append the data responsed by the ajax request to the container underneath
});
But you have to have a exactly same view with a conatiner (feed container) existing in the currently page