I'm new to Laravel. I am trying to create a common social network.
Now I want to be able to delete a user's post. At the moment when you try to submit the form it loads the ajax
but can not delete the data.
Here is my code:
$("#_global_modal").delegate('#modal_form_delete', 'submit',
function(event)
{
// To stop a form default behaviour
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
})
.done(function(response){
if(response.delete == "success"){
window.location.href = response.redirect_route
}else{
console.log(response);
}
})
.fail(function(){
console.log("error");
})
.always(function(){
console.log("complete");
});
});
Route:
Route::post('delete','crude#delete')->name('delete');
My controller part:
public function delete(Request $request)
{
if($request->ajax()){
$user = Auth::user();
$user->post()->delete(['post' => $request->post]);
return response()->json([
'delete' => 'success',
'redirect_route' => route('profile')
]);
}else{
return response()->json([
'delete' => 'ERROR',
'ERROR_MSG' => 'ERROR MSG'
]);
dd("Sorry you have to send your form information by using ajax
request");
}
}
So how can I solve this problem?
Your delete statement is wrong.
public function delete(Request $request)
{
if($request->ajax()) {
Post::where('id', $request->post)
->where('user_id', auth()->id())
->delete();
return response()->json([
'delete' => 'success',
'redirect_route' => route('profile')
]);
}
return response()->json([
'delete' => 'ERROR',
'ERROR_MSG' => 'ERROR MSG'
]);
}
Related
i built a registration form and validated it using javaScript. but i want after a user filled the form, it should post to the server. i am confused on where to place my httpRequest function. i don't know if its after validation or inside the validation function
This is my validation function
function formregister(e){
if (first_name.value=== "" || last_name.value=== "" || user_id.value==="" || id_type.value=== ""
|| id_no.value=== "" || address.value==="" || !terms.checked) {
var fPassResult = '1';
} else{
var fPassResult = '0';
}
if(fPassResult === "1") {
window.location = "register.html";
}else{
Swal.fire({
type: 'success',
title: 'Your Registration has been Submitted Successfully',
text: 'Click Ok to Login',
timer: 10000
}
).then(function(){
window.location="Login.html";
})
}
e.preventDefault();
};
**And this is my post request function**
function registerationApiCall(e){
var data = {
"user_id":"user_id.value",
"user_pin": "user_pin.value",
"first_name":"first_name.value",
"last_name":"last_name.value",
"address":"address.value",
};
fetch("jehvah/api",{
type : 'POST',
data : data,
dataType : 'JSON',
encode : true,
success: function (response, status, xhr) {
if (result==="OK") {
console.log("success");
}else{
console.log("bad");
}
},
error: function (xhr, status, error) {
console.log("something went wrong");
}
});
}
Please kindly check my post request function, i dont know if i am doing it the right way
Hi ✌ when fPassResult === "0" in this case inside else{} call registerationApiCall()
you tell the user it's a success after you get OK from the server which is Asynchronous call
& inside fetch response you call swal.fire
for this code to work your server when checks the database & every thing is ok returns a msg like this {"msg":"OK"}
CODE:
else{
registerationApiCall()
}
function registerationApiCall becomes
fetch('jehvah/api',
{ method: 'POST',headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
if (result.msg="OK") {
console.log("success");
Swal.fire({
type: 'success',
title: 'Your Registration has been Submitted Successfully',
text: 'Click Ok to Login',
timer: 10000
}).then(function(){window.location="Login.html";})
}else{ console.log("usres exsists / etc");}
})
.catch((error) => {
console.log("something went wrong");
});
}
Also in the request payload you sent a group of strings not the variables containing the form values
Here
var data = {
"user_id":"user_id.value",
"user_pin": "user_pin.value",
"first_name":"first_name.value",
"last_name":"last_name.value",
"address":"address.value",
};
Change that to
var data = {
"user_id":user_id.value,
"user_pin": user_pin.value,
"first_name":first_name.value,
"last_name":last_name.value,
"address":address.value
};
Looking at the fetch documentation (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), success and error does not exists.
The fetch function returns a Promise, so you can handle results as any Promise should do:
fetch("jehvah/api", {
method: 'POST',
body : JSON.stringify(myDataObject)
})
.then(blob => blob .json())
.then(result => console.log('Success!!))
.catch(e => console.log('Failure :('))
I have a function which uses jquery to call API and get a result. My API end is programmed to return the number "19" just for testing.
export function clientAdd(data) {
return (dispatch) => {
return $.ajax({
url: "http://api.example.com/client/add/",
headers: {'AUTHORIZATION': `${sessionStorage.jwt}`},
type: 'POST',
cache: false,
data: data,
dataType: 'json',
success: function (data) {
let redirectUrl = '/client/' + data
return redirectUrl';
},
error: function(xhr, status, err) {
if (xhr.status === 401) {
sessionStorage.removeItem('jwt');
return '/signin';
}
console.log('xhr',xhr.responseText);
console.log('status',status);
console.log('err',err);
return dispatch({type: GET_CLIENT_FAIL, err});
}
})
}
}
Then in my component, upon clicking on the submit button, it will call the onSave function as follows
onSave(event) {
//event.preventDefault();
this.props.actions.clientAdd(this.state.credentials).then((result) => {
return this.setState({redirect: true, newCustomerId: result})
}).catch((result) => {
return this.setState({redirect: false, errorMessage: result})
});
}
Where the result is supposed to be the redirectUrl or ErrorMessage.
However, I'm keep getting the number 19 which is returned by my API.
I read online if I want to use promise in my component, i have to add return infront of $.ajax, if not "then" will be undefined.
What you can do is, create your own promise and put the ajax call inside it
Then call resolve and pass data that you want when then is called
resolve(data_passed_to_then)
Like this :
return new Promise((resolve,reject) => {
$.ajax({
...
success: function (data) {
let redirectUrl = '/client/' + data
resolve(redirectUrl);
},
error: function(xhr, status, err) {
...
// return dispatch({type: GET_CLIENT_FAIL, err});
reject(err);
}
})
})
I'm trying to send data to the server API from a webpage but it keeps falling to
'No Connection!' as you will see in the code.
Note:The server, database and the API are working, because I also use it on a phone application that do the same as I'm trying to do here which is post an event to the database.
Here is the webpage code:
function onAddEvent(){
var title = document.getElementById("title").value;
var desc = document.getElementById("desc").value;
var date = document.getElementById("date").value;
var userid = localStorage.getItem("userid");
$.ajax({
url: API_URL,
type: 'POST',
data: {eventname: title, eventdate: date, eventdesc: desc, user_id: userid},
async: true, // set the property here
success: function(data) {
if(data.result == "success"){
alert("Add Event Successfully!");
}
else{
alert("Can't add event");
}
},
error: function(xhr, error) {
//It is falling here
alert('No Connection!');
}
});
}
And here is the PHP API that it will connect to:
function addevent()
{
$new_member_insert_data = array(
'eventname' => $this->input->post('eventname'),
'eventdate' => $this->input->post('eventdate'),
'eventdesc' => $this->input->post('eventdesc'),
'user_id' => $this->input->post('user_id')
);
$insert = $this->db->insert('event', $new_member_insert_data);
return $insert;
}
Remove the code from the function or try calling the function in the API.
//Call the function from your API
addevent();
function addevent()
{
$new_member_insert_data = array(
'eventname' => $this->input->post('eventname'),
'eventdate' => $this->input->post('eventdate'),
'eventdesc' => $this->input->post('eventdesc'),
'user_id' => $this->input->post('user_id')
);
$insert = $this->db->insert('event', $new_member_insert_data);
return $insert;
}
When the session is expired, User cant log back in without a page refresh because the _token in ajax headers is expired(AKA TokenMismatchException). I cant handle the exception by redirecting user to a log in page because the login is an overlay modal and the request is handled via ajax.
I thought i could catch the mismatch exception in Handler.php and return a json response with a session token. and on the client side, use the new token to continue the intended process. However, when i use the new token passed from server, the session token will be changed again on server side which results another TokenMismatchException.
So how should i handle the exception in a secured way without refreshing a page?
Here's what i have right now:
setup csrf_token in a global js file:
$(function () {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content') }
});
});
render method in app/exceptions/handler.php:
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else if ($e instanceof TokenMismatchException)
{
if ($request->ajax()) {
return response()->json([
'message' => 'TokenMismatchException',
'token' => csrf_token()
]);
}
}
else
{
return parent::render($request, $e);
}
}
in authentication.js:
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked')
},
success: function(response) {
if (response.message === 'TokenMismatchException') {
console.log(response); //message and token exist
//if catch the exception, use the new token to set up the ajax headers and login again
$.ajaxSettings.headers["X-CSRF-TOKEN"] = response.token;
console.log($.ajaxSettings.headers["X-CSRF-TOKEN"]);
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked'),
},
success: function(res) {
console.log(res);
},
error: function(err) {
console.log(err);
}
});
}
console.log('logged in');
},
error: function(xhr, status, err) {
}
});
thanks in advance.
In your render function, you've to check for a specific TokenMismatchException. So may be you can try something like this:
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json('msg', 'Your session has expired. Please try again.');
}
You may also pass a new csrf_token along with the json so that you can replace the old one with the new one and send the form request again.
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json(['msg'=> 'Your session has expired. Please try again.', 'token'=> csrf_token()]);
}
I haven't tested this code. But this should get you started.
Also, if you want, you can use a package: https://github.com/GeneaLabs/laravel-caffeine
It is giving me the uncaught typeerror on the $.ajax({ line below.
function set_cookie(hashtag_data)
{
$.ajax({
url: "http://domain.dev/home/set_cookie",
data: { hashtag: hashtag_data },
type: 'POST',
dataType:"json",
success: function (data) {
if (data.status == 'success') {
console.log(data.message);
} else {
console.log(data.message);
}
}
});
}
twttr.events.bind('tweet', function (event) {
console.log(event);
$(event.target).closest('div').hide().next().show();
set_cookie(event.target);
});
the home/set_cookie the ajax is suppose to post to returns a json encoded response with status and message.
// home/set_cookie, php function
public function set_cookie()
{
$hashtag = "test";
print json_encode(array('status' => 'success', 'message' => $hashtag));
exit;
}