ajax call does not hit to controllers function, what is the reason and why I am not understanding kindly guide me
I am trying to send ajax call to controller update the record this is my ajax code
$(document).ready(function() {
$(".update").click(function(event) {
debugger;
event.preventDefault();
var vehno = $("input#vn").val();
var vbrand = $("input#vb").val();
var vmodel = $("input#vm").val();
var vcolor = $("input#vcol").val();
debugger;
$.ajax({
type: "ajax",
method:"Post",
url:'<?php echo base_url('index.php/vehicleCtrl/FunUpdate')?>',
//async:false,
dataType: 'json',
data: {vehicle: vehno, brand: vbrand, vmodel:vmodel,vcolor:vcolor},
success: function(res) {
alert("working");
// if (res)
// {
// // Show Entered Value
// jQuery("div#result").show();
// jQuery("div#value").html(res.username);
// jQuery("div#value_pwd").html(res.pwd);
// }
},
error:function(res){
alert(res);
}
});
});
});
this Controller's Function
this is a codeigniter controller
public function FunUpdate()
{
$as= $this->input->post('vehicle');
$id=-1;
$vehicleArray = array('vehicleNo' => $this->input->post('vehicle'),
'Brand' => $this->input->post('brand'),
'Model' => $this->input->post('vmodel'),
'Color' => $this->input->post('vcolor'),
);
echo json_encode($vehicleArray);
$Result=$this->VehicleModel->Update($vehicleArray,$no);
if($Result)
{
$data= array('error' =>'Vehicle Update Successful');
$data["DetailList"]=$this->VehicleModel->FunDetailSearch($no);
$data["EditTrack"]=$this->VehicleModel->EditTrackDetail($id);
$data["NewVehicle"]=$this->VehicleModel->FunfindVehicle($no);
$this->load->view('Layout/header');
$this->load->view('vehicle/create',$data);
$this->load->view('Layout/footer');
}
}
ajax request should look like this
$('#buttonid').click(function(){
var vehno = document.getElementById('vehno').value;
var brand = document.getElementById('brand').value;
$.ajax({
url:'<?=base_url()?>index.php/Controller/function',
method: 'post',
data: {vehno: vehno, brand: brand},
dataType: 'json',
success: function(response){
alert('data updated');
}
});
});
function
public function updateDetails(){
// POST data
$postData = $this->input->post();
//load model
$this->load->model('Main_model');
// get data
$data = $this->Main_model->updateVehicle($postData);
echo json_encode($data);
}
Modal
function updateVehicle($postData){
$response = array();
if($postData['id'] ){
$this->db->where('id',$postData['id']);
return $this->db->update('vehicle',$postData);
}
Hope Now You Update Your Data With Ajax
Related
I'm trying to create a notification feature and I wanted the ajax to be able to run a query via the controller on button click
THIS IS MY SCRIPT
$('#noti_Button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>'
});
});
THE CONTROLLER
public function read_notif(){
$this->profile_model->read_notifs($data['id']);
return;
}
AND THE MODEL
function read_notifs($id)
{
$read = array(
'read' => '1'
);
$this->db->where('recipient', $id);
$this->db->update('tbl_notifications', $read);
return;
}
I tried this and the data in the database doesn't update.
IN MY HTML IT IS JUST A SIMPLE BUTTON
Script
$('#noti_Button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>',
success:function(data)
{
alert(data);
}
});
});
Controller
public function read_notif(){
$this->profile_model->read_notifs($data['id']);
echo $this->db->last_query();
}
It is the sample calling the ajax in ruby on rails . In this code we are calling the controller for getting the values.
$('#Button').on('change', function(event) {
var selected_resource_id = $(this).val();
$.ajax({
type: 'GET',
url: "<%= Home_index_path %>",
data: { id: selected_resource_id },
success: function (data) {
alert("Ajax success");
}
});
});
use error: to check if there's any error in submitting your form.
$('#button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>',
success:function(data)
{
alert(data);
}
});
});
In controller I have a _remap() for routing.
My controller is as follows:
public function _remap($id)
{
$this->index();
}
public function index()
{
$this->accesscontrol->can_or_redirect('view', 'translation');
$this->output->view('translation/language');
}
function process(Request $request){
// if(Response::ajax()) return "OK";
return json_encode(array('ok'));
}
My view is as follows:
$('#lang_choice1').each(function() {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?=site_url('translation/language/process')?>',
data: msg,
success: function(data){ }
});
return false;
});
I am trying to call the function process in ajax and its not getting called. How do I need to modify the _remap function to call ajax calls as well?
Try This
Script part
$('#lang_choice1').each(function () {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?= site_url('language/process') ?>',
data: {"msg":msg},
dataType:"json",
success: function (data) {
console.log(data);
}
});
return false;
});
Controller process function
function process() {
$data = $this->input->post();
$result['status'] = "ok";
$result['response'] = $data;
echo json_encode(array($result));
exit(0);
}
Check response in console
I wanted to show products from db using infinite scroll.
Here is my Controller:
$start=0;
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
$response->setData(array('classifiedList' => $list));
return $response;
}
Ajax:
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
getmoredata();
}
})
function getmoredata() {
$.ajax({
type: "GET",
url: "{{ path('classified_list', {'type' : 'all'}) }}",
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
},
error: function (response) {
console.log(response);
}
});
}
So now what is happening is the first 6 results is repeatedly showing when the scrolling is triggered. I know this is not correct and I don't expect this to work properly. But what I don't know is what is the next step.
So do I need to add paginator or something?
Any help would be appreciated,Thanks!
You need to track whether your ajax is requesting or not, so it will not do request multiple times when window reach the scroll limit. Also, you need to track the offset and whether you have more data to loads. e.g
window.__isFetching = false;
window.__offset = 0;
window.__hasMoreData = true;
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
if(!window.__isFetching && window.__hasMoreData) {
getmoredata();
}
}
})
function getmoredata() {
window.__isFetching = true;
$.ajax({
type: "GET",
// NOTE, you can pass current offset here in url
url: "{{ path('classified_list', {'type' : 'all', }) }}"+"&offset="+window.__offset,
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
// Note that here, server side response must have next offset and hasMoreData attribut.
window.__isFetching = false;
window.__hasMoreData = response.hasMoreData;
window.__offset = response.offset
},
error: function (response) {
console.log(response);
}
});
}
in server side , which is symfony, you might want to do something like:
// Get offset from request query
$start= $request->query->get('offset');
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
// And add offset and hasMoreData fields in response
$response->setData(array(
'classifiedList' => $list,
'offset' => $start += 1
'hasMoreData' => count($list) < ($limit * &start)
)
);
return $response;
I have to return a return a multidimensional associative arrays from PHP page for a jQuery AJAX function.
This is my PHP page called 'seachsongs.php'
<?php
$brano = $_POST['brano'];
$sql = "SELECT Titolo, Autore FROM Brani WHERE Titolo = '$brano';";
$ris = $conn->query($sql);
while ($row = $ris->fetch_array()) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
?>
This is my jQuery AJAX function
$(document).ready(function () {
$('#nBrano').keyup(function () {
nomeBrano = $(this).val();
$.ajax({
type: "POST",
data: {brano: nomeBrano},
url: "searchsong.php",
success: function (data) {
document.write(data);
//alert("Prova" + data['data'][0]["Titolo"]);
/*if (msg != 'null') {
$('#similarSongs').css('display', 'block');
/*$.each(prova, function (key1, value1) {
$.each(value1['two']['three'], function (key1, value1) {
document.write('test');
});
})
$('#similarSongs table').html(tabella);
}
if (msg == 'null') {
$('#similarSongs table').html("Nessun brano simile trovato");
$('#similarSongs').css('display', 'block');
}*/
},
error: function () {
//alert('errore');
}
});
});
});
How can I access to array data from jQuery? What is the correct statement?
alert(data)
print this
{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}
PS: sorry form my bad english.
I've set the data type of this request to be json, so the response returned should be a json object. You can access it by this way:
$(document).ready(function () {
$('#nBrano').keyup(function () {
nomeBrano = $(this).val();
$.ajax({
type: "POST",
data: {brano: nomeBrano},
url: "searchsong.php",
dataType:'json',
success: function (response) {
for(var i=0; i<response['data'].length; i++){
console.log(response['data'][i][/*your_target_index*/]);
}
},
error: function () {
//alert('errore');
}
});
});
});
see more about ajax
I have a question about javascript and cakephp, I need to send data via Post and recive it in the other side (the controller) and make the normal process that I already have. But I don't know how can I catch the data. I'm working with Ajax
function editFun(clicked_id){
var id = clicked_id;
$("#Content").empty();
$('#Content').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: '/Posts/edit',
data: (id)
})
.done(function(data){
console.log(data);
$('#Content').html(data);
})
.fail(function(data){
$('#Content').html(data);
});
}
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
In that case you should send your id in URL. So even GET method is enough, because you controller receive $id param from URL.
So all what you need to change are post arguments:
$.ajax({
type: 'POST',
url: '/Posts/edit/' + id
})