AJAX Javscript - PHP - javascript

I learn MVC and make some AJAX interaction. So I've routes file with
'cart/addProductAjax' => 'cart/addProductAjax',
CartController with actionAddProductAjax:
<?php
class CartController
{
public function actionIndex() {
}
public function actionAdd($productId) {
Cart::addProduct($productId);
$referer = '/';
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
}
header("Location: $referer");
}
public function actionAddProductAjax() {
$productId = $_POST['productId'];
print_r($_POST);
exit;
Cart::addProduct($productId);
$itemsAmount = Cart::countItems();
exit(json_encode($itemsAmount));
}
}
And JS piece of code that send request and receive response from the server:
document.body.addEventListener('click', event => {
if(event.target.classList.contains('add-to-cart')) {
event.preventDefault();
let productId = event.target.dataset.id;
let response = fetch("/cart/addProductAjax/", {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(productId),
})
.then(response => response.json())
.then(response => console.log(response));
}
});
And nothing works. I think there is an error somewhere in PHP method. What shoul I do to make it work?

Related

SpringBoot Required request body is missing from browser

i have a POST request using springboot, everything works fine when i make tests on postman but when i try it from the browser i get this error,
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.
this is my code.
the Service class
#Transactional(rollbackFor = {SQLException.class})
public ResponseEntity<Message> save(Cursos cursos) {
Optional<Cursos> optionalCursos = cursosRepository.findByTituloCursos(cursos.getTituloCursos());
if (optionalCursos.isPresent()) {
return new ResponseEntity<>(new Message("la entrada ya existe", null), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new Message("ok", false, cursosRepository.saveAndFlush(cursos)), HttpStatus.OK);
}
DTO class
public class CursosDTO {
long id;
#NotNull
String tituloCursos;
#NotNull
String cuerpocursos;
public CursosDTO() {
}
public CursosDTO(long id, String tituloCursos, String cuerpocursos) {
this.id = id;
this.tituloCursos = tituloCursos;
this.cuerpocursos = cuerpocursos;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTituloCursos() {
return tituloCursos;
}
public void setTituloCursos(String tituloCursos) {
this.tituloCursos = tituloCursos;
}
public String getCuerpocursos() {
return cuerpocursos;
}
public void setCuerpocursos(String cuerpocursos) {
this.cuerpocursos = cuerpocursos;
}
}
controller class
#PostMapping("/")
public ResponseEntity<Message> save(#RequestBody CursosDTO cursosDTO) {
Cursos saveCursos = new Cursos(cursosDTO.getTituloCursos(), cursosDTO.getCuerpocursos());
return cursosService.save(saveCursos);
}
and this is my JavaScript code
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
let dataUpd = {
tituloCursos: titulo,
cuerpocursos: contenido
};
console.log(JSON.stringify(dataUpd) + " prueba");
fetch(url, {
method: "POST",
BODY: dataUpd,
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.catch((error) => console.error("error al subir datos: ", error))
.then((response) => {
console.log("Datos subidos: ", response);
})
})
when i fetch data it brings all the data stored in the db correctly and this is the info that im trying to store
{"tituloCursos":"Stack","cuerpocursos":"<p>Overflown</p>"}
just in case it is relevant im using edge browser and im trying to store info from a rich text editor using tinymce
Probably a very simple typo. You capitalized BODY in your Post requests js code. It needs to be lowercase: body
See: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options
Also, you would need to JSON.stringify your Data so your request options for the Post request would look like this:
method: "POST",
body: JSON.stringify(dataUpd),
headers: {
"Content-Type": "application/json",
},

POST request parameters are not detected by PHP

I am trying to submit some data with fetch to a php backend, but no request arrives on the backend.
The following is triggered on a change event.
JS
const submitVote = async (value) => {
const vote = { vote: value };
console.log('vote:', vote);
let postVote = await fetch('Backend/postHandler.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json;charset=utf-8' },
body: JSON.stringify(vote)
});
let result = await postVote.text();
console.log('result:',result);
};
Logs vote: Object { vote: "yes" } to the console.
On the backend
PHP
<?php
namespace WebPoll\Backend;
if(isset( $_POST['vote'] )) {
$a = ["vote" => $_POST['vote']];
$myJSON = json_encode($a);
echo $myJSON;
} else {
print_r($_POST);
}
Logs result: array() to the JS console.
What is wrong here? Thanks.

in Vue PUT POST DELETE method showing not allowed when middlewear included

I am trying to implepement vue in my laravel application. Simple CRUD. The fetching and showing of data is working fine, but edit, delete, add is not. It is working if there is no auth checking middlewear in feedController. Need to make it work while the middlewear included.
Here is my add method:
fetch('api/feed', {
method: 'post',
body: JSON.stringify(this.feed),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then( data=> {
this.feed.title = '';
this.feed.body = '';
alert('Feed Added');
this.fetchFeeds();
})
Here is my delete method:
deleteFeed(id){
if (confirm('Are you sure you want to delete?')){
fetch(`api/feed/${id}`, {
method: 'delete'
})
.then(res => res.json())
.then(data=> {
alert('Article Removed');
this.fetchFeeds();
})
.catch(err => console.log(err));
}
}
Here are the routes in api.php
/Create new feed
Route::post('feed', 'FeedController#store');
//Update feed
Route::put('feed', 'FeedController#store');
//Delete feed
Route::delete('feed/{id}', 'FeedController#destroy');
And finally here is the controller's functions where the middlewear is.
For adding:
public function store(Request $request)
{
$feed = $request->isMethod('put')?Feeds::findOrFail($request->feed_id):new Feeds;
$feed->id= $request->input('feed_id');
$feed->title= $request->input('title');
$feed->body= $request->input('body');
// $feed->image= "Test Image String";
// $feed->link="Test Link String";
// $feed->user_id=4;
if($feed->save())
{
return new FeedResource($feed);
}
}
For deleting:
public function destroy($id)
{
$feed = Feeds::findOrFail($id);
if ($feed->delete()){
return new FeedResource($feed);
}
}

How to send data to server React Native |

I made a react native project and I got a prolem
I try to send a data to my server but the server didn't get the data.
I already made a code but its not work properly
and here's my code
constructor(props) {
super(props)
this.state = {
e :"",
}
}
componentWillMount(){
this.UserLoginFunction(View);
}
UserLoginFunction = () =>{
fetch('https://sen.000webhostapp.com/Profile.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
em: this.state.e,
})
}).then((response) => response.json())
.then((responseJson) => {
Alert.alert(JSON.stringify(responseJson));
}).catch((error) => {
Alert.alert(error);
});
}
render() {
AsyncStorage.multiGet(['email']).then((data) => {
let email = data[0][1];
if (email !== null){
this.setState({
e:email
});
}
});
return()
}
and the .php file is
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$u = $obj['em'];
echo json_encode($u);
but the respond is nothing I got null. can anyone solve this?

Laravel -, Can't update more than one record using Fetch Api

I want to update my multiple records. But only first record is updating, other ones aren't..
I'm using fetch api for ajax call, but I thins problem is not here, cause I'm able to send array data, I can see in browser dev section. (I mean, I can send multiple id data, it's ok)
Then I'm trying to save them in foreach loop, but only first record is updating in this loop.
in controller
public function approveComment(Request $request)
{
if ($request->ajax()) {
$ids = $request->json()->all();
foreach ($ids as $id) {
$comment = Comments::find($id);
$comment->comment_status = 1;
$comment->save();
}
return response()->json("successful");
} else {
$comment = Comments::find($request->input('comment_id'));
$comment->comment_status = 1;
$comment->save();
return back();
}
}
ajax call;
ajax.put('comments/approve',token,ids)
.then(data => data.json())
.then(log => console.log(log))
.catch(err => console.log(err))
put method in ajax class
async put(url, token, data) {
const response = await fetch(url, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": token
},
method: "put",
credentials: "same-origin",
body: JSON.stringify(data)
});
return response;
}
I find the problem;
public function approveComment(Request $request)
{
if ($request->ajax()) {
$ids = $request->json()->all();
foreach ($ids as $id) {
$comment = Comments::find($id);
$comment->comment_status = 1;
$comment->save();
// return response()->json("successful"); (it was here)
}
return response()->json("successful"); (it should be in here, not in loop)
} else {
$comment = Comments::find($request->input('comment_id'));
$comment->comment_status = 1;
$comment->save();
return back();
}
}

Categories

Resources