Display data on selected item with Laravel and Ajax - ajax

I'm trying to display the selected data from table to a modal using Ajax but seems no working. I used the restful routing in laravel. Data is successfully fetched but I'm stuck in displaying it inside the modal.
Controller:
public function show($project)
{
$project = Project::find($project);
return \Response::json($project);
}
Ajax:
$.ajax({
url: url,
data: data,
method: 'GET',
success: function(data) {
console.log(data)
$("#editProject").modal('show');
$('#editProject').find('.modal-body').html(data);
}
})
From console:

Related

ajax query without passing page data laravel 5.6

I have a button and when it's clicked, I basically want to load the Auth::user()->name and a date into the database. I can't figure out how to do an ajax call without passing in some sort of data. This is my ajax query.
var url2 = "/application-background-sent/{{$application->id}}";
$(document).ready(function(){
$('#bgSubmit').click(function(e){
$.ajax({
url: url2,
success: function(data) {
alert(data);
},
type: 'GET'
});
});
});
My route:
Route::get('/application-background-sent/{id}', 'ApplicationsController#backgroundSent');
My controller:
public function backgroundSent($id)
{
$application = Application::findOrFail($id);
$application->bg_check_submitted_by = Auth::user()->name;
$application->save();
return response()->json(['success'=>'Data is successfully added']);
}

How do I request views from a layout using AJAX?

In my MVC application I don't want the layout page to reload everytime a view is selected. It would be great if the views could be loaded using ajax to keep things nice and fast and allow me to persist certain interface states that are wiped out when you move around.
My initial approach was to add some ajax to the _Layout.cshtml and then whent he view was requested pass that request to the controller method which will grab that page. All I ended up doing however was returning the WHOLE view again.
Here is the code I have so far, am I on the right tracks here or is this totally wrong?
Layout Ajax Script
<script>
$(function () {
var content = document.getElementById('content');
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
console.log("Data Attrib : " + page);
$.ajax({
type: 'GET',
url: '#Url.Content("~/Home/")' + page,
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
</script>
As I say, this sort of works, but it's not perfect as it returns the whole page into the content area including layout, ideally I just want the core view data.
you can create a Single Page Application that have 1 layout and in home controller and index action method create menu or user setting or another things
and now you can load other action with Ajax call with data-content html that does not have layout file and append that in container
when user click another menu clean older content and add new or you can create tab strip or window
Layout.cshtml
<script>
$(function () {
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
$.ajax({
type: 'POST',
url: '/Home/Pages',
data: { pageValue: page },
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
Controller
public class HomeController : Controller
{
[HttpPost]
public string Pages(string pageValue)
{
string result = //Whatever
return result;
}
}
Controller
public ActionResult SomeAction(String someparams)
{
//Make the model
SomeModel someModel = new SomeModel();
someModel.someparams = someparams;
return PartialView("SomePartialView", someModel);
}
In View
$.ajax({
url: "/Home/SomeAction",
type: "POST",
dataType : "html",
data: json,
contentType: 'application/json; charset=utf-8',
success: function(data){
$('#SomeDivID').html(data);
}
});

Laravel cant submit ajax forms appended by javascript

I have implemented infinite scroll that appends html in the exact same manner as the static item with forms (inclusive csrf), but the dynamic forms that has been appended seems to be submitting without ajax and failing when pressing the submit button.
I get this error on the appended forms in console log:
Resource interpreted as Document but transferred with MIME type application/json:
The ajax submit.
$('.cart_add').on('submit',function (event) {
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (data) {
console.log("item has been added to cart");
event.preventDefault();
}
});
});
Edit I noticed that the jquery doesn't select the dynamically appended forms
Try setting your content type. The content type is the type of data sent to the server. In this case, you are sending data to the server which is interpreted as a Document (html) but is sent as json. This is because the browser is trying to infer what type of data your are sending becuase you did not explicitly state it.
Use the contentType to set it.
contentType: "text/html"
So your call should look like this:
$.ajax({
type: 'POST',
url: url,
data: data,
contentType: "text/html",
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (data) {
console.log("item has been added to cart");
event.preventDefault();
}
});

Rendar partial view in another partial view along with data model using jQuery .Ajax function

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.

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

Resources