I have a foreach loop in my view
<div class="col-lg-6 collapse" >
<div class="job-summ-panel" id="job-summ-panel" >
#foreach($jobs as $job)
{{$job['active']}}
#endforeach
</div>
</div>
I also have a Google map on the page with map markers and when I click a map marker an ajax call is made to get all the info related to the page
$.ajax({
method: "get",
url: '/joblocation/jobsummary',
data: {
job_ref: marker.getCustomData('job_ref'),
},
success: function (response) {
$('.collapse').collapse('show');
$('#job-summ-panel').html(response.jobs)
},
});
Jobs will initially be empty when they first load the page so it wont display anything. I dont get how to refresh/reload the div and do the foreach again with the new response data.
There are two ways to achieve this. First, is server-side generation, and second is client-side application.
1. Server side content generation
You might want to move that part of the page to a different blade template. Then with a AJAX call, you can rebuild the page and send the output to the browser. For example:
Route Definition
Route::post("generateList", "Partials#generateList");
Partial Template Definition
Partials\loopContainer.blade.php
<div class="col-lg-6 collapse" >
<div class="job-summ-panel" id="job-summ-panel" >
#foreach($jobs as $job)
{{$job['active']}}
#endforeach
</div>
</div>
Your Partial Content Generator
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Partials extends Controller {
public function generateList(Request $request){
// generate data from the parameters again
$input = $request->input('job_ref');
$generatedData = GenerateDataFromJobRef($input);
return View::make("partials/loopContainer", ["jobs" => $generatedData]);
}
?>
Client Side Refresh
$.ajax({
method: "POST",
url: '/generateList',
data: {
job_ref: marker.getCustomData('job_ref'),
},
success: function (response) {
$('.collapse').collapse('show');
$('#job-summ-panel').html(response)
},
});
2. Client side content application
Route Definition
Route::post("generateList", "Partials#generateList");
Your Partial Content Generator
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Partials extends Controller {
public function generateList(Request $request){
// generate data from the parameters again
$input = $request->input('job_ref');
$generatedData = GenerateDataFromJobRef($input);
return json_encode(["data" => $generatedData]);
}
?>
Client Side Refresh
$.ajax({
method: "POST",
url: '/generateList',
data: {
job_ref: marker.getCustomData('job_ref'),
},
success: function (response) {
$('.collapse').collapse('show');
var appendString = "";
for(var i = 0; i < response.data.length; i++){
appendString += "<div>" + response.data[i].info + "</div>";
}
$('#job-summ-panel').empty().append(appendString);
},
});
Related
Hello guys need some help
In my controller:
public function index() {
$data['myvar'] = 'hai';
$this->load->view('Bank/Main',$data);
}
In view:
echo $myvar ;
its works ... i can view my variable
but in another function in same controller
public function getdatafromview() {
$data['myvar']=$this->input->get('keywordid'); --> from post
$this->load->view('Bank/bankModal',$data);
}
in view :
echo $myvar ;
It did not work. I cannot view my variable in my view class="modal" ?
Message: Undefined variable: myvar
Filename: Bank/Main.php
variable : myvar from function(getdatafromview) not store in ci_cached_vars
Post variables won't be available via get only post. Further, you should plan for errors such as this and remove the modal entirely when the variable isn't defined via a condition block:
Pseudo code:
{if !isset($myvar)} {modal} {/if}
Solved By this method
Post data from view :
<td style="width: 100px;">
<span data-original-title="Edit" class="lnr lnr-pencil" data-toggle="tooltip" data-placement="top" title=""></span>
</td>
step 2 in controller :
public function get_datamodal(){
$komemo=$this->input->get('keywordid');
$data=$this->M_bank->get_bank_by_kode($komemo);
echo json_encode($data);
step 3 in model :
function get_bank_by_kode($komemo){
$hsl=$this->db->query("SELECT * FROM m_bank WHERE idbank='$komemo' order by unikid desc");
if($hsl->num_rows()>0){
foreach ($hsl->result() as $data) {
$hasil=array(
'idbank' => $data->idbank,
'cnamabank' => $data->cnamabank,
'cnorekening' => $data->cnorekening,
'cstatus' => $data->cstatus
);
}
}
return $hasil;
}
step 4 in view ui modal :
put under the div element :
<script>
$(document).ready(function(){
$('#posteidt').click(function(){
var id=$(this).attr('data');
$.ajax({
type : "GET",
url : "<?php echo base_url('Bank/get_datamodal?keywordid=xxx')?>",
dataType : "JSON",
data : {id:id},
success: function(data){
$.each(data,function(idbank,cnamabank){
$('#bankModal').modal('show');
$('[name="kdbank"]').val(data.idbank);
$('[name="nmbank"]').val(data.cnamabank);
//console.log(data);
});
}
});
// return false;
});
});
</script>
I have a problem that I was stacked on for a while. I am rather new to this stuff so please be patient. I think it is like very simple to solve but I am running circles now. My intention is to make a simple alert that informs that method was completed. As you can see below my first attempt was made with simple string and if statement. I dont want to reload the page any more but now I have a problem that method ends later than alert script starts.
So I have a controller:
[HttpPost]
public ActionResult Executor(LMCMainViewModel model)
{
var curlsExecutor = _curls;
var applicationPurgeCurl = curlsExecutor.GetApplicationCurl(model);
var temporary = model.SuccessExecutionStatus = curlsExecutor.CurlCaller(model.ApplicationList.ApplicationCurl);
var tempListOfApplications = PopulateModel(model);
model.ApplicationList.ListOfApplications = tempListOfApplications.ApplicationList.ListOfApplications;
model.SuccessExecutionStatus = temporary;
return View("ListOfApplications", model);
}
And I have my view:
#model LMC.Models.LMCMainViewModel
#{
ViewData["Title"] = "Liberation";
}
#using (Html.BeginForm("HeaderString", "LMC"))
{
}
#using (Html.BeginForm("Executor", "LMC", FormMethod.Post))
{
<div class="col-sm-2" asp-action="ListOfApplications">
#Html.DropDownListFor(x => x.ApplicationList.ChosenApplication, Model.ApplicationList.ApplicationListItem, new { #id = "DropdownID" })
</div>
<div class="col-sm-2 col-sm-push-5">
#Html.HiddenFor(x => x.ApplicationList.ApplicationListItem)
<input class="btn ctn-success" id="submit" type="submit" value="Submit" />
<button id="submitButtonAjax" type="button" class="btn btn-success">Ajax button</button>
<div class="col-sm-12">
#Html.Label(null, (Model.SuccessExecutionStatus ? "Success" : " "),
new { Style = Model.SuccessExecutionStatus ? "color: green;" : "color: red;" })
</div>
</div>
}
Than I tried to implement many variations of Ajax script but I got so twisted that I can't even post you the best one... One thing I know is that when I remove: #using (Html.BeginForm("Executor", "LMC", FormMethod.Post)) and try to place it into Ajax it simply doesn't work. My intention is to have something that would work like this:
<script type="text/javascript">
$("#submitButtonAjax").on("click", function () {
$.ajax({
type: 'POST',
url: "/LMC/Executor",
success: function () {
alert("Went well");
}
});
</script>
I tried to convert controller method return into Json but it didnt work as well. I would appreciate any advices, where I can read about anything similar(I am aware that there are probably many similar topics, but I wan't able to implement anything that was working into my code, because I find my question one step backwards in comparison to others), or maybe it is that easy and I am missing something and you can just post a solution. Anyway, many thanks for any help.
The ajax call should look like bellow
$( document ).ready(function() {
$("#submitButtonAjax").on("click", function () {
var postData = {
FirstPropertyOfTheModel: ValueForTheFirstProperty,
SecondPropertyOfTheModel: ValueForTheSecondProperty,
};
$.ajax({
type: 'POST',
url: "/LMC/Executor",
data:postData,
success: function () {
alert("Went well");
},
error: function () {
alert("Opssss not working");
}
});
});
});
data is the value for the model of ActionResult method of the controller. The FirstPropertyOfTheModel and SecondPropertyOfTheModel will be replaced by the name of property and assign the corresponding value respectably. At url you can use
'#Url.Action("Executor", "LMC")'
so the ajax will look like
$( document ).ready(function() {
$("#submitButtonAjax").on("click", function () {
var postData = {
FirstPropertyOfTheModel: ValueForTheFirstProperty,
SecondPropertyOfTheModel: ValueForTheSecondProperty,
};
$.ajax({
type: 'POST',
url: '#Url.Action("Executor", "LMC")',
data:postData,
success: function () {
alert("Went well");
},
error: function () {
alert("Opssss not working");
}
});
});
});
Need to delete a record without using form tag. Just pass a id in url and get a id need to process.
Thanks
follow below steps
HTML
Delete
JS
$('a#btnDelete').on('click',function()
{
var thisElement = $(this);
$.ajax({
type: 'post',
url: "{{url('/')}}" + '/deleteRecord/'+thisElement.attr('thisRecordId'),
data : {'_token': '{!! csrf_token() !!}'},
async: false,
success:function(response)
{
console.log(response)
}
});
});
Route
Route::post('deleteRecord/{id}','YourController#deleteRecord');
Controller
public function deleteRecord($id)
{
$findRecord = ModelName::findOrFail($id);
$findRecord->delete();
return 'success';
}
hope you will find your solution !
Try like this
<a type="button" class="label label-danger" href="/user/delete/{{$user->id}}">Delete</a>
Controller method
public function getDelete($id)
{
echo $id;
}
i need to fetch data from database from controller file and display into element file and ajax value showing in inspect element and also when i alert in ajax it is showing that value is going to controller.
but problem is that how can i echo or print ajax value in controller to fetch data from database and display it into element file?
how can i render custom element file in controller function?
ajax script
<script>
$('#categories .accordion .tablist .tablistitem').on('click', function () {
event.preventDefault();
$(".accordion li").removeClass("active");
var $li = $(this);
$liid = $li.attr('id');
$slug = $li.data('slug');
$li.addClass("active");
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#categories_info').show();
$.ajax({
type: 'POST',
url: '/reviews/getsubcategories',
data: {"selectid":$liid },
dataType:"text",
success: function(data, textStatus, xhr) {
alert(data);
},
error: function(xhr, textStatus, error) {
alert(textStatus);
}
});
});
</script>
controller function
function getsubcategories()
{
echo $selectid= $_POST['selectid'];
return $selectid;
}
element file
$SubCategoryObj = cri('Reviews');
$selectid = $SubCategoryObj->getMainCategories();
echo $selectid;
What you have done so far is mostly right, however in the past I have just created the view as normal in the View/Reviews folder.
In the controller set your data:
/app/Controller/ReviewsController.php
public function getsubcategories()
{
$this->layout = 'ajax';
$data = /**code to get data**/
$this->set('data', $data);
}
/app/View/Reviews/getsubcategories.ctp
<?php echo json_encode($data); ?>
another option is to create the same view above but put it in file app/View/Ajax/json.ctp
And then inside the controller the last thing you call in the getsubcategories action is.
$this->render('Ajax/json');
In my experience elements are used inside views and not as replacements of views
I am working on MVC 5 app and I want to render partialView in another partialview with model data using jQuery ajax function. when javaScript function is called, it suppose to send ID of selected element back to controller which is working fine, and in return bring partial view along with model which is not working from following code
<td>
<a href="#" class="SearchUser_Icon Hyperlink_Text" onclick="load_getUserListByGroupID(this)" id=#item.GroupID></a>
</td>
.
JavaScript function
function load_getUserListByGroupID(element)
{
var selectedGroupID = element.id;
alert(selectedGroupID);
$.ajax({
type: "POST",
url: "/UserManagement/SearchUsersByGroupID/",
dataType: "json",
data: { 'GroupID': selectedGroupID },
success: function (viewHTML) {
alert("success");
$("#userContentBlock").html(viewHTML);
},
error: function (errorData) { onError(errorData); }
}).done(function (result) {
alert("done!");
});
}
.
<div id="userContentBlock"></div>
Controller Method
[HttpPost]
public ActionResult SearchUsersByGroupID(string GroupID)
{
int intID = Convert.ToInt32(GroupID);
var UsersListByGroupID = _userServices.GetUsersByGroupID(intID);
return PartialView("GetUsersListByGroup_Partial", UsersListByGroupID );
}
You are returning HTML while expecting JSON in the ajax call. Just remove the dataType: "json" from the settings and everything should work as expected.
jQuery.ajax() dataType:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.