开发者

jQuery AJAX form not sending

开发者 https://www.devze.com 2023-03-27 20:14 出处:网络
Why isn\'t this data being sent to my controller? No sign of jsonForm in firebug. No success alert. JS

Why isn't this data being sent to my controller? No sign of jsonForm in firebug. No success alert.

JS

$('form').submit(function() {

  var title = $('#title:input').val();

  alert(title);

  var urlsStr = $("#links").val();
  var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
  var formData = {
    "title": title,
    "urls": urls
  }
开发者_JS百科  var jsonForm = JSON.stringify(formData);                

  $.ajax({
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: { jsonForm: jsonForm },
    url: 'publishlinks/publish',
    success:
      function(response) {
        alert('winrar');
      }
    })
})

Controller

function publish() {

  $form = $this->input->get('jsonForm');

  echo json_decode($form);

  $data = array(

  'movieid' => $this->input->post('id')

  );

  $this->load->model('publish_model');
  $this->publish_model->add_record($data);
  $this->load->model('NewsFeed_model');
  $feed['queryMovies'] = $this->NewsFeed_model->getPublications();        
  $this->load->view('news_feed_view', $feed);     

}


Don't forget semicolons. They can be important. And, dataType in the ajax request refers to the data coming back from the request not the data being sent by the request.

Start with modifying your ajax:

$('form').submit(function(e) {
    e.preventDefault();

    var title = $('#title:input').val();

    alert(title);

    var urlsStr = $("#links").val();
    var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
    var formData = {
       title: title,
        urls: urls
    };                

  $.ajax({
    type: 'GET',
    cache: false,
    data: formData,
    url: 'publishlinks/publish',
    success:
      function(response) {
        alert('winrar');
      }
   });
});

Your data will be attached as query string which your controller can then pick up. From the documentation:

The data option can contain either a query string of the form key1=value1&key2=value2, or a map of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent.

Modify your controller to pick up the query string vars.

Here is a fiddle: http://jsfiddle.net/jensbits/2F4kN/


Didn't you meant to do: url: '/publishlinks/publish', with a relative path? Also you can add a failure callback to the ajax function: http://api.jquery.com/jQuery.ajax/

Also you should really add a return false; add the end of the $('form').submit(function() { function to prevent the form from being submitted the 'normal' way.

Or use:

$('form').submit(function(e)

e.preventDefault();
e.stopPropagtion();
0

精彩评论

暂无评论...
验证码 换一张
取 消