Angular2: Send data to MySQL with php file - php

I am trying to set a CRUD system with Angular2 and MySQL and PHP, I can get my data with this code:
getClients(){
this.http.get('http://localhost/Angular%20tests/pr1/getClients.php')
.subscribe(res=>this.clients=res.json(),
error=> alert("Error get clients"),
()=> console.log("Get clients completed..."));
}
But for sending the data to the server, I don not understand were is my error, The first three instructions are giving the correct values of my entries.
onPersonneF(f:NgForm){
console.log(f.value);
console.log(JSON.stringify(f.value));
console.log(f.valid);
// test for the post
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
this.http.post('http://localhost/Angular%20tests/pr1/insertClient.php', JSON.stringify(f.value), options);
}
And the code of my php file is:
<?php
// for: Blocage d'une requête multi-origines (Cross-Origin Request)
header("Access-Control-Allow-Origin: *");
try {
$pdo = new PDO("mysql:host=localhost; dbname=test; char=utf8", '****', '****');
} catch (Exception $e) {
echo "Connexion Error".$e->getMessage();
}
$data = json_decode(file_get_contents("php://input"));
//var_dump($data);
echo "**************";
echo $data->nom_client;
echo "**************";
$nom_client = $data->nom_client;
$prenom_client = $data->prenom_client;
$no_order = $data->no_order;
$query = $pdo->prepare("insert into clients values(NULL,'".$nom_client."', '".$prenom_client."', '".$no_order."')");
$query->execute();
$query->closeCursor();
?>

Do not send it as JSON, but using URLSearchParams and headers as application/x-www-form-urlencoded instead.
onPersonneF(f:NgForm){
let body = new URLSearchParams();
// obviously set your correct parameters
body.set('myPropertyName', f.myProperty)
// the rest of data to send...
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
this.http.post('http://localhost/Angular%20tests/pr1/insertClient.php', body.toString(), options)
.map(res => res.json());
.subscribe(data => console.log(data)) // do subscription in component
}
Then you can reach your data in your php-file... here I simply retrurn the data. Remember to json_encode what you are returning :)
<?php
header("Access-Control-Allow-Origin: *");
$data = file_get_contents("php://input");
echo json_encode($data);
?>

Related

simple php script, unable return json

I wrote this simple php script, that should return a json.
I can't understand what is wrong here.
if I comment - remove the part of code regarding the connection to mySQL(PDO) I'm able to get the print out as expected otherwise Alamofire and SwiftyJson return me the error
'"JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."'
<?php
header('Content-Type: application/json');
// if i remove the pdo to connect to mySQL server the everthing work fine
// $host = "127.0.0.1";
// $user = "test";
// $password = "123456789";
// $database = "nx_database";
// try{
// $pdo = new PDO ("mysql:host=$host;dbname=$database", $user, $password);
// $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// print('connesso db -- ');
// }catch(PDOException $e){
// echo "DB Connection Fail" . $e->getMessage();
// die();
// }
$staff = $_POST['staff_ID'];
$array = [
'isLoggedIn'=>$staff
];
$js = json_encode($array);
echo $js;
?>
I attach the code also use to post the request:
func trysimple (){
let parm : [String : Any] = ["staff_ID": "3879"]
AF.request("http://127.0.0.1/nx/public/testRegister.php", method: .post,parameters: parm, headers: nil, interceptor: nil, requestModifier: nil)
.responseString { st in
print(st)
}
.responseJSON { js in
switch js.result {
case .success(let value) :
let json = JSON(value)
debugPrint(json)
case .failure(let err) :
debugPrint(err.localizedDescription)
}
}
}
}
I don't know why do you need a database connection here, but I think I know where is the mistake. You're displaying text that is not json here: print('connesso db -- '); If you expect a json format, you should display everything only in json format. Even on the failed connection possibility.
Here is how I would write it:
<?php
$host = "127.0.0.1";
$user = "test";
$password = "123456789";
$database = "nx_database";
header('Content-Type: application/json');
try{
$pdo = new PDO ("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo json_encode(['error' => "DB Connection Fail" . $e->getMessage()]);
exit;
}
$staff = $_POST['staff_ID'];
$array = [
'isLoggedIn'=>$staff
];
$js = json_encode($array);
echo $js;
?>
kindly update your code like this, for simple printing of json
<?php
header('Content-Type: application/json');
$array = array();
if(isset($_POST['staff_ID']))
{
$staff = $_POST['staff_ID'];
$array = array(
'isLoggedIn' => $staff
);
}
echo json_encode($array);

Http failure during parsing for - angular http post to php

I am able to consume the php endpoint from postman. I try to do the same from angular post, I get this error - Http failure during parsing for. Even though everything looks perfect to me, the problem is surprising. Here is my snippet
php file
<?php
header('Access-Control-Allow-Origin: *');
// check for post
if ($_SERVER['REQUEST_METHOD']=='POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$conn = new db_CONNECT();
$cone=$conn->con;
//escpae the strings to be inserted to DB
$escapedname = mysqli_real_escape_string($cone, $name);
$escapedemail = mysqli_real_escape_string($cone, $email);
$escapedsubject= mysqli_real_escape_string($cone, $subject);
$escapedmessage = mysqli_real_escape_string($cone, $message);
// mysql inserting a new row
$sql = "INSERT INTO contacts(name, email, subject, message) VALUES ('$escapedname', '$escapedemail', '$escapedsubject', '$escapedmessage')";
// $result= $cone -> query($sql);
// $affected = $cone -> affected_rows;
if (mysqli_query($cone,$sql)) {
echo "Information saved successfully.";
} else {
echo "Not successful";
}
} else {
echo "Some field missing.";
}
?>
here is the angular snippet
saveContactDetails = function () {
this.proceed = true;
this.success = false;
const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
data.append('name', this.contactDeJson.name);
data.append('email', this.contactDeJson.email);
data.append('subject', this.contactDeJson.subject);
data.append('message', this.contactDeJson.message);
this.http
.post('http://localhost:80/'+'api/create_contact.php', data.toString(), {headers: myheader})
Please why am I getting this error
{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost/api/create_contact.php","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost/api/create_contact.php",
I believe the issue is that your angular script is expecting a json response (the default responseType), but not receiving the correct headers or data. In stead of just echoing out your result in php, I would make a function that can handle sending the response. Something like this:
function sendJsonResponse(data, status = 200) {
header('Content-Type: application/json', true, status);
echo json_encode($data);
exit();
}
In stead of of doing this:
echo "Not successful";
You can now do this:
sendJsonResponse("Not successful", 500);
This should give you more valuable information in the frontend. And the response should now be formatted correctly, and no longer produce the parse error in angular that you are getting now.
I believe you are trying to send some query parameters using data variable. You could actually send a JS object as the parameters. Try the following
private saveContactDetails() {
this.proceed = true;
this.success = false;
const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
const data = {
'name': this.contactDeJson.name,
'email': this.contactDeJson.email,
'subject': this.contactDeJson.subject,
'message': this.contactDeJson.message
}
this.http.post('http://localhost:80/'+'api/create_contact.php', { params: data }, { headers: myheader })
}

Can send email using URL on Browser but on Angular it does not work

If I call the script on browser it does send email to my domain email. Anyway I'm trying to send some contact email from angular 7 apps. I did use HttpClient post and try to send the data as JSON. (Apache server PHP -v 5.6)
I have tried to send the data with URL like mail.php?param1="info#test.test"&param2="Test email". I did not have any luck. I tried file_get_contents("php://input"); no luck either.
<?php
echo("called");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
// Sanitize.
// $title = $_GET['title'];;
// $message = $_GET['message'];;
// $name = $_GET['name'];;
// $from = $_GET['from'];;
$title = $request->title;
$message = $request->message;
$name = $request->name;
$from = $request->from;
$to = "info#test.com";
// Sending email
if(mail($to, $title, $message, $name)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
Here is my Angular Service
export class PollServiceService {
PHP_API_SERVER: string = "/api";
constructor(private http: HttpClient) {
}
public SendEmail(e: any): Observable<any>{
var tmp1 = "/?title=" + e.title + "&message=" +e.message + "&name=" +e.name + "&from=" + e.from ;
return this.http.post<any>(`${this.PHP_API_SERVER}/mail.php`, e);
}
}
I do call the SendEmail(e: any) method on the form. Anyway it does not seem to do to anything. I'm suspect that the php file does not get called at all from the script. Thanks in advance guys.
Your SendEmail function returns an Observable.
You have to subsribe to this Observable in order to make the call happen.
So you should do something like that in a function in your component:
this.pollServiceService.SendEmail(e).subscribe(res => {
// here you can do whatever you want with the result of the call
});
this function should then be called from your form.

How to get the JSON Object in PHP from Android OKHttp

I have my OkHttp code here (i'm working in Android)
void postRequest(String postUrl, String postBody) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON,postBody);
Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("TAG",response.body().string());
}
});
}
And this is my PHP part
<?php
header("Content-type: application/json; charset=utf-8");
include("conexion.php");
$nombre = $_POST["nombre"];
$apellidoPaterno = $_POST['apellidoPaterno'];
$apellidoMaterno = $_POST['apellidoMaterno'];
$direccion = $_POST['direccion'];
$redesSociales = $_POST['redesSociales'];
$telefono = $_POST['telefono'];
$nombreUsuario = $_POST['nombreUsuario'];
$contrasena = $_POST['contrasenaUsuario'];
?>
I want to obtain the values that are passing through my JSON, but when I use $_POST they end with no values. I've tried with the API of reqres and it does send the information.
Any help is appreciated, thanks.
Following your and my comments you could do the following:
<?php
// header("Content-type: application/json; charset=utf-8"); // not really needed here for now
include("conexion.php");
$fgc = file_get_contents("php://input");
$json = json_decode($fgc, true);
// now you've got all your values in $json:
$nombre = $json["nombre"];
alternatively you could do:
$json = json_decode($fgc);
// now you've got all your values as an object in $json:
$nombre = $json->nombre;
further reading: http://php.net/manual/de/wrappers.php.php#wrappers.php.input
try this:
//this only you use to issue a response in json format from your php to android
//header("Content-type: application/json; charset=utf-8");
include("conexion.php");
//The following lines serve to receive a json and transform them to the variables
$data = json_decode($_POST);
$nombre = $data->nombre;
$apellidoPaterno = $data->apellidoPaterno;
$apellidoMaterno = $data->apellidoMaterno;
$direccion = $data->direccion;
$redesSociales = $data->redesSociales;
$telefono = $data->telefono;
$nombreUsuario = $data->nombreUsuario;
$contrasena = $data->contrasenaUsuario;
Of course everything depends on how you are arming the body of the post sent, on the other hand if you are making a post request from android to your php, you do not need to convert the variables to json, just pass the body and already.
You must convert to JSON only the answers of your php towards android.
SAMPLE: https://ideone.com/x2ENdd

Api returning text/html while it should return json

I am new to web service development. I didn't use any framework. I did it by scratch. I wanted to create an RESTFUL api service which I want to use for my iOS application. But I am getting some error related to content-type
This is my api.php script-
<?php
require_once "scripts/Database.php";
require_once "scripts/Database_Handler.php";
require_once "scripts/config.php";
header('Content-type:application/json;charset=utf-8'); //set the content type
$db_obj = new Database();
$db = $db_obj->get_database_connection(); //returns the database connection object
$handler = new Database_Handler($db); //this is the class that does all the queries to database
$method = $_SERVER['REQUEST_METHOD']; //method is POST here
$url = explode("/", $_SERVER['PATH_INFO']);
$request = end($url);
if($request == 'all_products'){
$result_array = $handler->get_all_products();
}
else if ($request == 'customers'){
$result_array = $handler->get_customers();
}
else{
$result_array = $handler->get_all_products_available_in_stores();
}
echo json_encode($result_array);
?>
When I try to consume the resource with the help of AFNetworking in iOS, it gives me following error.
"Request failed: unacceptable content-type: text/html" UserInfo={AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x7fe6b241c0b0> { URL: http://........../....../api.php/customers } { status code: 200, headers {
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "text/html";
Date = "Tue, 29 Dec 2015 11:16:01 GMT";
Server = "nginx/1.8.0";
"Transfer-Encoding" = Identity;
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html, NSErrorFailingURLKey=http://........../....../api.php/customers}
Can anyone please help me to solve the problem from the api end.

Categories