2

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.

1
  • Try to return a JSON string from your controller and access individual components with data.title for example. Commented Mar 2, 2016 at 15:09

2 Answers 2

2

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
});
Sign up to request clarification or add additional context in comments.

Comments

1
    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
            }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.