how to insert data into tally using php? - php

i have fetch data from tally erp 9.0 using this code,
<?php
$requestXML = '<ENVELOPE>'.
'<HEADER>'.
'<TALLYREQUEST>Export Data</TALLYREQUEST>'.
'</HEADER>'.
'<BODY>'.
'<EXPORTDATA>'.
'<REQUESTDESC>'.
'<REPORTNAME>Daybook</REPORTNAME>'.
'<STATICVARIABLES>'.
'<SVEXPORTFORMAT>$$SysName:XML</SVEXPORTFORMAT>'.
'</STATICVARIABLES>'.
'</REQUESTDESC>'.
'</EXPORTDATA>'.
'</BODY>'.
'</ENVELOPE>';
$server = 'LOCALHOST:9000';
$headers = array( "Content-type: text/xml","Content-length:".strlen($requestXML) ,"Connection: close");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
echo " request accepted";
print $data;
curl_close($ch);
}
But my problem is how to push(insert) data into Tally ERP 9.0 using php(curl).

instead of
$server = 'LOCALHOST:9000';
give
$server = '10.0.0.155:9000';

use tally to generate xml format, and use same format to insert data back in to tally for eg.
to create sale voucher, get the xml from tally
i.e
GatewayOfTAlly-->Display-->Account Books--> Sales Register-->chhose
month-->ctl+E to export the voucher,
Now you got the xml format, you are good to go.

Instead of
$server = 'LOCALHOST:9000';
Use
$server = 'http://localhost:9000';

<form action="" method="post">
<table width="100%" border="1">
<tr>
<th scope="col">Name</th>
<td><input name="nm" id="nm" type="text" /></td>
</tr>
<tr>
<td colspan="4"><div align="center">
<label>
<input type="submit" name="sub" value="Submit" />
</label>
</div></td>
</tr>
</table>
</form>
<?php
/* This is PHP code to insert an entry in Tally. All required XML tags by Tally are taken here in a string and name for Ledger is taken by posted value from HTML form. */
if(isset($_POST['sub']))
{
$name = $_POST['nm'];
$requestXML = '<?xml version="1.0"?>
<ENVELOPE>
<HEADER>
<TALLYREQUEST>Import Data</TALLYREQUEST>
</HEADER>
<BODY>
<IMPORTDATA>
<REQUESTDESC>
<REPORTNAME>Vouchers</REPORTNAME>
<STATICVARIABLES>
<SVCURRENTCOMPANY>SAVH</SVCURRENTCOMPANY>
</STATICVARIABLES>
</REQUESTDESC>
<REQUESTDATA>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<VOUCHER REMOTEID="123" VCHTYPE="Receipt" VCHKEY="321" ACTION="Create" OBJVIEW="Accounting Voucher View">
<OLDAUDITENTRIES.LIST> </OLDAUDITENTRIES.LIST>
<ACCOUNTAUDITENTRIES.LIST> </ACCOUNTAUDITENTRIES.LIST>
<AUDITENTRIES.LIST> </AUDITENTRIES.LIST>
<OLDAUDITENTRYIDS.LIST TYPE="Number">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<DATE>20130401</DATE>
<GUID>f6c10ce3-4a15-42b8-961e-143a512a9e62-00000009</GUID>
<VOUCHERTYPENAME>Receipt</VOUCHERTYPENAME>
<VOUCHERNUMBER>5</VOUCHERNUMBER>
<PARTYLEDGERNAME>'.$name.'</PARTYLEDGERNAME>
<CSTFORMISSUETYPE/>
<CSTFORMRECVTYPE/>
<FBTPAYMENTTYPE>Default</FBTPAYMENTTYPE>
<PERSISTEDVIEW>Accounting Voucher View</PERSISTEDVIEW>
<VCHGSTCLASS/>
<DIFFACTUALQTY>No</DIFFACTUALQTY>
<AUDITED>No</AUDITED>
<FORJOBCOSTING>No</FORJOBCOSTING>
<ISOPTIONAL>No</ISOPTIONAL>
<EFFECTIVEDATE>20130401</EFFECTIVEDATE>
<ISFORJOBWORKIN>No</ISFORJOBWORKIN>
<ALLOWCONSUMPTION>No</ALLOWCONSUMPTION>
<USEFORINTEREST>No</USEFORINTEREST>
<USEFORGAINLOSS>No</USEFORGAINLOSS>
<USEFORGODOWNTRANSFER>No</USEFORGODOWNTRANSFER>
<USEFORCOMPOUND>No</USEFORCOMPOUND>
<ALTERID>20</ALTERID>
<EXCISEOPENING>No</EXCISEOPENING>
<USEFORFINALPRODUCTION>No</USEFORFINALPRODUCTION>
<ISCANCELLED>No</ISCANCELLED>
<HASCASHFLOW>Yes</HASCASHFLOW>
<ISPOSTDATED>No</ISPOSTDATED>
<USETRACKINGNUMBER>No</USETRACKINGNUMBER>
<ISINVOICE>No</ISINVOICE>
<MFGJOURNAL>No</MFGJOURNAL>
<HASDISCOUNTS>No</HASDISCOUNTS>
<ASPAYSLIP>No</ASPAYSLIP>
<ISCOSTCENTRE>No</ISCOSTCENTRE>
<ISSTXNONREALIZEDVCH>No</ISSTXNONREALIZEDVCH>
<ISEXCISEMANUFACTURERON>No</ISEXCISEMANUFACTURERON>
<ISBLANKCHEQUE>No</ISBLANKCHEQUE>
<ISDELETED>No</ISDELETED>
<ASORIGINAL>No</ASORIGINAL>
<VCHISFROMSYNC>No</VCHISFROMSYNC>
<MASTERID>9</MASTERID>
<VOUCHERKEY>177657027231784</VOUCHERKEY>
<INVOICEDELNOTES.LIST> </INVOICEDELNOTES.LIST>
<INVOICEORDERLIST.LIST> </INVOICEORDERLIST.LIST>
<INVOICEINDENTLIST.LIST> </INVOICEINDENTLIST.LIST>
<ATTENDANCEENTRIES.LIST> </ATTENDANCEENTRIES.LIST>
<ORIGINVOICEDETAILS.LIST> </ORIGINVOICEDETAILS.LIST>
<INVOICEEXPORTLIST.LIST> </INVOICEEXPORTLIST.LIST>
<ALLLEDGERENTRIES.LIST>
<AMOUNT>200000.00</AMOUNT>
<OLDAUDITENTRYIDS.LIST TYPE="Number">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<LEDGERNAME>'.$name.'</LEDGERNAME>
<GSTCLASS/>
<ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
<LEDGERFROMITEM>No</LEDGERFROMITEM>
<REMOVEZEROENTRIES>No</REMOVEZEROENTRIES>
<ISPARTYLEDGER>Yes</ISPARTYLEDGER>
<ISLASTDEEMEDPOSITIVE>No</ISLASTDEEMEDPOSITIVE>
<BANKALLOCATIONS.LIST></BANKALLOCATIONS.LIST>
<BILLALLOCATIONS.LIST></BILLALLOCATIONS.LIST>
<INTERESTCOLLECTION.LIST></INTERESTCOLLECTION.LIST>
<OLDAUDITENTRIES.LIST></OLDAUDITENTRIES.LIST>
<ACCOUNTAUDITENTRIES.LIST></ACCOUNTAUDITENTRIES.LIST>
<AUDITENTRIES.LIST></AUDITENTRIES.LIST>
<TAXBILLALLOCATIONS.LIST></TAXBILLALLOCATIONS.LIST>
<TAXOBJECTALLOCATIONS.LIST></TAXOBJECTALLOCATIONS.LIST>
<TDSEXPENSEALLOCATIONS.LIST></TDSEXPENSEALLOCATIONS.LIST>
<VATSTATUTORYDETAILS.LIST></VATSTATUTORYDETAILS.LIST>
<COSTTRACKALLOCATIONS.LIST></COSTTRACKALLOCATIONS.LIST>
</ALLLEDGERENTRIES.LIST>
<ALLLEDGERENTRIES.LIST>
<OLDAUDITENTRYIDS.LIST TYPE="Number">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<LEDGERNAME>Bank of Maharashtra</LEDGERNAME>
<GSTCLASS/>
<ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
<LEDGERFROMITEM>No</LEDGERFROMITEM>
<REMOVEZEROENTRIES>No</REMOVEZEROENTRIES>
<ISPARTYLEDGER>Yes</ISPARTYLEDGER>
<ISLASTDEEMEDPOSITIVE>Yes</ISLASTDEEMEDPOSITIVE>
<AMOUNT>-200000.00</AMOUNT>
<BANKALLOCATIONS.LIST>
<DATE>20130401</DATE>
<INSTRUMENTDATE>20130401</INSTRUMENTDATE>
<BANKBRANCHNAME>Warje</BANKBRANCHNAME>
<TRANSACTIONTYPE>Cheque/DD</TRANSACTIONTYPE>
<BANKNAME>AXIS</BANKNAME>
<PAYMENTFAVOURING>'.$name.'</PAYMENTFAVOURING>
<INSTRUMENTNUMBER>50026</INSTRUMENTNUMBER>
<UNIQUEREFERENCENUMBER>38ROUrdV00QEKOhl</UNIQUEREFERENCENUMBER>
<STATUS>No</STATUS>
<CHEQUEPRINTED>-1</CHEQUEPRINTED>
<AMOUNT>-200000.00</AMOUNT>
</BANKALLOCATIONS.LIST>
<BILLALLOCATIONS.LIST></BILLALLOCATIONS.LIST>
<INTERESTCOLLECTION.LIST></INTERESTCOLLECTION.LIST>
<OLDAUDITENTRIES.LIST></OLDAUDITENTRIES.LIST>
<ACCOUNTAUDITENTRIES.LIST></ACCOUNTAUDITENTRIES.LIST>
<AUDITENTRIES.LIST></AUDITENTRIES.LIST>
<TAXBILLALLOCATIONS.LIST></TAXBILLALLOCATIONS.LIST>
<TAXOBJECTALLOCATIONS.LIST></TAXOBJECTALLOCATIONS.LIST>
<TDSEXPENSEALLOCATIONS.LIST></TDSEXPENSEALLOCATIONS.LIST>
<VATSTATUTORYDETAILS.LIST> </VATSTATUTORYDETAILS.LIST>
<COSTTRACKALLOCATIONS.LIST> </COSTTRACKALLOCATIONS.LIST>
</ALLLEDGERENTRIES.LIST>
<ATTDRECORDS.LIST> </ATTDRECORDS.LIST>
</VOUCHER>
</TALLYMESSAGE>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<COMPANY>
<REMOTECMPINFO.LIST MERGE="Yes">
<NAME>12</NAME>
<REMOTECMPNAME>SAVH</REMOTECMPNAME>
<REMOTECMPSTATE>Maharashtra</REMOTECMPSTATE>
</REMOTECMPINFO.LIST>
<REMOTECMPINFO.LIST MERGE="Yes">
<NAME>f6c10ce3-4a15-42b8-961e-143a512a9e62</NAME>
<REMOTECMPNAME>SAVH</REMOTECMPNAME>
<REMOTECMPSTATE>Maharashtra</REMOTECMPSTATE>
</REMOTECMPINFO.LIST>
</COMPANY>
</TALLYMESSAGE>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<COMPANY>
<REMOTECMPINFO.LIST MERGE="Yes">
<NAME>12</NAME>
<REMOTECMPNAME>SAVH</REMOTECMPNAME>
<REMOTECMPSTATE>Maharashtra</REMOTECMPSTATE>
</REMOTECMPINFO.LIST>
<REMOTECMPINFO.LIST MERGE="Yes">
<NAME>f6c10ce3-4a15-42b8-961e-143a512a9e62</NAME>
<REMOTECMPNAME>SAVH</REMOTECMPNAME>
<REMOTECMPSTATE>Maharashtra</REMOTECMPSTATE>
</REMOTECMPINFO.LIST>
</COMPANY>
</TALLYMESSAGE>
</REQUESTDATA>
</IMPORTDATA>
</BODY>
</ENVELOPE>';
/* Actual code for importing goes here */
$server = 'http://localhost:9000';
$headers = array( "Content-type: text/xml" ,"Content-length: ".strlen($requestXML) ,"Connection: close" );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch))
{
print curl_error($ch);
echo " something went wrong..... try later";
}
else
{
echo " request accepted";
print $data;
curl_close($ch);
}
}
?>
Try this, it will be working....
give your port in "$server" which is in tally configuration....

<?php
if(count($_POST)) {
$group_name = strtoupper($_POST['group_name']);
$item_name = $_POST['item_name'];
/*$opening_balance = $_POST['opening_balance'];
$opening_value = $_POST['opening_value'];
$opening_rate = $opening_value * $opening_balance;*/
$res_str =<<<XML
<ENVELOPE>
<HEADER>
<TALLYREQUEST>Import Data</TALLYREQUEST>
</HEADER>
<BODY>
<IMPORTDATA>
<REQUESTDESC>
<REPORTNAME>All Masters</REPORTNAME>
</REQUESTDESC>
<REQUESTDATA>
<!-- Create Stock Group named "$group_name" -->
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<STOCKGROUP NAME="{$group_name}" ACTION="Create">
<NAME.LIST>
<NAME>{$group_name}</NAME>
</NAME.LIST>
<PARENT/>
<ISADDABLE>Yes</ISADDABLE>
</STOCKGROUP>
</TALLYMESSAGE>
<!-- Create Stock Item named "$item_name" -->
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<STOCKITEM NAME="{$item_name}" ACTION="Create">
<NAME.LIST>
<NAME>{$item_name}</NAME>
</NAME.LIST>
<PARENT>{$group_name}</PARENT>
<BATCHALLOCATIONS.LIST>
<NAME>Primary Batch</NAME>
<BATCHNAME>Primary Batch</BATCHNAME>
<GODOWNNAME>Main Location</GODOWNNAME>
<MFDON>20190120</MFDON>
<OPENINGBALANCE>0.000 NOS</OPENINGBALANCE>
<OPENINGVALUE>0.000</OPENINGVALUE>
<OPENINGRATE>0.000/NOS</OPENINGRATE>
</BATCHALLOCATIONS.LIST>
</STOCKITEM>
</TALLYMESSAGE>
</REQUESTDATA>
</IMPORTDATA>
</BODY>
</ENVELOPE>
XML;
//var_dump($res_str);die;
$url = "http://localhost:8000/";
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $res_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
if(curl_errno($ch)){
var_dump($data);
} else {
$msg = $data;
}
curl_close($ch);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Tally</title>
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3" style="margin-top:20px">
<?php if(isset($msg) && $msg) :?>
<div class="alert alert-success" role="alert"><?=$msg?></div>
<?php endif;?>
<div class="pull-left">Item List | </div>
<div class="pull-left">Create StockGroup Item | </div>
<div class="pull-left">Create Ledger | </div>
<hr>
<form class="form-horizontal" method="post" action="">
<div class="form-group">
<label for="group-name" class="col-sm-4 control-label">Stock Group name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="group-name" placeholder="Stock Group name" name="group_name">
</div>
</div>
<div class="form-group">
<label for="item-name" class="col-sm-4 control-label">Stock Item name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="item-name" placeholder="Stock Item name" name="item_name" required>
</div>
</div>
<!-- <div class="form-group">
<label for="opening_balance" class="col-sm-4 control-label">Quantity</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="opening_balance" placeholder="Item Quantity" name="opening_balance" required>
</div>
</div>
<div class="form-group">
<label for="opening_value" class="col-sm-4 control-label">Unit Price</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="opening_value" placeholder="Item Unit Price" name="opening_value" required>
</div>
</div> -->
<div class="form-group">
<div class="col-sm-offset-4 col-sm-6">
<button type="submit" class="btn btn-primary">Insert</button>
</div>
</div>
</form>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

Related

Android/IOS push notification from PHP adding emoji's

I have a class in php that sends push notification to android/IOS users of the app through web. Now I need to add emoji's to title/body of the push notification payload, but no luck doing so.
I've already tried convert encoding to UTF-8, I've tried using this library and I've tried replacing \\ to \ (json_encode function adds \\ instead of \ on e.g \xC2\xA9 becomes \\xC2\\xA9).
Here's my code :
public function sendPush($payload)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->base_url . "/push");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-AUTH-TOKEN: 94h4f5RCDSEYKYqXDHTk';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
That's push function, and here's the .tpl where I get the data from web.
<?php
include(SITE_ROOT . '/core/admin/logo.class.php');
if (isset($_POST['push-button'])) {
if (
isset($_POST['push-title'])
&& isset($_POST['push-body'])
&& isset($_POST['push-city'])
&& isset($_POST['push-url'])
&& isset($_POST['push-platform'])
) {
$push = new Push();
$title = $_POST['push-title'];
$body = $_POST['push-body'];
$url = $_POST['push-url'];
$platform = $_POST['push-platform'];
$cities = $_POST['push-city'];
$payload = [
'title' => $title,
'body' => $body,
'url' => $url,
'cities' => [
$cities
]
];
if ($platform === 'all') {
$responses_ios = json_decode($push->sendPush($payload), true);
$responses_android = json_decode($push->sendPushAndroid($payload), true);
} elseif ($platform === 'ios') {
$responses_ios = json_decode($push->sendPush($payload), true);
} elseif ($platform === 'android') {
$responses_android = json_decode($push->sendPushAndroid($payload), true);
}
// $devices = '';
// var_dump($responses);
// foreach ($responses_ios as $response) {
// $devices .= $response . "<br>";
// }
$message = '<span class="message"><strong>PUSH-notiser har skickats</strong></span>';
unset($_SESSION['message']);
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PUSH - Administration</title>
<?php include(SITE_ROOT . '/views/admin/meta.tpl'); ?>
</head>
<body class="page-admin">
<?php include(SITE_ROOT . '/views/admin/header.tpl'); ?>
<?php include(SITE_ROOT . '/views/admin/navigation.tpl'); ?>
<p class="shoutout p-45 text-center">Skicka PUSH-meddelanden till användare i en stad</p>
<?php echo $message; ?>
<section class="wrapper">
<section class="container centered">
<section class="col-3-5">
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<section class="row">
<span class="input-title">Välj stad</span>
<span class="input-field">
<select name="push-city">
<option value="all">Alla</option>
<?php
$cities = $app->get_page_list('city');
foreach ($cities as $city) {
echo '<option value=' . $city['page_name'] . ' />' . $city['page_name'] . '</option>';
}
?>
</select>
</span>
</section>
<section class="row">
<span class="input-title">Titel</span>
<span class="input-field">
<input type="text" name="push-title" class="slug" placeholder="Titel på meddelande"
required/>
</span>
</section>
<section class="row">
<span class="input-title">Meddelande</span>
<span class="input-field">
<textarea name="push-body" class="slug" placeholder="Meddelande" required></textarea>
</span>
</section>
<section class="row">
<span class="input-title">URL</span>
<span class="input-field">
<input type="text" name="push-url" class="slug" placeholder="URL att skicka med" required/>
</span>
</section>
<section class="row">
<span class="input-title">Plattform</span>
<span class="input-field">
<input type="radio" name="push-platform" class="slug"
placeholder="Välj plattform att skicka till"
value="all" checked required/>Alla
<input type="radio" name="push-platform" class="slug"
placeholder="Välj plattform att skicka till"
value="ios" required/>iOS
<input type="radio" name="push-platform" class="slug"
placeholder="Välj plattform att skicka till"
value="android" required/>Android
</span>
</section>
<section class="row" style="margin-top: 2rem;">
<input type="submit" class="button-large-2 button-no-g" name="push-button"
value="Skicka PUSH-notis"/>
</section>
</form>
</section>
</section>
</section>
<?php include(SITE_ROOT . '/views/admin/emoji.tpl'); ?>
<?php include(SITE_ROOT . '/views/admin/footer.tpl'); ?>
</body>
</html>
Here's what I get from echo/var_dump on title/body
string(13) "test \xC2\xA9" string(13) "test \xC2\xA9"
Those 2 \xC2\xA9 should be copyright signs.

execute php function on click in html 204 returneed

I'm trying to post the html form data below to hubspot but when i have it deployed to either heroku or aws elastic beanstalk I receive 204 back instead of my data being posted to the crm. I used the solution found here how to execute php function on html button click
but have had no success getting the information needed into hubspot.
html file
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'index.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<div class="row">
<div class="row">
<div class="col-lg-12 form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
class="form-control"
name="email"
required
pattern="'^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$'"
>
</div>
<div class="row moveRight">
<div class="col-lg-12 form-group">
<label for="firstname">First Name</label>
<input
type="text"
id="firstname"
class="form-control"
name="firstname"
required
>
</div>
</div>
<div class="row moveRight">
<div class="col-lg-12 form-group">
<label for="lastname">Last Name</label>
<input
type="text"
id="lastname"
class="form-control"
name="lastname"
required
>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<button onclick="myAjax()" class="btn btn-success" id="startnode" type="submit">Submit</button>
</div>
</div>
</div>
</div>
</form>
<?php include 'index.php';?>
</body>
</html>
php file
<?php
function bb() {
//Process a new form submission in HubSpot in order to create a new Contact.
$hubspotutk = $_COOKIE['hubspotutk']; //grab the cookie from the visitors browser.
$ip_addr = $_SERVER['REMOTE_ADDR']; //IP address too.
$hs_context = array(
'hutk' => $hubspotutk,
'ipAddress' => $ip_addr,
'pageUrl' => 'http://www.example.com/form-page',
'pageName' => 'Example Title'
);
$hs_context_json = json_encode($hs_context);
//Need to populate these variable with values from the form.
$str_post = "firstname=" . urlencode($firstname)
. "&lastname=" . urlencode($lastname)
. "&email=" . urlencode($email)
. "&hs_context=" . urlencode($hs_context_json); //Leave this one be
//replace the values in this URL with your portal ID and your form GUID
$endpoint = 'https://forms.hubspot.com/uploads/form/v2/hubid/guid';
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $str_post);
#curl_setopt($ch, CURLOPT_URL, $endpoint);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = #curl_exec($ch); //Log the response from HubSpot as needed.
$status_code = #curl_getinfo($ch, CURLINFO_HTTP_CODE); //Log the response status code
#curl_close($ch);
echo $status_code . " " . $response;
}
bb();
?>

Getting error “Trying to get property of non-object in C:\xampp\htdocs\registration.php on line 111” while executing Mysql command [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 1 year ago.
Here is my code. Don't know why getting this problem. Will really appreciate any help. The error says: “Trying to get property of non-object in C:\xampp\htdocs\registration.php on line 111” I am trying to create an account at registration page and also enabling reCaptcha.
<?php
require_once('includes/settings.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>FirstAide</title>
<link rel="stylesheet" type="text/css" href="css files/loginAndRegistration.css">
<link rel="stylesheet" href="css files/sweetalert.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form method="POST" onsubmit="return validate()" /><!--validations for form fields entered js file- validation-v12.js-->
</head>
<body>
<center>
<div>
<h1 class="text">First Aide</h1>
<hr id="line">
<h2 class="text">A Confidentiality Safety Resource for Peace Corps Volunteers</h2>
</div>
<!--form fields for registration-->
<div class="div-reg">
<table class="tables">
<tr>
<th class="text">Username:</th>
<td><input class="input-box" type="text" id="uname" name="uname" placeholder="Enter your username" required/></td>
</tr>
<tr>
<th class="text" style="vertical-align: top">Password:</th>
<td>
<input class="input-box" type="password" id="password" name="password" required/>
<div id="password-validation">
<meter max="4" id="password-strength-meter"></meter>
<p id="password-strength-text" class="text">Password Strength: Very Weak</p>
<ul id="suggestion">
<li>at least one upper case letter</li>
<li>at least one number</li>
<li>at least one special character</li>
<li>minimum 6 characters long</li>
</ul>
</div>
</td>
</tr>
<tr>
<th class="text" style="vertical-align: top">Confirm Password:</th>
<td>
<input class="input-box" type="password" id="confirmpassword" name="confirmpassword" required/>
</td>
<tr>
<th class="text">Host Country:</th>
<td><select id = "host_country" name = "host_country" required></select></td>
</tr>
<tr>
<th class="text">Email:</th>
<td><input class="input-box" type="text" id="email" name="email" placeholder="Enter your email address" required /></td>
</tr>
</table>
<div class="g-recaptcha" data-sitekey="<?php echo $_settings['reCaptcha']['client_key']?>"></div>
</div>
<!--submit button-->
<div class="div-reg">
<input class="button" type="submit" value="Create Account">
<br><br>
<p class="text">Already have an account?&nbspSign in</p><br><br>
<img src="images/secure.png" style="width: 20px; height: 20px;"/>
<div class="text">This is a secure portal</div>
</div>
</center>
<script src="javascripts/passwordStrengthChecker.js"></script>
<script type="text/javascript" src="javascripts/validation-v12.js"></script>
<script src="javascripts/sweetalert.min.js"></script>
<script src="javascripts/sweetalert.js"></script>
<script src="javascripts/jquery-1.12.4.min.js"></script>
<script>
$.getJSON("javascripts/country.json", function(json) {
var countryElement = $("#host_country");
$.each(json,function(index, value){
var countryOption = '<option value="' + value + '">'+ value + '</option>';
if(value == 'Uganda') {
countryOption = '<option value="' + value + '" selected>'+ value + '</option>';
}
countryElement.append(countryOption);
});
});</script>
</body>
</html>
<?php
if(!isset($_SESSION))
session_start();
if(isset($_SESSION['email']))
{
header("location: welcome.php");
}
require 'dbconnect.php';
if(isset($_POST['email'])&&isset($_POST['uname'])&&isset($_POST['password'])&&isset($_POST['host_country'])&&!empty($_POST['email'])&&!empty($_POST['uname']))
{
$reCaptchaUrl = 'https://www.google.com/recaptcha/api/siteverify';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $reCaptchaUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "secret=".$_settings['reCaptcha']['server_key']."&response=".$_POST['g-recaptcha-response']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
$reCaptchaResponse = json_decode($server_output);
**if(!$reCaptchaResponse->success)**
{
echo "<script type='text/javascript'>salert('Oops','Captcha not verified','error');</script>";
}
else
{
$sql="CALL dupemail('$_POST[email]')";
$result = mysqli_query($connection,$sql);
$connection -> next_result(); //used when there are multiple procedure calls, use after ecah procedure call
if(mysqli_num_rows($result)>=1) //check if it is a duplicate email
{
echo "<script type='text/javascript'>salert('Oops','User with this email already exists','error');</script>";
}
else
{
$email = $_POST['email'];
$password = $_POST['password'];
$password = md5($email.$password);
$newUser="CALL registration('$_POST[email]','$_POST[uname]','$password','$_POST[host_country]')"; //inserts into the user table
if(mysqli_query($connection,$newUser))
{//if successfully added user then add comrades of user with null phone numbers
$connection->next_result();
for($i=1;$i<=6;$i++)
{
$addcomrade = "CALL addcomrade($i,'$email')";//adds comrades into comrade table
mysqli_query($connection,$addcomrade);
$connection->next_result();
}
echo "<script>salert('Success','Registered Successfully','success');
setTimeout(function () {
window.location.href = 'login.php';},2000);
</script>";
}
else
echo "<script type='text/javascript'>salert('Oops','Error in adding user','error');</script>";
}
mysqli_close($connection);
}
}
?>
There are many errors in your code as follows:-
If statement in line 108 is surrounded with ** **.
alert in echo statement(line 110) is preceded by a "s"
You have forgot to add brackets to your if statement at the starting of the php code. Corrected code:-
<?php
if(!isset($_SESSION)){
session_start();}
if(isset($_SESSION['email']))
{
header("location: welcome.php");
}
require 'dbconnect.php';
if(isset($_POST['email'])&&isset($_POST['uname'])&&isset($_POST['password'])&&isset($_POST['host_country'])&&!empty($_POST['email'])&&!empty($_POST['uname']))
{
$reCaptchaUrl = 'https://www.google.com/recaptcha/api/siteverify';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $reCaptchaUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "secret=".$_settings['reCaptcha']['server_key']."&response=".$_POST['g-recaptcha-response']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
$reCaptchaResponse = json_decode($server_output);
**if(!$reCaptchaResponse->success)**
{
echo "<script type='text/javascript'>salert('Oops','Captcha not verified','error');</script>";
}
else
{
$sql="CALL dupemail('$_POST[email]')";
$result = mysqli_query($connection,$sql);
$connection -> next_result(); //used when there are multiple procedure calls, use after ecah procedure call
if(mysqli_num_rows($result)>=1) //check if it is a duplicate email
{
echo "<script type='text/javascript'>salert('Oops','User with this email already exists','error');</script>";
}
else
{
$email = $_POST['email'];
$password = $_POST['password'];
$password = md5($email.$password);
$newUser="CALL registration('$_POST[email]','$_POST[uname]','$password','$_POST[host_country]')"; //inserts into the user table
if(mysqli_query($connection,$newUser))
{//if successfully added user then add comrades of user with null phone numbers
$connection->next_result();
for($i=1;$i<=6;$i++)
{
$addcomrade = "CALL addcomrade($i,'$email')";//adds comrades into comrade table
mysqli_query($connection,$addcomrade);
$connection->next_result();
}
echo "<script>salert('Success','Registered Successfully','success');
setTimeout(function () {
window.location.href = 'login.php';},2000);
</script>";
}
else
echo "<script type='text/javascript'>salert('Oops','Error in adding user','error');</script>";
}
mysqli_close($connection);
}
}
?>

How to get a response from a web service with php and cURL

I am trying to connect to a web service with cURL and PHP. This is my code, along with the form for the user input.:
<?php
if (isset($_POST['submit'])) {
date_default_timezone_set('Europe/Sofia');
$hotelID = 1;
$userName = 'admin';
$password = 'admin';
$url = 'http://serviceurl.com/someservice/freerooms.svc';
$requestTime = date('d.m.Y H:m:s');
$tempFromDate = date_create($_POST['fromDate']);
$tempToDate = date_create($_POST['toDate']);
$fromDate = date_format($tempFromDate, 'd.m.Y H:m:s' );
$toDate = date_format($tempToDate, 'd.m.Y H:m:s' );
$data = array(
'fromDate' => $fromDate,
'toDate' => $toDate,
'hotelID' => $hotelID,
'requestTime' => $requestTime,
'userName' => $userName,
);
$token = md5(md5($password . $requestTime));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
echo $token . '<br>';
echo curl_setopt($ch, CURLOPT_HTTPHEADER, array('Bearer: ' . $token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
$response = curl_exec($ch);
if (!$response) {
$error = curl_error($ch);
}
curl_close($ch);
$result = json_decode($response,true);
print_r($result);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Site</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div id="wrapper" class="col-md-10 col-md-offset-1" style="position: absolute; top: 40%; left: 20%;">
<div id="form-messages">
<?php
if(isset($error)) {
echo '<b>Error: </b>' . $error;
} else {
$error = null;
}
?>
</div>
<form action="" method="post" class="form-inline" id="form">
<div class="form-group">
<input type="date" name="fromDate" required>
</div>
<div class="form-group">
<input type="date" name="toDate" required>
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
</body>
</html>
Problem is, I don't have access to the service from the back end. All the person that maintains it has told me, is the format of the data that should be submitted, and that the response will be in JSON format. This is for hotel room reservation. I am told that I should submit the data in the headers along with the token. When I submit this code, I get an empty response, with an error, stating that the token is INVALID. It's the first time I've been working with cURL and RESTful services, so any help is welcome.

Problems sending data to PHP with Curl

I need some advice with this curl script. I am trying to send values from the FORM to the curl script, but seems that the curl script doesn`t receive the info.
Here is the script:
<?php
if($_SERVER['REQUEST_METHOD'] != 'POST') {
$self = $_SERVER['PHP_SELF'];
?>
<form method="post" action="<?php echo $self; ?>" class="form-horizontal">
<fieldset>
<legend>SMS Contact</legend>
<div class="control-group">
<label for="basic" class="control-label">Name and Surname</label>
<div class="controls">
<input type="text" name="name" id="name" disabled class='input-square' value="<?php print $contactname;?> <?php print $contactsurname;?>">
</div>
</div>
<div class="control-group">
<label for="basic" class="control-label">Mobile No</label>
<div class="controls">
<input type="text" name="mobile" id="mobile" disabled class='input-square' value="<?php echo urlencode($contactmobile);?>">
</div>
</div>
<div class="control-group">
<label for="textcounter" class="control-label" id="textcounter">Textarea</label>
<div class="controls">
<textarea name="textcounter" id="textcounter" class='input-square span9 counter' data-max="160" rows='6'></textarea>
</div>
</div>
<div class="form-actions">
<button class="btn btn-primary" type="submit">Send SMS</button>
</div>
</fieldset>
</form>
<?php
} else {
$mobile = $_POST['mobile'];
$text = $_POST['textcounter'];
$username = 'xxxx';
$password = 'xxxx';
// Set Timezone
date_default_timezone_set('Africa/Johannesburg');
$date = date("m/d/y G.i:s", time());
// Create Unique ID
$code = md5(time());
$newid = $code.$clientid;
$sql="INSERT INTO sent_itmes (sent_id, sent_message, sent_date, sent_quantity, client_id, sent_mobile)VALUES('$newid', '$text', '$date', '1', '$clientid', '$mobile')";
$result=mysql_query($sql);
$url = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0"; // URL to calc.cgi
$fields = array(
'site'=>'',
'username'=>($username),
'password'=>($password),
'message'=>urlencode($text),
'msisdn'=>urlencode($mobile)
);
$fields_string="?";
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
ob_start();
curl_exec($ch);
ob_end_clean();
echo '<div class="alert alert-block alert-success">
<a class="close" data-dismiss="alert" href="#">×</a>
<h4 class="alert-heading">Success!</h4>
Your message has been Sent!
</div><br/><br/>Search Contact';
//close connection
curl_close($ch);
}
?>
When submitting the form, I get the error from response server "No recipients specified", so this means that the form value "mobile" doesnt pass though the value to the curl.
Help please, going off my mind.
Try adding a header that describes the content you post and maybe content you apply
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/x-www-form-urlencoded',
'Accept: text/html',
'Expect: ',
) );
use this for sending data
//open connection
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,POSTVARS.$fields_string); // this line is edited..
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
//execute post
ob_start();
curl_exec($ch);
your order was wrong...
more info http://www.askapache.com/php/sending-post-form-data-php-curl.html
When you submit form with disabled field, that field do not sent:
<input type="text" name="mobile" id="mobile" disabled class='input-square' value="<?php echo urlencode($contactmobile);?>">
If you want to send "mobile", you should add hidden field for it. And maybe replace disabled field name

Categories