javascript - ajax data is getting null in controller function of MVC
Get the solution ↓↓↓I am beginner to ajax and MVC framework. I have to find mobile exist or not using ajax. I have tried following code.
View
if(mno.match(phoneno)){
//alert(mno);
$.ajax({
url: "/api/sales/existmobile",
type:"POST",
//ContentType: 'application/json',
// dataType: "json",
//async: false,
//data:{'data': mno},
//data:{data: JSON.stringify(mno)},
data:{data: JSON.stringify(6547655566)},
success: function (data, textStatus, jqXHR) {
console.log('success',data);
if(data === false){
alert('Mobile number already exists!');
$( "#custmobilenumber" ).focus();
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
}
Route
case "sales/existmobile":
$sale = new Sale($data);
$result = $sale->checkMobileExistSale($result);
break;
Controller
public function checkMobileExistSale($result)
{
print_r($this->data);
// $custMdl = new CustomerModel();
// $mobileExistResult = $custMdl->checkMobileExist($this->data);
// return $mobileExistResult;
}
Model
public function checkMobileExist($mobile){
$sql = 'SELECT * FROM customers WHERE mobile= :mobile';
$placeholders = [':mobile'=>$mobile];
$users = $this->select($sql, $placeholders);
if (count($users) > 0) {
return false;
} else {
return true;
}
}
When I print data of ajax passed in controller then its coming null. In inspect's Network(XHR)->Headers->form data, I can see data passed from ajax. But Network(XHR)->Response, its showing null.
I debugged with every possible way i could find with stackoverflow anwsers and google search but no use. I am not getting where the code is going wrong.
Please help and guide. Thanks in advance.
Answer
Solution:
in ajax you are using post method then you have to use in controller
$this->input->post('data');
try this it will work for you
Answer
Solution:
I've written a possible rectified code for your problem, I've mentioned the comments wherever necessary, see if it helps you. :)
Route
case "sales/existmobile":
$sale = new Sale($data);
$result = $sale->checkMobileExistSale($data); // send $data here not $result
break;
Controller
public function checkMobileExistSale($result)
{
echo $result;
// print_r($result);
// or try $result = $this->input->post();
// $custMdl = new CustomerModel();
// $mobileExistResult = $custMdl->checkMobileExist($result); // send relevant data here
// return $mobileExistResult;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: method illuminate\database\eloquent\collection::paginate does not exist.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.