Axios doen't send any data to php - php

I'm using axios in Reactjs to send user's data to php and then create a new user with php,but when I want to send my data it goes empty and my php side gives some error
My react codes
import React, { useReducer } from 'react';
import axios from 'axios';
import UserContext from './userContext';
import userReducer from './userReducer';
//Register user
const registerUser = async () =>{
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const response = await axios.post('http://localhost/react_cms/api/users/user.php' , {message : 'ppp'} , config);
console.log(response.data);
}
return (
<UserContext.Provider
value={{
registerUser
}}>
{props.children}
</UserContext.Provider>
);
}
export default UserState;
And my php side codes :
<?php
$message = isset($_GET['message']) ? $_GET['message'] : 'no';
$data = array ('message' => $message);
echo json_encode($data);
?>
The result of this code is :
{message : 'no'}

You have to either change this line
$message = isset($_GET['message']) ? $_GET['message'] : 'no';
into
$message = isset($_POST['message']) ? $_POST['message'] : 'no';
or leave it as it is and send a get request by changing your axios call
from
const response = await axios.post('http://localhost/react_cms/api/users/user.php' , {message : 'ppp'} , config);
to
const response = await axios.get('http://localhost/react_cms/api/users/user.php?message=ppp', config);
Please note that the signature of the get method is different than the post method in Axios, as the get method does not require the data parameter.
It's considered good practice to when sending data to store you use the POST verb, whereas if you are retrieving data for a certain identifier, you may use GET.
Have a look at this documentation for explanations of http verbs that axios can utilize: https://restfulapi.net/http-methods/.

Related

axios/ fetch failed but postman work with php api

I got stuck when calling php api with form-data type in my React app. When I test with Postman, it works correctly but failed in react.
Please let me know if I'm doing wrong here.
In Postman, call api like this:
URl_API: xxxx/yyyy.php.
Config in Body tab in key/value: form-data
k: "some string"
id: "some string"
With axios, I had an error:
My code:
const formData = new FormData()
formData.append('k', 'some string')
formData.append('id', 'some string')
const response = await axios.post('xxxx/yyyy.php', formData, {
headers: {
'Access-Control-Allow-Origin': '*',
},
})
xxxx/yyyy.php net::ERR_HTTP2_PROTOCOL_ERROR
I had already tried with fetch but no luck - call api success with status 200 but the response.text() is empty.
With fetch api:
const result = await fetch('xxxx/yyyy.php', {
method: 'POST',
mode: 'no-cors',
body: formData,
cache: 'no-cache',
})
.then(async (res) => {
return res.text()
})
.then((text) => console.log('It is empty here', text))
It look like a CORS also, but you will be able to sort it out
a simple solution in development is to use a local api server, and finally when the app is deployed to the server which is on the same domain as the api, you should get the response, as demonstrated below by making the calls using dev tools.
in short: if a api calls work with postman but not through the browser, its mostly due to cors restrictions, then it could be the response type
Verifying cors issue by making calls throught dev tools
let onSubmit = async () => {
try {
const url = "https://www.your-domain***.com/getUrlApp.php";
const formData = new FormData();
formData.append("k", "kk");
formData.append("id", "dd");
const data = new URLSearchParams(formData);
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "no-cors", // no-cors, *cors, same-origin
body: data // body data type must match "Content-Type" header
});
//const res = response.json();
const buffer = await response.arrayBuffer();
const decoder = new TextDecoder("iso-8859-1");
const text = decoder.decode(buffer);
console.log("text", text);
return response;
} catch (error) {
console.log("error", error);
}
};
To verify the response
go https://www.your-domain***.com
open dev tools => console
past the function above and run it by typing onSubmit() in the console
you will see the response
Hope it helps you in some way

Retreive Html form value in a PHP script using an Angular Service

I have an Angular 5 App with a contact form and I want to be able to retreive data from this form via a service in my PHP Script.
Here is my html
contact.html
<div class="">
<input [(ngModel)]= "subjet" name="subjet" type="text">
<label for="">subject</label>
</div>
When I click on my from button I call a function sendmail(subject) in the same component.
contact.component.ts
export class ContactComponent implements OnInit {
constructor(private sendMailService:SendMailService) { }
sendmail(subjet):void{
this.sendMailService.performGetEx().subscribe( (v =>
console.log('value: ', v)),
(e => console.log('error: ', e)),
(() => console.log('the sequence completed! :' ,subjet)));
}
And finally my service :
Injectable()
export class SendMailService {
private url = 'assets/php/sendmail.php'
constructor(private http:HttpClient) { }
performGetEx():Observable<any>{
return this.http.get<any>(this.url,
{
responseType: 'text' as 'json'
});
}
This service is the one that use the PHP Script but I can't find a way to retreive my subject value in my PHP Script.
When I do something like that $sujet = $_POST['sujet'];it doesn't work. It could have worked if my script was in the same folder as my contact component but it's not the case.
Do you know how I can do It ?
UPDATE 1 :
This link could be helpful, it might be the solution for people that have this issue : Angular HTTP post to PHP and undefined
Im my case when I do the following :
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$subject = $request->subject;
I have an error because my $postdata variable is empty ! Still don't know why
UPDATE 2 :
Like #Simos said I checked and I didn't see the data sent from Angular in my network.
So I changed my SendmailService class method from get to post.
Injectable()
export class SendMailService {
private url = 'assets/php/sendmail.php'
constructor(private http:HttpClient) { }
performGetEx():Observable<any>{
return this.http.post<any>(this.url,
{
responseType: 'text' as 'json'
});
}
I get an other error HttpErrorResponse SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse.
I already had this error before and had to add the reponseType: 'text' as 'json' in order to avoid it...And now it don't work with the post method....

Pass multiple values with http GET from Angular2 to php

Am using Angular2 as front end and php as my server script . I want to pass the user login details to server with the http.get() .
I used like..
var uname = event.email;
var pass = event.password;
this.http
.get('http://192.168.0.100:80/php/logincheck.php?user='+uname+'&pwd='+pass).subscribe();
but it can't get the 2 values. I can simply pass a single value easily.
If 2 values can be passed like this. Please help ..
I do not think it is secured to send a password without doing some sort of encrypting. but if you want to send some data to your server request it is possible to send them in the request headers as well. see below code snippet.
//on import section
import { Http, Headers, RequestOptions } from '#angular/http';
//inside your login function
let requestUrl= "http://192.168.0.100:80/php/logincheck.php"
let requestOptions = new RequestOptions();
requestOptions.headers = new Headers({ 'Content-Type': 'application/json', 'email': event.email,
'pwd': event.password });
this.http.get(requestUrl, this.requestOptions).subscribe();
Try like this :
import { URLSearchParams, BaseRequestOptions } from '#angular/http';
getLogin() {
const options: BaseRequestOptions = new BaseRequestOptions();
const params: URLSearchParams = new URLSearchParams();
params.set('uname', event.email);
params.set('pass', event.password);
options.search = params;
return this.http.get('http://192.168.0.100:80/php/logincheck.php', options)
.map(res => res.json())
}
Server side :
<?php
echo $_GET['uname'];
?>
or
$url = parse_url($url);
parse_str($url['query'], $queryParams);
echo $queryParams['uname'];
echo $queryParams['pass'];

How to post data using AWS API Gateway Http?

I am using AWS API Gateway. I want to post data to my controller which resides on my server directory.
I've created one API which has a development resource and POST method.
I've also added OPTIONS method to add headers.
I am using ajax to send the request data to controller.
Data is always empty.
Controller is in CakePHP
function which I am calling is
function webservice() {
if(empty($this->data['username'])){
echo json_encode("Data is Empty");
}
else{
$username = $this->data['username'];
$password = $this->data['password'];
$deviceType = $this->data['deviceType'];
$token = $this->data['token'];
$conditions= array('username' => $username,
'password' => $password,
'token' => $token,
'deviceType' => $deviceType
);
echo json_encode($conditions);
}
exit();
}
Ajax Call is :
var username = "dummydata";
var password = "dummydata";
var deviceType = "dummydata"
var token = "dummydata";
alert(username + password + token);
$.ajax(
{
type : "POST",
url : "https://xxxxxxxxxx.execute-api.ap-southeast-1.amazonaws.com/dev/webserv",
data: "{username : username, password: password, token: token, deviceType: deviceType}",
success : function(result){
alert((result));
}
});
How to receive posted data from AJAX in controller using AWS API Gateway?
First you need to provide a mapping template to API Gateway to allow it to map request data to your Lambda function call. Second, pay attention to "Content Type" you set on the mapping template, and set that same content type in your AJAX call in order to trigger the use of that template.
For example if you set the content type in API Gateway to "application/json" then you would set this property on your jQuery AJAX call: contentType: "application/json"
As for the mapping template, I find it easiest to just use a template that always maps everything from the incoming request. I use this template, taken from this answer:
{
"method": "$context.httpMethod",
"body" : $input.json('$'),
"headers": {
#foreach($param in $input.params().header.keySet())
"$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end
#end
},
"queryParams": {
#foreach($param in $input.params().querystring.keySet())
"$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end
#end
},
"pathParams": {
#foreach($param in $input.params().path.keySet())
"$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end
#end
}
}

IBM Worklight - How to access JSON sent using an adapter in server-side PHP?

I am developing a hybrid application in IBM Worklight.
In my app, there is a registration form. I have a requirement: After the user registers with the app, the form data will be sent to an external server in JSON format using an HTTP adapter.
In the external server,
How to access the JSON data sent using the HTTP adapter in a PHP file? and
How to send back a response in the same JSON format?
Please give demo codes of both HTTP adapter and server side PHP code.
Client code:
function callAdapter(){
var invocationData = {
adapter : 'MyAdapter',
procedure : 'MyAdapterProcedure',
parameters : [username, password]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : adapterSuccessCallback,
onFailure : adapterFailureCallback
});
}
Adapter implementation:
function myAdapterProcedure(username, password) {
var credentials = JSON.stringify({username: username, password: password});
var input = {
method : 'post',
returnedContentType : 'json',
path : "/myPHPscript.php",
parameters: {credentials: credentials}
};
return WL.Server.invokeHttp(input);
}
PHP script:
<?php
$jsonObj = $_POST['credentials'];
$credentials = json_decode($jsonObj)
// sanitation, database calls, etc
$returnDict = array();
$returnDict["success"] = true;
echo json_encode($returnDict);
?>

Categories