简体   繁体   中英

Displaying returned json data from controller with AJAX

I am trying to send a POST submission to a controller, and want to receive a json string back so that I can then append the information to a table. Here's what I have so far:

My AJAX call:

$('#addTicketButton').click(function(){
      $.ajax({
          type:'POST',
          url:'<?php echo site_url();?>ticket_system/add_ticket',
          data:{
              'headline': $("#headline").val(),
              'description': $('#description').val(),
              'category': $('#category').val(),
              'priority': $('#priority').val(),
              'assigned': $('#assign').val()
          },
          datatype: 'json',
          success: function(data){
            $("#created_table > tbody:last-child").append("<tr><td>" + data[0].ticketId + "</td><td>" + $("#headline").val() + "</td><td>" + data[0].lastUpdated + "</td></tr>");
          }
      });
});

My Controller:

public function add_ticket()
{
    $ticket = array(
        'headline' => $this->input->post('headline'),
        'description' => $this->input->post('description'),
        'category' => $this->input->post('category'),
        'priority' => $this->input->post('priority'),
        'assigned' => $this->input->post('assigned'),
        'userId' => $this->userId
    );
    $ticketId = $this->tickets->addTicket($ticket);
    $ticket = $this->tickets->getTicketByTicketId($ticketId);
    $success = array(
        'ticketId' => $ticketId,
        'lastUpdated' => date("M d, Y H:i A")
    );

     echo json_encode($success);
}

I have also tried it just using:

 data.ticketId

but that didn't work either.

Any help would me greatly appreciated. Thank you!

Not sure, but you can try this:

Controller:

$success = json_encode($ticketId||date("M d, Y H:i A")); //added '||' between the results

Ajax :

d =  data.split("||"); //break the results
$("#created_table > tbody:last-child").append("<tr><td>" + d[0] + "</td><td>" + $("#headline").val() + "</td><td>" + d[1] + "</td></tr>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM