Problems when passing parameter by POST via Ajax

Asked

Viewed 60 times

0

I’m having trouble passing parameters via POST to my PHP methods. I have the variable in JS properly populated with the attributes I want to pass on. But when trying to access the variable in my PHP code it says that it is undefined. I am using Codeigniter as a framework.

JS Code:

var arr = [];
var vars = arr.concat(put, pedidoData);
$.ajax({
   url: "controller/metodo",
   type: 'POST',
   data: {vars:vars},
   success: function(r) {
     if (r.status == "success"){                                                       
         console.log("Sucesso");
     }else{
         console.log(vars);
         console.log("erro na inserçao");
         console.log(r);
     }
   }
});

Code of the controller.php :

public function metodo(){
    $resposta = $this->input->post();
    $response = $this->meumodel_model->metodo($resposta);
    if(is_null($response)){
        $this->response(array("status"=>"erro", "erro"=>"Resposta nula ou vazia."), 200);
    }else{
        $this->response($response, 200);
    }
}

Code of meumodel_model.php:

  public function metodo($vars = array()){

    $variaveis = array();
    $inserir = "SQL utilizando as variaveis...";
    $q = $this->db->query($inserir); 

    if($q){
        return array("status"=>"success");
    }else{
        return array("status"=>"error");
    }
}

I’d like to know what I’m doing wrong. Thank you.

  • the value of the url in Ajax should not be in quotes?

  • Yes, I passed wrong to the question, the original code is. Thank you for the =D alert

  • Just to check, are you sure that the error is related to variable? I ask to make sure that you used the $this->load->model('meu_model_model); in your constructor method, because if you didn’t, you’re trying to call the model without loading it before.

  • Hello error was solved by declaring data_type, which in case was a JSON

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.