Ajax form content and insert into DB with Laravel .. - ajax

i created a form using AJAX because i have several alternatives concerning the fields.
I have correct information in my javascript and make tests... my first select use the following function and generates form
function setParentSector() {
$("#listSectors").html("");
$("#createSector").html("");
if($('#langname option:selected').val() !=0) {
var obj = { 'id': $('#langname option:selected').val() };
if (obj['id'] != 1) {
ajaxSectors(obj);
}
else
{
// another form generated here ...
$('#createSector').append("something else");
}
}
};
I use a "classical" ajax ..
function ajaxSectors(objSetParent) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/ajax/sectorParent',
type: 'post',
dataType: 'json',
async: true,
success: function (result) {
$('#listSectors').append("<label for='langname'>label </label> " +
"<select class='form-control m-input m-input--air' id='sectors' onclick='setLangTranslation()'>" +
"<option value='0' selected>Select value</option></select>" +
"<span class='m-form__help' id='existsAlready'>");
var count = result.length;
for (var i = 0; i < count; i++) {
if (result[i].deleted_at === null) {
$('#sectors').append("<option value='" + result[i].sector_id + "'>" + result[i].sectname + "</option>");
}
else {
console.log("peanuts");
}
}
},
data:objSetParent,
error: function (result) {
},
complete: function (result) {
//console.log("complete");
}
});
}
This part of code works fine and i display what i want...
When I want to save into DB the form, I plan to use the store method and I create the $request->validate()
In the store method I have :
$request->validate([
'admin' => 'required',
'langname' => 'required',
'sectname' => 'required',
'sectshortname' => 'nullable',
]);
return view ('test')
The test view contains just in order to see what i post ..
If i keep the validate part, the page is just refreshed and not validated...
Without the request validate I display the view and i just see the value of the input with the token.
Thanks for your answers. Let's hope my question is "clear" enough

Use this code I hope this code works for you please use this Use Validator;
$rules = [
'admin' => 'required',
'langname' => 'required',
'sectname' => 'required',
'sectshortname' => 'nullable',
];
$data = $request->all();//or you can get it by one by one
$validator = Validator::make($data , $rules);
if ($validator->fails()) {
$error=[];
$errors = $validator->messages();
foreach($errors->all() as $error_msg){
$error[]= $error_msg;
}
return response()->json(compact('error'),401);
}
return view ('test')

Related

How to use Select2 Ajax on CakePHP?

I have been trying to make an autocomplete dropdown list but I really have no idea on how to do it. I have found an example on youtube but sadly it is not for cakephp. Here is the link if you are curious: https://www.youtube.com/watch?v=S6yCBggCKl0&t=305s. Please help me.
The CakePHP version of the project I'm working with is 3.8.
Here are the code the I come up with so far:
view:
$('.js-data-example-ajax').select2({
ajax: {
url: "<?php echo Router::url(["controller"=>"VScripts","action"=>"searchTask"]); ?>",
dataType: "json",
delay: 250,
data: function (params) {
return {
q: params.term,
};
},
processResults: function (data) {
return {
results: data,
};
},
cache: true
},
placeholder: 'Type atleast 1 digit to search',
minimumInputLength: 1
});
Controller:
public function searchTask()
{
$this->autoRender = false;
$term = $this->request->query['q'];
$select = array(
'task_id' => 'id',
);
$tasksTable = TableRegistry::getTableLocator()->get('Tasks');
$tasks = $tasksTable
->find()
->select($select)
->from('tasks')
->where(['task_id' => '%' . $term . '%'])
->limit(10)
->order(['task_id' => 'ASC'])
->execute()
->fetchAll('assoc');
$result = array();
foreach ($tasks as $task) {
$id = $task['task_id'];
$result[] = array('id' => $id, 'text' => $id);
}
echo json_encode($result);
}

Laravel controller validation of request with nested parameters

I am trying to validate in my controller a request of nested parameters but I can't get it working. I did find a few resources online and tried different things with no success.
This is the script that sends the data to the controller:
var fieldsValuePair = {
type: this.history.type
};
axios.get('/app/admin/cms/clients/processActivity', {
params: {
fieldsValuePair: fieldsValuePair,
hid: this.history.hid
}
})
.then((response) => {})
.catch(error => {
this.errors = [];
this.errors = error.response.data;
console.log(this.errors);
});
This is my validation in my controller:
$this->validate($request, ['type' => 'required'] , ['activity-type.required']);
I want to say that if i add: type: this.history.type in my axios request just after hid: this.history.hid then the validation works correctly.
What I want to achieve is to have the type: this.history.type in the fieldsValuePair object and have this validate correctly in the controller.
I did find a solution but not sure if this would be the best one. At least it's working for me.
$rulesArray = [];
$fieldsValuePairArray = json_decode($request['fieldsValuePair'], true);
foreach ($fieldsValuePairArray as $key => $value) {
if($value == '')
$rulesArray[$key] = 'required';
}
$this->validate($request, $rulesArray , ['activity-type.required']);

Why jquery ajax post request get error in yii2?

js:
$.ajax({
url: '/site/updateuserdata',
method: 'POST',
//async: true,
//cache:false,
data: {
'type': 'sort'
//val: val
//csrfParam: csrfToken
},
dataType: 'text',
error: function(jqXHR, textStatus, errorThrown) {
alert('error by ajax');
},
success: function(data, status, jqXHR) {
alert('success by ajax');
}
});
Controller:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['updateuserdata'],
'allow' => true,
// 'roles' => ['*'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'updateuserdata' => ['post'],
],
],
];
}
public function actionUpdateuserdata()
{
/*if (Yii::$app->request->isAjax) {
$message = 'Ваше сообщение успешно отправлено';
Yii::$app->response->format = Response::FORMAT_JSON;
$response = [
'success' => true,
'message' => $message
];
return $response;
}*/
$f = fopen('testajax.txt','a+');
fwrite($f, 'ajax: '.(isset($_POST['type'])?$_POST['type']:'error'));
fclose($f);
if(isset($_POST['type']))
return $_POST['type'];
else return 'error1';
// return Yii::$app->getResponse()->redirect(Yii::$app->request->referrer, 302, FALSE);
}
yii.js:
function initRedirectHandler() {
// handle AJAX redirection
$(document).ajaxComplete(function (event, xhr) {
var url = xhr && xhr.getResponseHeader('X-Redirect');
alert(url); //my code
if (url) {
window.location.assign(url);
}
});
}
I see first alert(ajax error) "error by ajax" and then alert(yii.js) "..../site/updateuserdata...", why ajax error? File testajax.txt not create.
I tried comment 'updateuserdata' => ['post'], and get error too.
Updated.
Also, tried:
public function beforeAction($action)
{
if ($action->id == 'updateuserdata') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
and uncomment csrf parameters in ajax.
And 'error' return status 302(jqXHR.status).
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
I find problem, it's stupid problem:
url: '/mag/updateuserdata/',
i have in 'urlManager':
'suffix' => '/',
i think this added for all, but not.....
Cause you commented
//csrfParam: csrfToken
from your ajax js file you have 400 http status code in your ajax.
So you can solve it in two way:
one: disable csrf validation by adding
$this->enableCsrfValidation = false;
in your actionUpdateuserdata method.
two: add csrf token and csrf param to your ajax.
print this code in your js, where you commented it.
Yii::$app->request->csrfParam . ':' . Yii::$app->request->csrfToken
then your request sent successfully and if you have other error you must check your code.

JSON_ENCODE LARAVEL No Work

Do not return my json_encode page after I access the button. I do not know why.
SkinID data is saved correctly. Only the return does not work.
public function buy()
{
$player = \Auth::user();
$player->SkinID = $_POST['id'];
$player->save();
return json_encode(['type' => 'success','title' => 'TEST BOX','text' => 'TEST MESSAGE LARAVEL!']);
}
app.min.js:
$("._buy").click(function() {
var o = $(this).attr("id");
$.ajax({
url: _PAGE_URL + "api/buy",
type: "POST",
data: {
id: o
}
})
})
You can use laravel built in function to return json:
return response()
->json(['type' => 'success','title' => 'TEST BOX','text' => 'TEST MESSAGE LARAVEL!']);

Need JSON to pass values to AJAX from specific content type fields

Im new to PHP.
I'd like to build a module and i need json to pass specific content type fields.
Im trying with this but i dont know how to deal with callback function.
here is my ajax in .js
$.ajax({
type: 'GET',
url: '/mappy/ajax/poi',
data: {
nid: nid
},
dataType: 'json',
success: function(data){
alert(data)
}
});
})
here is my php in .module
function mappy_menu() {
$items = array();
$items['/mappy/ajax/poi'] = array(
'title' => 'Mappy Pois',
'page callback' => 'mappy_get',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mpapy_get() {
$nid = $_GET('nid');
$title = field_get_items('node', $node, 'field_title');
$result = json_encode(
db_query("SELECT nid,title FROM {node}", $nid)
);
drupal_json_output($result);
print $result;
}
Many thanks for advice.
Once you get the JSON response you need to convert it to a javascript array. For that, you can do:
var javaArray = $.parseJSON(data);
Now you can retrieve the data, using code like javaArray['key1']['key2'], etc.
.js
$.ajax({
type: 'GET',
// Do not use slash at the beginning, use Drupal.settings.basePath instead
url: Drupal.settings.basePath + 'mappy/ajax/poi',
data: {
nid: nid
},
dataType: 'json',
success: function(data) {
alert(data)
}
});
.module
function mappy_menu() {
$items = array();
// Never use slash at the beginning in hook_menu
$items['mappy/ajax/poi'] = array(
'title' => 'Mappy Pois',
'page callback' => 'mappy_get',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mappy_get() {
$node = node_load($_GET('nid'));
// Or equivalent
/* $node = db_select('node', 'n')
->fields('n', array('nid', 'title'))
->condition('n.nid', $_GET('nid')))
->execute()
->fetchAll(); */
$values = array(
'nid' => $node->nid,
'title' => $node->title
);
#$result = json_encode(
# db_query("SELECT nid,title FROM {node}", $nid)
#);
// drupal_json_output already print the value
// print $result;
drupal_json_output($values);
drupal_exit();
}

Resources