OctoberCMS callback for successful DB action after AJAX request - php

Im sending data via AJAX from my Chrome-extension to my OctoberCMS controller.
How can I recognize in my Chrome-extension that the database operation was successful?
So the goal is that I can use the done() in my AJAX call after a successful database update.
Do I have to return something from my controller?
Ajax from extension
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/saveData",
type: "POST",
dataType: "JSON",
data: { "data": data}
}).done(function((){//does nothing});
OctoberCMS Controller
function saveData(Request $request)
{
$data = post('data');
//do some actions with the data;
DB::table('users')->where(['id' => Auth::getUser()->id])->update(['data' => $data]);
}

You can check for response
From server side
function saveData(Request $request)
{
$data = post('data');
//do some actions with the data;
DB::table('users')->where(['id' => Auth::getUser()->id])->update(['data' => $data]);
// if all good return success
return ['success' => true];
// if something is not correct
// return ['success' => false];
}
Client side
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/saveData",
type: "POST",
dataType: "JSON",
data: { "data": data}
}).done(function((data){
if(data.success == true) {
// yes all good data is updated
}
else {
// data is not updated some error handling
}
}).fail(function() {
// data is not updated some error handling
// failed in case server is not able to answer or error
});
if any doubt please comment.

Related

Laravel 5.6 ajax post without form

I want to use ajax with selectize to load bdd results onchange.
I need to use post because I must send data to my url.
My function looks like this :
select_etages.load(function(callback) {
xhr && xhr.abort();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
data : { bat : value },
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
In my web.php I've got this :
Route::post('/lots/add/etages', ['as' => 'lots.add_post.select', 'uses' => 'Copro\LotController#select2']);
And my controller :
public function select(Request $request)
{
return "test";
}
But when I tried to use it, I've got an "419 unknown status". I can see that it's a post ajax and my data but I've got no error message :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
If I change to get it's working but not post.
Anyone know why I can't use post ??
Thank for your help.
Maybe you just rewrite the "select2" name end of the route to "select"?
I think you need to remove $.ajaxSetup function in callback function. Code might look like this.
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
select_etages.load(function(callback) {
xhr && xhr.abort();
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
});

Pass data from ajax to laravel 5.1 Controller in order to save to mysql?

I need to pass data from jquery (version 1.9.1) to my Controller (Laravel 5.1) and then save it to mysql.
How to do that and pass the variable slot? It didn't work so far. For any further details, please asked me.
jquery:
$(".tic").click(function(){
var slot = $(this).attr('id');
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { _token: {{ csrf_token() }}, moves: slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
Controller:
public function addhistory(Request $request)
{
$history = new History();
$history->game_id = Game::orderBy('id', 'desc')->first()->id;
$history->moves = $request->moves;
$history->save();
return redirect()->back();
}
Routes:
Route::post('/addhistory', 'GameController#addhistory');
Errors in console:
(index):198 Uncaught ReferenceError: HAmcYRScL9puItnUGbd2kHx.... is not defined
at HTMLAnchorElement.<anonymous> ((index):198)
at HTMLAnchorElement.dispatch (191.js:3)
at HTMLAnchorElement.v.handle (191.js:3)
191.js file is the jquery version of 1.9.1
You can use this code, it may works
$(".tick").click(function (event) {
event.preventDefault();
$('.loading').show();
var form = $(this);
var data = new FormData($(this)[0]);
var url = form.attr("action");
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert("Data has been saved successfully.");
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
Try this code-
$(".tic").click(function(){
var slot = $(this).attr('id');
var token= $("input[name='_token']").val();
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { '_token': token, 'moves': slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
And in your controller you don't need return redirect because the request is asynchronous. So I am returning true. Make sure you include History model at the top of your controller
public function addhistory(Request $request)
{
$game_id=Game::orderBy('id', 'desc')->first()->id;
History::create([
'game_id'=>$game_id,
'moves'=>$request->moves
]);
return true;
}

Assign Ajax response to php variable

How do I assign my ajax response to a php variable, if it is even possible?
In my Laravel controller I have this method for that purpose:
public function editProductPost(Request $request)
{
return response()->json([
'sliderValue' => $request->get('value')
]);
}
And this is my Ajax:
/**
* Ajax Post
*/
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'post',
contentType: "application/json",
url: "{{ Route('editProductPost', $product->id) }}",
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
data: JSON.stringify({
value: getSliderVal,
productId : getPrId
}),
datatype: 'json',
success: function(response) {
// get response
console.log(response.sliderValue)
}
If I understand you correctly, you want to do something like this:
public function editProductPost(Request $request)
{
// Create your JSON response
$response = response()->json([
'sliderValue' => $request->get('value')
]);
// Assign the content of the response to a variable
$responseContent = $response->content();
// Return your response
return $response;
}

Jquery function cant access json object

I'm using bootstrap validator to validate my form data. If form is validated I'm posting those data to php. In php I'm returning json string. Even though my post is success and get correct response, I can't access json object.
$('#dealForm')
.bootstrapValidator({
message: 'This value is not valid',
fields: {
deal_description: {
message: 'The deal discription is not valid',
validators: {
notEmpty: {
message: 'The deal discription is required and can\'t be empty'
}
}
}
}
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var formObj = $(e.target);
var formURL = formObj.attr("action");
$.ajax({
url: formURL,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
dataType:JSON
}).done(function(data) {
console.log(data);
});
});
debugger output
php
$temp= $_POST['deal_description'];
if(!empty($_FILES['userfile']['name'])){$temp2='has';} else $temp2='no has';
echo json_encode(array(
'message' => $temp,
'test' => $temp2
));
Either set the correct header in php:
header('Content-Type: application/json');
echo json_encode(array(
'message' => $temp,
'test' => $temp2
));
Or use JSON.parse in js:
}).done(function(data) {
data = JSON.parse(data);
console.log(data);
alert(data.mesage);
});
EDIT just noticed you also have a spelling mistake in your js. data.mesage should have two s data.message
Try
.done(function(data) {
var res=$.parseJSON(data);
alert(res.message);
});
Your AJAX request is wrong I think. It should be
function getData(){
$.ajax({
url: formURL,
type: "POST",
data: new FormData(this),
contentType: 'application/json; charset=utf-8',
cache: false,
dataType: 'json'
}).success(function (data) {
console.log(data);
workWithData(data);
}).done(function(e){
console.log("I'm done");
});
}
function workWithData(data){
if (typeof data != 'undefined') {
var jsonData = $.parseJSON(data);
// do stuff with data
}
}
The reason for having it in a second function is that it is a callback. We don't know how long the AJAX request might take, so we must not interrupt execution of the page whilst waiting for a response. By using a callback, when the data eventually arrives it will be processed.
I'd like to recommend you go through this to learn more about AJAX requests http://api.jquery.com/jquery.ajax/

How to do a POST json request with jQuery?

How can I recreate a request with jquery which would work exactly as this PHP request?
$client = new Zend_Http_Client($uri);
$response = $client->setMethod(Zend_Http_Client::POST)
->setRawData(trim($json), 'application/json')
->request();
Thanks.
$.ajax({
cache:false,
type: 'POST',
url: "yoururl",
data:yourJsonData,
contentType: "application/json",
success: function(data) {
//do what you what with return data
}
});
Like this
$.postJSON("/application/json".
{
ID:5 // all parameters here for the method
},
function(data)
{
//data is what comes back from your function
});

Categories