I am trying to update my database using ajax in laravel. When i click the button (toggle button) it should update the database enable column from 1 to 0.
Here is the script written in the view
$(".toggle-btn").change(function() {
var id = $(this).attr('name'); // $(this) refers to button that was clicked
$.ajax({
url: '/adminpanel/dviulaan/stt',
method: "post",
data: {'id' : id} ,
dataType: "json",
});
});
Here is my route
Route::post('adminpanel/dviulaan/stt', 'AdminDvAnnouncement#status');
And here is the controller function
public function status()
{
$id = Input::all();
if (Request::ajax()) {
DvAnnouncement::where('announcement_id', $id)->update(
[
'enable' => '0',
'user_updated' => Auth::user()->id,
'updated_at' => new DateTime,
]);
}
$response = array(
'status' => 'success',
'msg' => 'Option created successfully',
);
return Response::json( $response );
}
When i click the button it shows the following error in the consol
POST http://localhost/adminpanel/dviulaan/stt 500 (Internal Server Error)
Please help me to find the error.
I have even changed the controller method as below
public function status(Request $request)
{
$id = Input::get('id');
if (Request::ajax()) {
DvAnnouncement::where('announcement_id', $id)->update(
[
'enable' => '0',
'user_updated' => Auth::user()->id,
'updated_at' => new DateTime,
]);
}
$response = array(
'status' => 'success',
'msg' => 'Option created successfully',
);
return Response::json( $response );
}
$id = Input::all(); => $id = Input::get('id');
UPD after logs
include in head
<meta name="csrf-token" content="{!! csrf_token() !!}" />
then change in function
$(".toggle-btn").change(function() {
var id = $(this).attr('name'); // $(this) refers to button that was clicked
$.ajax({
url: '/adminpanel/dviulaan/stt',
method: "post",
data: {'id' : id, '_token': $('meta[name="csrf-token"]').attr('content')} ,
dataType: "json",
});
});
Related
I have created a form for making donation when user makes donation he will be viewing an error or if successful will be able to see a form on second page like second form will be loaded up. Now the problem is that when I tested data is properly updating in the database as well as on back end everything is working fine. The problem is that ajax is not getting return data I have placed a loader on success the loader will be hidden and it is not working it's continuously loading but not getting return data can anyone help me out to fix this error for me please here is my code
This is my javascript
$(document).ready(function() {
$('.donate').on('submit', function(e) {
$('.load').fadeIn(500);
var formData = new FormData(this);
console.log(formData);
$.ajax({
url : "http://mydomainname.com/directory/user/makedonation",
type : "POST",
data : formData,
contentType : false,
cache : false,
processData : false,
success : function(data) {
$('.load').fadeOut(500);
console.log(data.status);
$('.donation_form').html(data);
}
});
});
});
This is my controller User.php where the data is being processed
public function makedonation() {
$comments = $this->input->post('comments');
$user_data = $this->get_data->user_info($this->session->userdata('uid'));
$class = $this->db->get_where('classes', array('id' => $user_data->row()->membership));
$amount = $class->row()->ammount_pay;
$data = array(
'user_id' => $user_data->row()->uid,
'amount' => $class->row()->ammount_pay,
'rcv_amount' => $class->row()->ammount_receive,
'class_id' => $class->row()->id,
'comments' => $comments
);
$rt_data = $this->data_insert->donate_user($data);
$rcv_data = $this->get_data->user_info($rt_data['receiver_id']);
$name = $rcv_data->row()->first_name . " " . $rcv_data->row()->last_name;
$view_data = array(
'user_id' => $user_data->row()->uid,
'receiver_id' => $rt_data['receiver_id'],
'transaction_id' => $rt_data['transaction_id'],
'comments' => $comments,
'name' => $name,
'amount' => $class->row()->ammount_pay,
'command' => 'Confirm Donation'
);
$this->load->view('user/includes/get_data', $view_data);
}
This is the modal where the data is being inserted into the database
public function donate_user($data) {
$donation_data = array(
'user_id' => $data['user_id'],
'amount' => $data['amount'],
'receive_ammount' => $data['rcv_amount'],
'date_deposit' => date('m-d-Y'),
'time_deposit' => date('h:i A'),
'class' => $data['class_id'],
'status' => 'Submitted'
);
$insert_donation = $this->db->insert('donation', $donation_data);
$transaction_id = $this->db->insert_id();
$rt_data = array(
'message' => 'Success',
'transaction_id' => $transaction_id,
'receiver_id' => $receiver->row()->user_id
);
return $rt_data;
}
Now here is my confusion if the data is inserting correctly into the data base and also when I run this file separately in the browser I am referring to my controller the second page is loading up properly no errors found the why ajax is not returning data
Here is your answer. You have to set your ajax return data to json and do following in your controller.
$(document).ready(function() {
$('.donate').on('submit', function(e) {
$('.load').fadeIn(500);
var formData = new FormData(this);
console.log(formData);
$.ajax({
url : "http://mydomainname.com/directory/user/makedonation",
type : "POST",
data : formData,
contentType : false,
cache : false,
processData : false,
dataType: 'json',
success : function(data) {
$('.load').fadeOut(500);
console.log(data.status);
$('.donation_form').html(data.response);
}
});
});
});
Controller Code
public function makedonation() {
$comments = $this->input->post('comments');
$user_data = $this->get_data->user_info($this->session->userdata('uid'));
$class = $this->db->get_where('classes', array('id' => $user_data->row()->membership));
$amount = $class->row()->ammount_pay;
$data = array(
'user_id' => $user_data->row()->uid,
'amount' => $class->row()->ammount_pay,
'rcv_amount' => $class->row()->ammount_receive,
'class_id' => $class->row()->id,
'comments' => $comments
);
$rt_data = $this->data_insert->donate_user($data);
$rcv_data = $this->get_data->user_info($rt_data['receiver_id']);
$name = $rcv_data->row()->first_name . " " . $rcv_data->row()->last_name;
$view_data = array(
'user_id' => $user_data->row()->uid,
'receiver_id' => $rt_data['receiver_id'],
'transaction_id' => $rt_data['transaction_id'],
'comments' => $comments,
'name' => $name,
'amount' => $class->row()->ammount_pay,
'command' => 'Confirm Donation'
);
$result = $this->load->view('user/includes/get_data', $view_data,true);
$this->output->set_content_type('application/json')->set_output(json_encode(array('response' => $result,'status'=>'success')));
}
You can read https://www.codeigniter.com/userguide3/libraries/output.html for output and return view in variable to set as last parameter as true based on codeigniter feature of views.
I have two dependent select box in my form for selecting country and state.
i have a multi select checkbox dropdown for selecting country,
and i want to fetch state of selected country
but i cannot understand how to pass multiple checked id in my function from javascript.
below is my html select list box code
<?php
echo $this->Form->input('UserLogDetail.service_area_category_id', array(
'id' => 'shipping_type',
'required' => false,
'multiple' =>'multiple',
'type' => 'select',
'class' => 'form-control drop-arrow',
'label' => false,
'options' => $serviceCategory,
'empty' => '--Select--'
));
?>
<?php
echo $this->Form->input('UserLogDetail.skills', array(
'class' => 'form-control',
'required' => false,
'id' => 'skill',
'label' => false,
'options' => '$states',
'empty' => '--Select--'
));
?>
javascript function
<script type="text/javascript">
$(document).ready(function() {
$("#shipping_type").on('change', function() {
var id = $(this).val();
if (id) {
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Profiles", "action" => "loadSkills"),true); ?>',
data: dataString,
dataType: 'JSON',
cache: false,
success: function(html) {
$("#skill").html("");
$.each(html, function(key, value) {
$('<option>').val('').text('select');
$('<option>').val(key).text(value).appendTo($("#skill"));
});
$('#skill').selectpicker('refresh');
}
});
}
});
});
</script>
controlller function
public function loadSkills() {
$this->loadModel('Skill');
$states = array();
if (isset($this->request['data']['id'])) {
$states = $this->Skill->find('list', array('fields' => array('Skill.id','Skill.skill_name'),'conditions' => array(
'Skill.service_area_category_id IN' => explode(",",$this->request['data']['id']))));
}
echo json_encode($states);
exit();
}
try to call ajax below way
javascript :
$("#shipping_type").change(function() {
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Profiles", "action" => "loadSkills"),true); ?>',
//passing data to php
data: { id:$(this).val() },
dataType: 'JSON',
cache: false,
success: function(html) {
$("#skill").html("");
$.each(html, function(key, value) {
$('<option>').val('').text('select');
$('<option>').val(key).text(value).appendTo($("#skill"));
});
$('#skill').selectpicker('refresh');
}
});
});
php
public function loadSkills() {
$this->loadModel('Skill');
$states = array();
//Getting post id
if (isset($this->request['id'])) {
$states = $this->Skill->find('list', array('fields' => array('Skill.id','Skill.skill_name'),'conditions' => array(
'Skill.service_area_category_id IN' => explode(",",$this->request['data']['id']))));
}
echo json_encode($states);
exit();
}
public function loadSkills() {
$this->getServiceArea();
$this->loadModel('Skill');
$skills = array();
if (isset($this->request['data']['id'])) {
$ids = explode(",",$this->request['data']['id']);
if(count($ids)>1){
$skills = $this->Skill->find('list', array('fields' => array('Skill.id','Skill.skill_name'),'conditions' => array(
'Skill.service_area_category_id IN' => $ids)));
} else {
$skills = $this->Skill->find('list', array('fields' => array('Skill.id','Skill.skill_name'),'conditions' => array(
'Skill.service_area_category_id' => $ids)));
}
}
echo json_encode($skills);
exit();
}
I am about to submit my form Using Ajax,i have successfully submit my form using POST but don't know how to use Ajax with Symfony
builform
$builder->add('name', 'text', array('constraints' => array(new NotBlank()), 'attr' => array('placeholder' => 'Name')))
->add('gender', 'choice', array('empty_value' => 'Select Gender', 'constraints' => array(new NotBlank()), 'choices' => \AppBundle\Entity\Records::$gender_list, "required" => true))
->add('dateOfBirth', 'birthday', array('label' => 'Date Of Birth','required'=>true))
->add('image_path', 'file', array('label' => ' ','required'=>false, 'data_class' => null, 'constraints'=>array(new Assert\File( array('mimeTypes'=>$mime_types, 'maxSize'=>'2048k' )))))
->add('country_of_birth', 'entity', array('empty_value' => 'Country of Birth',
'class' => 'AppBundle\Entity\Location',
'property' => 'country',
'label' => 'Country of Birth'
))
->add('religion', 'entity', array('empty_value' => 'Select Religion',
'class' => 'AppBundle\Entity\Religion',
'property' => 'name',
'label' => 'Religion'
));
Action
$success = false;
$record_rep = new \AppBundle\Entity\Records();
$form = $this->createForm(new \AppBundle\Form\AddPersonType(), $record_rep);
if ($this->getRequest()->getMethod() == 'POST') {
$form->submit($request);
if ($form->isValid()) {
$data = $form->getData();
$file = $data->getImagePath();
$image = $file->getClientOriginalName();
$new_image_name = $this->hanldeUpload($image, $file);
$this->savetoDB($data, $record_rep, $new_image_name);
$success = true;
}
}
return $this->render('AppBundle:Homepage:add_person_form.html.twig', array('form' => $form->createView(), 'success'=>$success ));
}
With jQuery, use serialize() the form and post it to your route.
$('#form').submit(function(e) {
e.preventDefault();
var url = "{{ path('YOUR_PATH') }}";
var formSerialize = $(this).serialize();
$.post(url, formSerialize, function(response) {
//your callback here
alert(response);
}, 'JSON');
});
In your action
if ($form->isSubmitted() && $form->isValid()) {
....
// or return new JsonResponse($anyData);
return new Response(json_encode(['status'=>'success']));
}
it must be ok like this. but you can add some parameters like the format, methods etc... in your routing.
For the Ajax:
$("#person").submit(function(e){
var formURL = "{{ path('form') }}";
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //Prevent Default action.
e.unbind();
});
$("#person").submit();
And for Action
if ($request->isXmlHttpRequest()) {
....
return new Response(json_encode(array('status'=>'success')));
}
Hi i have a simple jquery codes that request a put to cakephp
$("#putBtn").click(function(){
var id = $("#searchTxt").val();
$.ajax({
url: 'http://localhost/cakephp/recipes/'+id,
type: 'PUT',
async: false,
cache: false,
dataType:'json',
data:{
name:"777",
number:"777"
},
success: function(data) {
console.log(data);
},
error: function(textStatus, errorThrown) {
console.log("error");
}
});
});
problem is that when the run this command and send it to cakephp
it make an error of this
/cakephp/recipes/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. jquery-2.1.0.js:8556
error
in my cakephp i just follow this tutorial
//book.cakephp.org/2.0/en/development/rest.html
public function edit($id) {
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type");
$this->viewClass = 'json';
if ($this->Recipe->save($this->data)) {
$message = 'Saved';
} else {
$message = 'Error';
}
$this->set(array(
'message' => $message,
'_serialize' => array('message')
));
}
i also added the router.php with
Router::resourceMap(array(
array('action' => 'index', 'method' => 'GET', 'id' => false),
array('action' => 'view', 'method' => 'GET', 'id' => true),
array('action' => 'add', 'method' => 'POST', 'id' => false),
array('action' => 'edit', 'method' => 'PUT', 'id' => true),
array('action' => 'delete', 'method' => 'DELETE', 'id' => true),
array('action' => 'update', 'method' => 'POST', 'id' => true)
));
Router::mapResources('recipes');
Router::parseExtensions();
i dont know why cakephp is not accepting my request of PUT or DELETE command.
any suggestions or advice ? .or what im i doing wrong . thx in advance .
I ran into a similar issue with CakePHP version 2.5.4 for parsing a PUT call.
Not elegant, but this did work.
Front End Code:
$("#myButton").click(function() {
$.ajax({
type : 'PUT',
url : '/projects/foo',
dataType : 'json',
data : JSON.stringify({
'projectId' : 789,
'desc' : "cheese cake",
}),
success: function(return_data) {
alert("success");
console.log(JSON.stringify(return_data));
},
error: function(return_data) {
alert("error");
console.log(JSON.stringify(return_data));
});
});
Back-end Code (app/Controller/ProjectsController.php)
public function foo() {
$this->autoRender = false;
if($this->request->is('PUT')) {
$in = $this->request->data;
reset($in);
$in = json_decode(key($in), true);
$project_id = $in['projectId'];
$desc = $in['desc'];
}
$response = array(
'project_id' => $project_id,
'desc' => $desc,
);
echo json_encode($response);
exit;
}
Result:
Check your console when you test this code. It will just send back what you sent over in the first place, but will give you the assurance that your back-end code in CakePHP can now parse these JSON PUT requests.
drupal 6: here is the code:
http://pastebin.com/GGVFfAGS
//getcity.js:
$(document).ready(function() {
$("#edit-field-house-geo-area-value").bind('change', function(){
selected_loc=$("#edit-field-house-geo-area-value option:selected").val();
var myURL="http://whatever.com/getajax/citys/"+selected_loc+"/";
$.ajax({
type: "GET",
url: myURL,
dataType: "json",
success: function(data){
console.log(data);
}
});
});
});
drupal module:
function sf_menu()
{
cache_clear_all();
$items = array ();
$items ['getajax/citys/%'] = array ('title' => 'This is my custom page', 'page callback' => 'sf_get_cities_ajax', 'access arguments' => array ('access content' ), 'access callback' => 'user_access', // TRUE will give access to everyone
'page arguments' => array (2 ), 'type' => MENU_CALLBACK );
return $items;
}
function sf_get_cities_ajax($cityid)
{
$termsarray = array ();
$terms = array ();
$cityid_safe = (int)$cityid;
$cityid_safe = check_plain($cityid_safe);
if (is_number($cityid_safe)) {
$terms = taxonomy_get_children($cityid_safe, 143, 'tid');
if (count($terms)) {
foreach ($termsarray as $k => $v) {
$termsarray [check_plain($k)] = t($v [tid]);
}
$f= array('status' => 1, 'data' => $termsarray,'moo'=>'sadasdsd');
print drupal_json($f);
exit();
}
}
}
its not return me somthing even i print the 'moo' data
its my function its working fine i get array at the final but its dont pass it
That looks like it should work except one thing... PHP doesn't have a function 'is_number()' so unless you wrote your own you need to change your IF statement to use PHP built in 'is_numeric':
if (is_numeric($cityid_safe)) {
Its not a JS issue at all.