I am trying to fetch some data from a test API posting some data to it, but I get an error for response.json().
I get no error when fetching data without posting anything from another API.
My JavaScript:
fetch('https://cuteweb.ir/translatochka/requests.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
requestKey: 'checkLogged'
})
})
.then(response => response.json())
.then(parsed => console.log(parsed))
.catch(error => console.log(error))
and here is my API code in PHP:
$requestKey = isset($_POST['requestKey'])? $_POST['requestKey']: false;
if($requestKey){
switch ($requestKey) {
case 'checkLogged':
$_SESSION['username'] = "sinaw";
$sql = "SELECT DISTINCT * FROM tbl_users where
username='$_SESSION[username]'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
$row['valid'] = true;
echo json_encode($row);
}
break;
My API code works correctly as I have tested it with jQuery $.ajax method.
This is the error I get:
SyntaxError: Unexpected end of JSON input
Related
fetch("http://10.0.2.2:80/NewAdmin/scripts/main/transactions", {
method:'post',
headers:{
"Accept":"application/json",
"Content-type":"application/json"
},
// (var) payload looks like this {Header: "Sending", . . .}
body:JSON.stringify(payload)
})
.then(res => res.json())
.then(resp => console.log(resp))
.catch(err => console.log(err));
My PHP code
<?php
$json = json_decode(file_get_contents('php://input'), true);
echo $json;
if($json["Header"] == "Sending"){
echo json_encode('!WTF');
}else{
echo json_encode('WTF!');
}
?>
It returns 'WTF!'—no pun intended. What am I missing?
Try this example, it should return 'action test' OR Error,
JS Code:
fetch(ConfigApp.URL + 'transactions.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'action test',
p: 'addSession',
}),
})
.then(response => response.json())
.then(responseJson => {
console.warn(responseJson)
})
.catch(function(error) {
console.warn(Strings.no_result + error.message);
});
PHP transactionsv.php:
<?php
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the i ncoming RAW post data from JSON.
$decoded = json_decode($content, true);
if(!is_array($decoded)){
$json_string = json_encode(false);
print ($json_string);
die();
}elseif(!isset($decoded["p"])){
$decoded = $decoded[0];
}
switch ($decoded["p"]) {
case 'addSession':
print (json_encode($decoded['action']));
break;
default:
$json_string = json_encode(false);
print ($json_string);
break;
}
I Create login form for React Native App with mysql database
it seems that it doesn't see the query in my api keep showing the invalid message 'Invalid Username or Password Please Try Again' while the data is correct
I didn't figure out where is the problem
please anyone help me on this
login.js
// Creating Login Activity.
export default class LoginActivity extends Component {
// Setting up Login Activity title.
static navigationOptions =
{
title: 'LoginActivity',
};
constructor(props) {
super(props)
this.state = {
UserEmail: '',
UserPassword: ''
}
}
UserLoginFunction = () =>{
const { UserEmail } = this.state ;
const { UserPassword } = this.state ;
fetch('http://URL', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: UserEmail,
password: UserPassword
})
}).then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('Second', { Email: UserEmail });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
this the api I tried different ones but didn't know where is the error exactly
API
<?php
// Importing DBConfig.php file.
include 'DBConfig.php';
// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
// Populate User email from JSON $obj array and store into $email.
$email = $obj['email'];
// Populate Password from JSON $obj array and store into $password.
$password = $obj['password'];
//Applying User Login query with email and password match.
$Sql_Query = "select * from customers where email = '$email' and password = '$password' ";
// Executing SQL Query.
$check = mysqli_fetch_array(mysqli_query($con,$Sql_Query));
if(isset($check)){
$SuccessLoginMsg = 'Data Matched';
// Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);
// Echo the message.
echo $SuccessLoginJson ;
}
else{
// If the record inserted successfully then show the message.
$InvalidMSG = 'Invalid Username or Password Please Try Again' ;
// Converting the message into JSON format.
$InvalidMSGJSon = json_encode($InvalidMSG);
// Echo the message.
echo $InvalidMSGJSon ;
}
mysqli_close($con);?>
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.
I get Notice: Undefined index response when i post data to php API using FormData in React Native. But when i hard code parameters in the php file i am able to get results.
I have tried using JSON.stringify from React docs. I get same problem.
On the server side i tried suggested file_get_contents('php://input') which just returns null.
var data = new FormData();
data.append({
latitude: '55555',
longitude: '9999',
});
fetch('http://localhost/someapi', {
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type': 'multipart/form-data',
'Content-length': data.length
},
body: data
})
.then((response)=>response.text())
.then((response)=>{
console.log(' Show response');
console.log(response);
})
.catch((err)=>{
console.warn(err);
});
I am using response.text() so i can display the error. otherwise response.json() gives me Unexpected token < because it returns html
Here is my PHP server code
$lat = $_POST['latitude'];
$lng = $_POST['longitude'];
echo json_encode($lat);
I also tried
$json = file_get_contents('php://input');
$obj = json_decode($json, TRUE);
echo $obj;
you are passing 'multipart/form-data' header , so you have to pass formdata to body instead of JSON.stringify
var formData = new FormData();
formData.append('latitude', 55555);
formData.append('longitude', 9999);
fetch('http://localhost/someapi', {
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then((response)=>{
console.log('Response ==>',response);
})
.catch((err)=>{
console.warn(err);
});
Just omit the header object in your Fetch API it would work fine
headers:{
'Accept':'application/json',
'Content-Type': 'multipart/form-data'
}
the solution should be like this
fetch('http://localhost/someapi', {
method:'POST',
body: data
})
.then((response)=>response.text())
.then((response)=>{
console.log(' Show response');
console.log(response);
})
.catch((err)=>{
console.warn(err);
});
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();
}
}