JSON_ENCODE LARAVEL No Work - laravel

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!']);

Related

Internal server error 500 when sending ajax post request in laravel 9

I am using laravel 9. I am trying to make a ajax crud operation using alax. It respond well in get request. but when I sending the post request it shows:
http://127.0.0.1:8000/add/teacher 500 (Internal Server Error) in the console. I used meta in the head and ajax csrf header according to documentation. Still showing error. here my ajax code example bellow:
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$(".add_teacher").on('click', function(event) {
event.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var position = $("#position").val();
var phone = $("#phone").val();
var password = $("#password").val();
$.ajax({
method: "post",
url: "{{route('store')}}",
data: {
name: name,
email: email,
position: position,
phone: phone,
password: password
},
success: function(res) {
if (res.status == 'success') {
$("#exampleModal").modal('hide');
$("#modalform")[0].reset();
$(".table").load(location.href + ' .table');
}
},
error: function(err) {
let error = err.responseJSON;
$.each(error.errors, function(index, value) {
$(".errorMessage").append('<span class="text-
danger">' + value +'</span><br>');
});
}
});
});
});
</script>
Here is my route:
Route::post('/add/teacher', [TeacherController::class,'store'])->name('store');
and my controller code is:
public function store(Request $request)
{
$request->validate(
[
"name" => "required",
"email" => "requied|unique:teachers",
"position" => "requied",
"phone" => "requied|unique:tachers",
"password" => "requied",
],
[
"name.required" => "Name is required",
"email.required" => "Email is required",
"email.unique" => "Email already exists",
"position.required" => "Postion is required",
"phone.required" => "Phone is required",
"phone.unique" => "Phone already exixts",
"password.required" => "password is required",
]
);
$teacher = new Teacher();
$teacher->name = $request->name;
$teacher->email = $request->email;
$teacher->position = $request->position;
$teacher->phone = $request->phone;
$teacher->password = $request->password;
$teacher->save();
return response()->json([
'status' => 'success',
]);
}
Now I need an exact solution to go farther. Thank you.

how can I customize json responses of laravel api and show them in vuex

Trying different solutions, I am fooling around with
response()->json([ ])
To create responses that I can read in my vue / vuex application
The Laravel api function that stores a new Speler ( dutch for player ;)):
I have trouble sending the created, or found Speler-object, through the response to the vuex-store.
Tried to set the status to 202 when succesfully logged, yet the actual status sent is 200..
It is clear that I do not understand it well enough. Can anyone help and explain?
public function store(Request $request)
{
if (Game::where('id',$request['game_id'])->exists() ){
if (!Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->exists()){
$newSpeler = Speler::create(
[
'name' => $request['name'],
'pass_code' => $request['pass_code'],
'game_id' => $request['game_id']
])->first());
return $newSpeler;
}
elseif ( Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code'])->exists()){
$speler = Speler::where('name',$request['name'])->where('game_id',$request['game_id'])->where('pass_code', $request['pass_code']);
return response()->json(['speler'=> $speler, 202]);
}
return response()->json(['status' => 'This name is already used, pass-code is not correct', 409]);
}
return response()->json([ 'status' => 'The game-pin does not exist', 403 ]);
}
This is called form the vuex actions:
export const addSpeler = ({commit}, formData) => {
return new Promise((resolve, reject) => {
fetch(`api/speler`, {
method: 'post',
body:formData,
})
.then(res => {
if (res.status === 202){
resolve('De speler is succesfully logged on');
commit('SET_CURRENT_SPELER', res.data.speler);
}
else if (res.status === 201){
commit('SET_CURRENT_SPELER', res.data);
resolve('De speler is succesfully added')
}
else {
reject('De speler is not logged in. Name exists and does not match passcode');
}
})
.catch(err => {
reject(err.message)
});
})
}
and this is called from a vue method:
methods: {
addSpeler(){
this.errorMessage ='';
this.spelerAdded =false;
const formData = new FormData();
formData.append('name', this.name);
formData.append('pass_code',this.pass_code);
formData.append('game_id', this.currentGame.id);
this.$store.dispatch('addSpeler', formData )
.then(res => {
this.spelerAdded = true;
console.log(res.status);
})
.catch(err => {
this.errorMessage = err;
this.spelerAdded = false;
});
},
mutations.js:
export const SET_CURRENT_SPELER = (state, speler) => {
state.currentSpeler = speler;
}
state.js:
export default{
currentGame:{},
currentSpeler:{}
}
The comment by porloscerros answered the question perfectly :
the status goes as the second argument of the json method return response()->json(['speler'=> $speler], 202); (and not inside the array as you are doing). If you don't pass a second argument, the argument value is assigned to 200 by default json(mixed $data = [], int $status = 200, array $headers = [], int $options = 0)

Laravel - How to call a controller function via AJAX (jQuery)

I have a number of working controller functions, however, for usability I want to switch some of them over to be called via AJAX.
Here is my jQuery code:
$.ajax({
method: 'GET',
url: $(this).data('url'),
data: {},
success: function( response ){
console.log( response );
},
error: function( e ) {
console.log(e);
}
});
And here is my controller function:
public function add( $user_id, $project_id )
{
$project = Project::findOrFail( $project_id );
if( empty( $project ) ) {
return view( 'home' )->with('message', 'Sorry, user not found');
}
if ( $project->user_id != $user_id ) {
$scrapbook = Scrapbook::firstOrNew(['user_id' => $user_id]);
$scrapbook->save();
$scrapbook->projects()->attach($project_id);
return true;
} else {
return false;
}
}
As it stands, the controller function actually does what it is supposed to (adds a project to a scrapbook). But what it returns is causing the AJAX request to class as an error so I am unable to handle this correctly. I assume I am supposed to return some kind of response object but I don't know what this is or what it needs to include.
You can simply return an array containing whether it is success or it is failed.
$output_data = ['response' => true, 'message' => 'request is successful.' ];
$output_data = ['response' => false, 'message' => 'error message for user.' ];
return $output_data;
This will return control in success block of ajax.
You can check there is the response is true or false and execute the code accordingly.
You may return a json response on success:
public function add( $user_id, $project_id )
{
// Other code ...
$isSuccess = false;
if ($project->user_id != $user_id) {
$scrapbook = Scrapbook::firstOrNew(['user_id' => $user_id]);
if ($isSuccess = $scrapbook->save()) {
// only attach it if successfully saved
$scrapbook->projects()->attach($project_id);
}
}
return response()->json([
'success' => $isSuccess
]);
}
So in your ajax response you can check:
success: function( response ){
console.log( response.success ); // true or false
}
You need to return a json response using json() fucntion
return response()->json(true);
or if want to send additional data back
return response()->json([
'message' => 'successfull',
'items' =>$insertedItems
],200);
or on fail
return response()->json(['error'=>'error text'],$statusCode)
In Routes:
Route::get('/url', 'controller_name#controller_function');
Ajax:
$.ajax({
method: 'GET',
url: 'url',
data: {},
success: function( response ){
console.log( response );
},
error: function( e ) {
console.log(e);
}
});
In response , send json:
return response()->json(['message' => 'successfull'],200);

Ajax form content and insert into DB with Laravel ..

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')

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