Reputation: 620
I have an ajax function:
$.get('/updateAssignment', {title: title, id: id, class: subject, date: date, description: description}, function(data)
{
window.location.hash = data;
});
And it works fine, this is my function in my controller that is routed to the above ajax call:
public function updateAssignment()
{
// Bunch of code here
return 'hello world';
}
Now I know that whatever I return, will be in the jQuery variable data
, but I want more than one "value".
How would I return something like
return array('title' => $title, 'description' => $description, etc...)
to my data
variable in jQuery and be able to use it like:
$('h2').val(data['title']);
Or anything similar
Thank you in advance, I appreciate any help.
Upvotes: 2
Views: 2201
Reputation: 11
public class AssignmentViewModels
{
public string title { get; set; }
public string id { get; set; }
public string class { get; set; }
public string date { get; set; }
public string description { get; set; }
}
public JsonResult updateAssignment(string title, string id, string class, string date, string description)
{
var model = new AssignmentViewModels();// if you have a list of data return, make "List<AssignmentViewModels>()" ,& in Ajax sucess method, make a foreach loop & collect the data.
model = repository._update(title,id,class,date,description);//return updated data
return Json(model, JsonRequestBehavior.AllowGet);
}
var URL = ResolvedUrl.replace('ActionName', 'updateAssignment').replace('ControllerName', 'YourController');
var data = { title: title, id: id, class: subject, date: date, description: description };
$.get(URL, data, function (result) {
if ($('#h2')[0]) {
$('#h2').val(result.title);// no need to use JSON.parse
}
}
Upvotes: 1
Reputation: 29258
In Laravel 5, use response()
to return a JSON object from an AJAX call, like this:
return response(['title' => $title, 'description' => $description]);
In your Javascript, you would then access this data using object notation, so:
$.get("URL", function(data){
var title = data.title;
var description = data.description;
// Etc, etc
});
Upvotes: 2