-3

I want to send data from JS file to PHP file where a function receives this data and performs further actions on it. But the problem is that the data isn't receiving from JS to controller function.

JS code:

$("#mybtn").click(function(){

  $.post(<?= base_url()?>+"upload",{a1: $('#a1').val(), a2: 
  $('#a2').val(), a3: $('#a3').val(), a4: $('#a4').val(),a5: 
  $('#a5').val()},function(data) {
  });

});     

Controller function:

function upload() {

  echo "this is upload";

  $data = array(
    'name' => $this->input->post('a1'),
    'email' => $this->input->post('a2'),
    'pass' => $this->input->post('a3'),
    'amnt' => $this->input->post('a4'),
    'pcode' => $this->input->post('a5')
  );

  $result = $this->pages_m->upload($data);

  var_dump($data);

}
tereško
  • 58,060
  • 25
  • 98
  • 150
aqib
  • 39
  • 8
  • Use simple jquery POST method to post your data variables. https://www.w3schools.com/jquery/jquery_ajax_get_post.asp – informer Jul 26 '17 at 09:32
  • am working in codeingetr 3 and am new to this i dont know how to perform database task – aqib Jul 26 '17 at 09:33
  • Need not panic. Its pretty much straight forward. Check the link and give a try. This will help you send data to your server from the browser/client. Once you receive the same on the backend you can process or persist in the database. – informer Jul 26 '17 at 09:35
  • can you just edit my code to ease my difficulty. thanx in advance – aqib Jul 26 '17 at 09:38

1 Answers1

2

first you declare this on header, after this you dont need to use base_url() function again in ajax.

<script>
   var url = <?php echo base_url(); ?>
</script>

$("#mybtn").click(function(){
 $.ajax({                    
  url: url+'upload',     
  type: 'post', // performing a POST request
  data : {
     a1: $('#a1').val(), 
     a2: $('#a2').val(), 
     a3: $('#a3').val(), 
     a4: $('#a4').val(),
     a5: $('#a5').val()
  },
  dataType: 'json',                   
  success: function(data)         
  {
    console.log(data)
  } 
  });
});

In controller

function upload()
 { 
  if($_POST){
     $data = array(
     'name' => $this->input->post('a1'),
     'email' => $this->input->post('a2'),
     'pass' => $this->input->post('a3'),
     'amnt' => $this->input->post('a4'),
     'pcode' => $this->input->post('a5')
     );
     $result = $this->pages_m->upload($data);
     if($result == true){
        echo "Successfully Save";      
     }else{
        echo "Error";
     }  
    }  
  }
Anand Pandey
  • 2,025
  • 3
  • 20
  • 39