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.
Related
I dont understand what i did wrong, can anyone give me a suggestion on what causes the above error below is my code. I can confirm that, i am hitting the route, succesfully because the code inside get it executed. I am also adding the 1 value at the end, to be passed it to json as per wp_send_json_success. At this point i dont know what to next, can anyone explaint to me, on what is going on?
route.php
function update_employee_photo($request){
global $wpdb;
$data_with_photo = array(
'photo' => $request['photo'],
'photo_privacy' => $request['photoPrivacy'],
'photo_description' => $request['photoDescription']
);
$data_null_photo = array(
'photo_privacy' => $request['photoPrivacy'],
'photo_description' => $request['photoDescription']
);
$data = ($request['photo'] != "null") ? $data_with_photo : $data_null_photo;
$where = array('wp_user_id' => get_current_user_id());
$result = $wpdb->update("aupair_registered_employee", $data, $where);
if($result){
wp_send_json_success($result, 200, 1);
} else {
wp_send_json_error($wpdb->last_query);
}
die();
}
add_action('rest_api_init', function(){
register_rest_route( 'activeAupair/v1', '/updateEmployeePhoto', [
'methods' => 'POST',
'callback' => 'update_employee_photo'
]);
});
file.js
$.ajax({
type: 'POST',
url: myAjax.restURL + 'activeAupair/v1/updateEmployeePhoto',
contentType: 'application/json',
datatype: 'json',
data: {
photo: photo,
photoPrivacy: getPhotoPrivacy(),
photoDescription: getPhotoDescription()
},
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', myAjax.nonce);
},
success: function(response){
console.log('TYPE OF ', typeof response);
console.log('RESPONSE ', response);
msg.empty();
msg.append($('<p id="required"></p>').text('Updated'));
uploadBtn.attr('value', 'Update');
uploadBtn.attr('disabled', false);
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function(data){
console.log('COMPLETE ', data);
}
});
As per the wordpress wp_send_json_success() function expect third parameter 1(default 0) to encode it into JSON format (see the reference). So you need to pass the status code as second parameter and 1 for the JSON object.
wp_send_json_success($result, 200, 1);
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 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",
});
});
The Problem is, the json file is not showing. Im using Xampp as local Server.
php file:
$array = array(
array(
"title" => "Erster Eintrag",
"description" => "Description",
"link" => "http://",
"pubDate" => "02.07.2015"
),
array(
"title" => "Zweiter Eintrag",
"description" => "Description",
"link" => "http://",
"pubDate" => "02.07.2015"
)
);
echo json_encode($json);
html file:
$ajax({
url:'localhost/uebung/staticfeed.php',
type:'POST',
data:'data',
dataType: 'json',
success: function(result){
$('#feeds').html(result[0]);
}
})
JavaScript use $.ajax and then full URL.
$.ajax({
url:'http://localhost/uebung/staticfeed.php',
type:'POST',
data:'data',
dataType: 'json',
success: function(result){
$('#feeds').html(result[0]);
});
You also need to encode your array in your php file.
echo json_encode($array);
Use json_encode in PHP
Returns a string containing the JSON representation of value.
Use $array to json_encode instead of $json.
echo json_encode($array);
/// ^^^^^^^^^
Change $ajax to $.ajax, this will remove the error in your code, everything else works fine
You are missing JSON headers in your PHP answer, Jquery may interpret your response as plain text or HTML...
Also, you are echoing $json and your array is $array.
Try this for PHP:
header('Content-type: application/json');
$array = [["title" => "Erster Eintrag","description" => "Description","link" => "http://","pubDate" => "02.07.2015"],["title" => "Zweiter Eintrag","description" => "Description","link" => "http://","pubDate" => "02.07.2015"]];
echo json_encode($array);
And this on your HTML:
$.ajax({type: "POST", url: "localhost/uebung/staticfeed.php", data:data, dataType: "json", timeout: 25000, success: function (result) {
$('#feeds').html('First array:' + result.[0].title + '<br />Seccond array:' + result.[1].title );
}});
You need to select the value INSIDE the array inside [result]...
Am using WordPress ajax to load the sub-categories dynamically.
Here's my code
Php code
function techento_getsubcat() {
$category_name = $_POST['catname'];
$cat_id = $_POST['catid'];
return wp_dropdown_categories( 'show_option_none=Choose a Sub Category&tab_index=10&taxonomy=category&hide_empty=0&child_of=' . $cat_id . '' );
}
add_action('wp_ajax_techento_getsubcat', 'techento_getsubcat');
add_action('wp_ajax_nopriv_techento_getsubcat', 'techento_getsubcat');
Jquery
jQuery(document).ready(function(){
$('#cat').change(function(e){
alert("changed");
$.ajax({
type: 'POST',
dataType: 'json',
url: pcAjax.ajaxurl ,
data: {
'action': 'techento_getsubcat', //calls wp_ajax_nopriv_ajaxlogin
'catname': $('#cat option:selected').text(),
'catid': $('#cat option:selected').val() },
success : function(response){
alert(response);
console.log(response);
$("#subcats").html(response);
}
});
e.preventDefault();
});
});
The problem with the above code is that php returns the raw html irrespective of the thing asked to return
even if set it to
return true;
it then returns the raw html of subcategories generated plus '0'
You're missing the $ shortcode in
jQuery(document).ready(function($){
The Ajax callback is better handled by wp_send_json_success(), so we don't have to worry with return or echo, exit or die. For that, set echo to false in the dropdown arguments:
function techento_getsubcat() {
$cat_id = intval( $_POST['catid'] );
$args = array(
'hide_empty' => 0,
'echo' => 0,
'child_of' => $cat_id,
'taxonomy' => 'category'
);
$data = wp_dropdown_categories( $args );
wp_send_json_success( $data );
}
On Ajax success, use response.data:
success : function(response){
console.log(response.data);
}