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);
Related
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 })
}
I am trying to send a JSON array to the web server. I have looked at several examples online i.e. https://www.youtube.com/watch?v=aTj0ZLha1zE&t and Saving CoreData to a Web Server with Swift 3.0 that have demonstrated how to parse data but I am struggling to achieve this.
Below is my function which should send the data to the server:
func sendRecordToServer() -> [Record] {
let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"Record")
fetchRequest.resultType = .dictionaryResultType
do {
let records = try context.fetch(fetchRequest)
if let jsonData = try? JSONSerialization.data(withJSONObject: records, options: []) {
// jsonData is a byte sequence, to view it you would need to convert to string
print(String(bytes: jsonData, encoding: String.Encoding.utf8))
let URL_SAVE_DATA = URL(string: "http://localhost/api/postdata.php")
let request = NSMutableURLRequest(url: URL_SAVE_DATA!)
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("error=\(String(describing: error?.localizedDescription))")
return
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
}
} catch {
print("Error fetching data from CoreData")
}
return records
}
After encoding the data to JSON, it prints out like this:
Optional([["record_id": 8EC9C1C9-7DD4-4343-B7CC-E4615FDDA150, "name": John ], ["record_id": 7EEA551D-9432-4737-99FB-6BFCF3A92D21, "name": Fred Smith]])
However as I try parsing it though to the server I get this and nothing get sent to the server:
responseString = Optional("")
Update:
Following up from the comment below here is what my posdata.php looks like:
<?php
//creating response array
$json = file_get_contents('php://input');
//echo $json shoulkd show the json string
$array = json_decode($json, true);
// var_dump($arr) should show the array structure
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$record_id = $_POST['record_id'];
$name = $_POST['name'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($record_id, $name)){
$response['error']=false;
$response['message']='Record added successfully';
}else{
$response['error']=true;
$response['message']='Could not add record';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
DBOperation:
<?php
class DbOperation
{
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createTeam($record_id, $name)
{
$stmt = $this->conn->prepare("INSERT INTO record (record_id, name) values (?, ?)");
$stmt->bind_param("si", $record_id, $name);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}
I have developed a php web service on a server with mysql database connection. It can not connect to database and does not execute codes after database connection. Also it does not show any error.
If I return something before database connection line, it is returned.
I have tested another php file with database connection and it works properly.
<?php require_once('lib/nusoap.php');
$server = new soap_server();
$server->configureWSDL('ivrmci', 'urn:ivrmciwsdl');
$server->register('upload_file', // method
array('username' => 'xsd:string','password' => 'xsd:string','encoded_filepath' => 'xsd:string','filename' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:ivrmciwsdl', // namespace
'urn:ivrmciwsdl#upload_file', // soapaction
'rpc', // style
'encoded', // use
'Uploads files to the server' // documentation
);
$server->register('inquiryMsisdnCalls', // method
array('username' => 'xsd:string','password' => 'xsd:string','callerid' => 'xsd:string','advertise_id' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:ivrmci', // namespace
'urn:ivrmci#inquiryMsisdnCalls', // soapaction
'rpc',
'encoded', // style // use
'Returns User Log' // documentation
);
function upload_file($username,$password,$encoded,$name) {
if ($username != "abc" OR $password != "123")
{
return "-2";
}
$location = "uploads/".$name; // Mention where to upload the file
//$current = file_get_contents($location); // Get the file content. This will create an empty file if the file does not exist
$current = base64_decode($encoded); // Now decode the content which was sent by the client
file_put_contents($location, $current); // Write the decoded content in the file mentioned at particular location
try
{
$db = new PDO('mysql:dbname=zzz;host=x.x.x.x',"root","1234",array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
return "-3";
}
$filename = explode(".", $name);
$sql = "INSERT INTO advertise (name) VALUES ($filename[0])";
try{
$db->exec($sql);
return $db->lastInsertid();
}
catch(PDOException $e)
{
return $e->getMessage();
}
if($name!="")
{
return "File Uploaded successfully..."; // Output success message
}
else
{
return "Please upload a file...";
}
}
function inquiryMsisdnCalls($username,$password,$callerid,$contentid)
{
if ($username != "abc" OR $password != "123")
{
return "-2";
}
try
{
$db = new PDO('mysql:dbname=zzz;host=x.x.x.x',"root","1234",array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
return "-3";
}
$sql = "select status from user_advertise_log where callerId=$callerid and advertise_id=$contentid";
try{
$log = $db->query($sql)->fetch(PDO::FETCH_OBJ);
return $log->status;
}
catch(PDOException $e)
{
return $e->getMessage();
}
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
i am using the below code to connect to salesforce using php
require_once ('SforcePartnerClient.php');
require_once ('SforceHeaderOptions.php');
require_once ('SforceMetadataClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("cniRegistration.wsdl");
$loginResult = $mySforceConnection->login("username", "password.token");
$queryOptions = new QueryOptions(200);
try {
$sObject = new stdclass();
$sObject->Name = 'Smith';
$sObject->Phone = '510-555-5555';
$sObject->fieldsToNull = NULL;
echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create($sObject, 'Account');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
echo $e->faultstring;
}
But the above code is connect to salesforce database.
But is not executing the create commands. it's giving me the below error message
Creating the following: Element {}item invalid at this location
can any one suggest me to overcome the above problem
MAK, in your sample code SessionHeader and Endpoint setup calls are missing
$mySforceConnection->setEndpoint($location);
$mySforceConnection->setSessionHeader($sessionId);
after setting up those, if you still see an issue, check the namespace urn
$mySforceConnection->getNamespace
It should match targetNamespace value in your wsdl
the value of $mySforceConnection should point to the xml file of the partner.wsdl.xml.
E.g $SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
Try adding the snippet code below to reference the WSDL.
$sfdc = new SforcePartnerClient();
// create a connection using the partner wsdl
$SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
$loginResult = false;
try {
// log in with username, password and security token if required
$loginResult = $sfdc->login($sfdcUsername, $sfdcPassword.$sfdcToken);
}
catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Fatal Login Error <b>" . $errors . "</b>";
die;
}
// setup the SOAP client modify the headers
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_SALESFORCE_URL_", "https://test.salesforce.com");
define ("_WS_NAME_", "WebService_WDSL_Name_Here");
define ("_WS_WSDL_", "soapclient/" . _WS_NAME_ . ".wsdl");
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
$urlLink = '';
try {
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
} catch ( Exception $e ) {
die( 'Error<br/>' . $e->__toString() );
}
Please check the link on Tech Thought for more details on the error.
I got some problem with php-sample.
I want to add users, but there were something went wrong.
Please help me!!
Here is code that I used:
<!DOCTYPE html>
<?php
require_once "vendor/autoload.php";
require_once "autoload.dist.php";
require_once "client/JasperClient.php";
require_once "client/User.php";
require_once "client/Role.php";
$client = new Jasper\JasperClient(
"localhost", // Hostname
8080, // Port
"jasperadmin", // Username
"jasperadmin", // Password
"/jasperserver-pro", // Base URL
"organization_1"
); // Organization (pro only)
$newUser = new Jasper\User("BI_User", // username
"superSTRENGTHpassw0rd", // password
"clever#email.com", // email
"Business Intelligence User", // description
"organization_1", // parent organization
"true" // enabled
);
$role = new Jasper\Role("ROLE_USER", NULL, "false");
$newUser->addRole($role);
try {
$client->putUsers($newUser);
}
catch (Exception $e) {
printf("Could not add new user: %s", $e->getMessage());
}?>
And Here is the error message that I got:
Could not add new user: Unexpected HTTP code returned: 400 Body of response:
Apache Tomcat/6.0.26 - Error report HTTP Status 400 - type Status
reportmessage description The request sent by the client was syntactically
incorrect ().Apache Tomcat/6.0.26
Ask I spent time google so much on that problem, I have found the solution.
Here is my solution whether someone are interested.
<?php
require_once "vendor/autoload.php";
require_once "autoload.dist.php";
use Jaspersoft\Client\Client;
use Jaspersoft\Dto\User\User;
use Jaspersoft\Dto\Role\Role;
function registerUsers(){
$client = new Client(
"localhost",
"8080",
"superuser",
"superuser",
"/jasperserver-pro",
"null"
);
$file_path = 'data/userlist.csv';
$handle = fopen($file_path,'r');
$array_users = array();
$i=0;
while (!feof($handle) !==false){
$line = fgetcsv($handle,1024,',');
$i++;
if($i==1) continue;
if(!empty($line)){
for($c = 0; $c < count($line); $c++){
$username = $line[0];
$password = $line[1];
$email = $line[2];
$fullname = $line[3];
$tenantId = $line[4];
$enabled = $line[5];
$user = new User($username, $password, $email,
$fullname, $tenantId, $enabled);
$role = new Role('ROLE_USER', null, 'false');
$array_users[$c] = $user;
$array_users[$c]->addRole($role);
try {
$client->userService()->addUsers($array_users[$c]);
} catch (Exception $e) {
printf('Could not add new user: %s', $e->getMessage());
}
}
}
}
}?>
And here is my csv data file:
User Name,Password,Email Address,Full Name,Tenant ID,Enable
User1,superSTRENGTHpassw0rd,clever#email.com,User One,a,true
User2,superSTRENGTHpassw0rd,clever#email.com,User One,a,true
User3,superSTRENGTHpassw0rd,clever#email.com,User One,a,true
User6,superSTRENGTHpassw0rd,clever#email.com,User One,organization_1,true
User7,superSTRENGTHpassw0rd,clever#email.com,User One,organization_1,true
User8,superSTRENGTHpassw0rd,clever#email.com,User One,b,true
User9,superSTRENGTHpassw0rd,clever#email.com,User One,b,true
User10,superSTRENGTHpassw0rd,clever#email.com,User One,c,true
User11,superSTRENGTHpassw0rd,clever#email.com,User One,c,true