Running PHP API call without Page Reloading - php

I have a multistep form (HTML / JS / PHP) and the form data gets sent to a backend after submitting, which results in a page reload.
Is it possible to pass the data live to the backend when the user gets to a new page of the form (clicks on the next button)?
<?php
require_once dirname(__FILE__) . '/MailWizzApi/Autoloader.php';
MailWizzApi_Autoloader::register();
// configuration object
$config = new MailWizzApi_Config(array(
'apiUrl' => 'http://email.mddasd.de/api/index.php',
'publicKey' => 'SAMPLEKEY',
'privateKey' => 'SAMPLEKEY',
// components
'components' => array(
'cache' => array(
'class' => 'MailWizzApi_Cache_File',
'filesPath' => dirname(__FILE__) . '/MailWizzApi/Cache/data/cache', // make sure it is writable by webserver
)
),
));
// now inject the configuration and we are ready to make api calls
MailWizzApi_Base::setConfig($config);
// start UTC
date_default_timezone_set('UTC');
$email = $_POST ['email'];
$name = $_POST['name'];
$phone = $_POST['telephone'];
if (isset($_POST['branch_0_answers']) && $_POST['branch_0_answers'] != "")
{
foreach($_POST['branch_0_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$grundflaeche .= $_POST['grundflaeche-grundstueck'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
if (isset($_POST['branch_1_answers']) && $_POST['branch_1_answers'] != "")
{
foreach($_POST['branch_1_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$wohnflaeche .= $_POST['wohnflaeche-haus'] . "\n";
$grundflaeche .= $_POST['grundflaeche-haus'] . "\n";
$baujahr .= $_POST['baujahr'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
if (isset($_POST['branch_2_answers']) && $_POST['branch_2_answers'] != "")
{
foreach($_POST['branch_2_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$wohnflaeche .= $_POST['wohnflaeche-wohnung'] . "\n";
$baujahr .= $_POST['baujahr'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
if (isset($_POST['branch_3_answers']) && $_POST['branch_3_answers'] != "")
{
foreach($_POST['branch_3_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$gewerbeflaeche .= $_POST['gewerbeflaeche'] . "\n";
$grundflaeche .= $_POST['grundflaeche-gewerbe'] . "\n";
$baujahr .= $_POST['baujahr'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
foreach($_POST['branch_1_1_answers'] as $value)
{
$stand.= trim(stripslashes($value)) . "\n";
};
$endpoint = new MailWizzApi_Endpoint_ListSubscribers();
$response = $endpoint->create('ma503j6m97b75', array(
'EMAIL' => $email,
'TELEFON' => $phone,
'NAME' => $name,
'ART' => $art,
'GEWERBEFLAECHE' => $gewerbeflaeche,
'WOHNFLAECHE' => $wohnflaeche,
'GRUNDFLAECHE' => $grundflaeche,
'BAUJAHR' => $baujahr,
'PLZ' => $plz,
'STAND' => $stand
));
?>
The .php gets executed with the final submit button.
Thanks for your answers.

Related

codeignigter use rest to pass data to external site

OK in plain PHP I use the following to pass data to a GET
file_get_contents('https://ws.mysite.com/some.svc/here?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');
I now want to apply this same piece of code to my CI project.
This Is how I have tried.
private function getResults()
{
$score = $this->actions->getSentEmailCount();
$percentilescore = $percentile = $this->actions->getPercentile($score);
$testID = '134';
$percentile = $this->actions->getPercentile($score);
$time = $this->input->get('time');
$timemath = 60000;
$timeinmseconds = $time * $timemath;
$adddata = array(
'uniID' => '5',
'testName' => 'some',
'testID' => $testID,
'total' => '10',
'correct' => $score = $this->actions->getScore(),
'percent' => $score = $this->actions->getScore(),
'dateTaken' => date('Y-m-d H:i:s'),
'timeSpent' => $timeinmseconds,
'userID' => $session_id,
);
$this->actions->add_record($adddata);
return $this->load->view('client/results', $data);
file_get_contents('https://ws.mysite.com/123.svc/some?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');
}
It is not posting the data any idea why and how I should do it in CI ?
return should be the last statement in the function because it's immediately ends execution of the current function. Just put file_get_contents before return:
file_get_contents('https://ws.mysite.com/123.svc/some?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');
$this->actions->add_record($adddata);
return $this->load->view('client/results', $data);

Payeezy: How to make "pre-authorize" transaction to "tagged-completion" transaction in php

Payeezy payment gateway has been integrated successfully with php. Kept transaction type as "AUTH_ONLY". To make the complete transaction will go to the admin panel and make it as tagged completion as shown in screen shot.
Now we want to allow the merchant to add the shipping
fee, compute the total from within our application, and then send a
request back to Payeezy with the total amount to be charged against the
transaction tag that was received earlier and complete the previous
pre-authorization as completed.
Here is the link how to achieve it, but unable to understand how to do with php.
Thanks in advance.
With regards,
Sudhir
I got the proper code to do this. Here is the proper code in php and fill all the variables with proper payeezy values.
class SoapClientHMAC extends SoapClient {
public function __doRequest($request, $location, $action, $version, $one_way = NULL) {
global $context;
$hmackey = "********************"; // <-- Insert your HMAC key here
$keyid = "******"; // <-- Insert the Key ID here
$hashtime = date("c");
$hashstr = "POST\ntext/xml; charset=utf-8\n" . sha1($request) . "\n" . $hashtime . "\n" . parse_url($location,PHP_URL_PATH);
$authstr = base64_encode(hash_hmac("sha1",$hashstr,$hmackey,TRUE));
if (version_compare(PHP_VERSION, '5.3.11') == -1) {
ini_set("user_agent", "PHP-SOAP/" . PHP_VERSION . "\r\nAuthorization: GGE4_API " . $keyid . ":" . $authstr . "\r\nx-gge4-date: " . $hashtime . "\r\nx-gge4-content-sha1: " . sha1($request));
}
else {
stream_context_set_option($context,array("http" => array("header" => "aut horization: GGE4_API " . $keyid . ":" . $authstr . "\r\nx-gge4-date: " . $hashtime . "\r\nx-gge4-content-sha1: " . sha1($request))));
}
return parent::__doRequest($request, $location, $action, $version, $one_way);
}
public function SoapClientHMAC($wsdl, $options = NULL) {
global $context;
$context = stream_context_create();
$options['stream_context'] = $context;
return parent::SoapClient($wsdl, $options);
}
}
$trxnProperties = array(
"User_Name" => "*******",
"Secure_AuthResult" => "",
"Ecommerce_Flag" => "",
"XID" => "",
"ExactID" => "******-**", //Payment Gateway
"CAVV" => "",
"Password" => "**********************", //Gateway Password
"CAVV_Algorithm" => "",
"Transaction_Type" => $txn_type, //Transaction Code I.E. Purchase="00" Pre-Authorization="01" etc.
"Reference_No" => "",
"Customer_Ref" => "",
"Reference_3" => "",
"Client_IP" => "", //This value is only used for fraud investigation.
"Client_Email" => "", //This value is only used for fraud investigation.
"Language" => "en", //English="en" French="fr"
"Card_Number" => "4111111111111111", //For Testing, Use Test#s VISA="4111111111111111" MasterCard="5500000000000004" etc.
"Expiry_Date" => "1121", //This value should be in the format MM/YY.
"CardHoldersName" => "test",
"Track1" => "",
"Track2" => "",
"Authorization_Num" => $_POST["auth_no"],
"Transaction_Tag" => $_POST["txn_tag"],
"DollarAmount" => $_POST["amt"] + $_POST["shippingfee"],
"VerificationStr1" => "",
"VerificationStr2" => "",
"CVD_Presence_Ind" => "",
"Secure_AuthRequired" => "",
"Currency" => "",
"PartialRedemption" => "",
// Level 2 fields
"ZipCode" => "",
"Tax1Amount" => "",
"Tax1Number" => "",
"Tax2Amount" => "",
"Tax2Number" => "" );
$client = new SoapClientHMAC("https://api.demo.globalgatewaye4.firstdata.com/transaction/v12/wsdl");
$trxnResult = $client->SendAndCommit($trxnProperties);
if(#$client->fault){
// there was a fault, inform
print "<B>FAULT: Code: {$client->faultcode} <BR />";
print "String: {$client->faultstring} </B>";
$trxnResult["CTR"] = "There was an error while processing. No TRANSACTION DATA IN CTR!";
}
//Uncomment the following commented code to display the full results.
echo "<H3><U>Transaction Properties BEFORE Processing</U></H3>";
echo "<TABLE border='0'>\n";
echo " <TR><TD><B>Property</B></TD><TD><B>Value</B></TD></TR>\n";
foreach($trxnProperties as $key=>$value){
echo " <TR><TD>$key</TD><TD>:$value</TD></TR>\n";
}
echo "</TABLE>\n";
echo "<H3><U>Transaction Properties AFTER Processing</U></H3>";
echo "<TABLE border='0'>\n";
echo " <TR><TD><B>Property</B></TD><TD><B>Value</B></TD></TR>\n";
foreach($trxnResult as $key=>$value){
$value = nl2br($value);
echo " <TR><TD valign='top'>$key</TD><TD>:$value</TD></TR>\n";
}
echo "</TABLE>\n";
// kill object
unset($client);

How can I email myself the RAW SQL query that this php function is producing?

I want to run explain on a query that is slow but I don't know how to view the raw sql so I can run it in phpmyadmin and debug it. Here is the function.
private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
{
$fids = '';
if ($forumIds)
{
$r = '';
if ($fidsReverse)
{
$r = ' NOT ';
}
if (is_array($forumIds))
{
$forumIds = implode(',', $forumIds);
}
$fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds . ')';
}
$tids = '';
if ($topicIds)
{
$tids = ' AND forums_topics.tid IN (' . $topicIds . ')';
}
$mids = '';
if ($membersIds)
{
$mids = ' AND core_attachments.attach_member_id IN (' . $membersIds . ')';
}
$whereT = array();
$joinsT = array();
$findInPosts = ' AND ' . \IPS\Db::i()->findInSet('queued', array('0'));
$joinsT[] = array(
'select' => 'forums_posts.*',
'from' => 'forums_posts',
'where' => array("forums_posts.pid=core_attachments_map.id2" . $findInPosts),
);
$findInTopics = ' AND ' . \IPS\Db::i()->findInSet('approved', array('1'));
$joinsT[] = array(
'select' => 'forums_topics.*',
'from' => 'forums_topics',
'where' => array("forums_topics.tid=forums_posts.topic_id" . $findInTopics . $fids . $tids),
);
$select = 'core_attachments.attach_id AS custom_data, core_attachments.*';
if ($group)
{
$select = 'core_attachments.attach_id AS custom_data, COUNT(attach_is_image) as cnt_images, SUM(attach_hits) as summ_attach_hits, core_attachments.*';
}
$joinsT[] = array(
'select' => $select,
'from' => 'core_attachments',
'where' => array('core_attachments.attach_is_image=1 AND core_attachments.attach_is_archived=0 AND core_attachments.attach_id=core_attachments_map.attachment_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_members.member_id, core_members.member_group_id, core_members.mgroup_others, core_members.name, core_members.members_seo_name',
'from' => 'core_members',
'where' => array('core_attachments.attach_member_id=core_members.member_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_permission_index.perm_id',
'from' => 'core_permission_index',
'where' => array("core_permission_index.app='forums' AND core_permission_index.perm_type='forum' AND core_permission_index.perm_type_id=forums_topics.forum_id"),
);
$groupT = $group;
$whereT[] = array(
"core_attachments_map.location_key='forums_Forums' AND " .
\IPS\Db::i()->findInSet('perm_view', array_merge(array(\IPS\Member::loggedIn()->member_group_id), array_filter(explode(',', \IPS\Member::loggedIn()->mgroup_others)))) . " OR perm_view='*'" .
$fids . $tids . $mids
);
$table = new \IPS\Helpers\Table\Db(
'core_attachments_map',
\IPS\Http\Url::internal('app=core&module=system&controller=nbattachpictures', 'front', 'nbattachpictures'),
$whereT,
$groupT
);
$table->joins = $joinsT;
$table->sortBy = $order;
$table->sortDirection = $sort;
$table->limit = $limit;
$table->rowsTemplate = array(\IPS\Theme::i()->getTemplate('plugins', 'core', 'global'), 'nbAttachmentsBlocksRows');
$table->parsers = array(
'custom_data' => function( $val, $row )
{
return array(
'topic_data' => \IPS\Http\Url::internal("app=forums&module=forums&controller=topic&id={$row['tid']}", 'front', 'forums_topic', array($row['title_seo'])),
'summ_attach_hits' => $row['summ_attach_hits'],
'jewel' => $this->attachJewel($row['summ_attach_hits']),
);
},
);
return $table;
}
Anybody know how I can see the SQL query only that is produced by this function? email is better than echo as I want to grab query from live site.
You could var_dump($table) and write the result in an email using the native php mail function or write it in a log file (this option is better).
Is that framework open-source? Because I couldn't find any documentation about the class \IPS\Helpers\Table\Db. Probably there's a method in it to build the query, you could look for it at that class source code and put the result of that method into the email message or log file instead of var_dump the table.

eBay API SKU missing from response

I am trying to download all my listings from ebay into my database using following code:
$client = new eBaySOAP($session);
$ebay_items_array = array();
try {
$client = new eBaySOAP($session);
$params = array(
'Version' => $Version,
'GranularityLevel' => "Fine",
'OutputSelector' => "ItemID,SKU,Title",
'EndTimeFrom' => date("c", mktime(date("H"), date("i")+10, date("s"), date("n"), date("j"), date("Y"))),
'EndTimeTo' => date("c", mktime(date("H"), date("i"), date("s"), date("n"), date("j")+120, date("Y"))),
'Pagination' => array(
'PageNumber' => $_GET['linkebaynum'],
'EntriesPerPage' => "20"
)
);
$results = $client->GetSellerList($params);
if($results->Ack == "Success")
{
$c = 0;
if(is_array($results->ItemArray->Item))
{
foreach($results->ItemArray->Item as $key => $value)
{
array_push($ebay_items_array, $value->ItemID);
$Qcheck = tep_db_query('select ebay_productstoitems_items_id from ' . TABLE_EBAY_PRODUCTS_TO_ITEMS . ' where ebay_productstoitems_items_id = ' . $value->ItemID);
$check = tep_db_fetch_array($Qcheck);
if($check == 0) {
if($check['ebay_productstoitems_items_id'] = $value->ItemID) {
echo 'Not in Database - Inserting ' . $value->ItemID . '<br>';
tep_db_query("insert ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}else{
echo 'Found - ' . $value->ItemID . ' Nothing to Change<br>';
tep_db_query("update ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "' where ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}
$c++;
}
}
} catch (SOAPFault $f) {
print "error<br>";
}
print "Request:<br>".ebay_formatxmlstring($client->__getLastRequest())."<br><br>";
print "Response:<br>".ebay_formatxmlstring($client->__getLastResponse())."<br><br>";
But it will not recover the SKU (or CustomLabel).
Can anyone explain what I am missing to get the SKU into the database along with the ItemID.
Or would I have to recover lists of ItemID and then do a second call to recover the SKU or CustomLabel?
Found out what the problem was the Sandbox does not appear to pass the SKU back. I switched to the live site and hey presto the SKU is being retrieved along with the Itemid.

Chrome, Opera, Mozilla Content decoding failed

I have a function in php, which lists followers of a user in twitter. When I use chrome to navigate to the page which holds the function, It works, sometimes it doesn't.
Chrome works 3 out of 5 times before it gives "Error 330 (net::ERR_CONTENT_DECODING_FAILED): Unknown error"
Mozilla works 4 out of 5 times before it gives "Content Encoding Error"
Opera shows this
Warning: Invalid argument supplied for foreach() in
C:\wamp\www\ntwyt\core\common\twitter.php on line 1639
�j&x���o��4�a ���h��RA�N����T.&�Km�n� 5ý i�<Т
K���/o4�¨�b�#�Y�����
Here's the code
function theme_followers($feed, $hide_pagination = false) {
$rows = array();
if (count($feed) == 0 || $feed == '[]') return '<p>No users to display.</p>';
foreach ($feed->users->user as $user) {
$name = theme('full_name', $user);
$tweets_per_day = twitter_tweets_per_day($user);
$last_tweet = strtotime($user->status->created_at);
$content = "{$name}<br /><span class='about'>";
if($user->description != "")
$content .= "Bio: " . twitter_parse_tags($user->description) . "<br />";
if($user->location != "")
$content .= "Location: {$user->location}<br />";
$content .= "Info: ";
$content .= pluralise('tweet', $user->statuses_count, true) . ", ";
$content .= pluralise('friend', $user->friends_count, true) . ", ";
$content .= pluralise('follower', $user->followers_count, true) . ", ";
$content .= "~" . pluralise('tweet', $tweets_per_day, true) . " per day<br />";
$content .= "Last tweet: ";
if($user->protected == 'true' && $last_tweet == 0)
$content .= "Private";
else if($last_tweet == 0)
$content .= "Never tweeted";
else
$content .= twitter_date('l jS F Y', $last_tweet);
$content .= "</span>";
$rows[] = array('data' => array(array('data' => theme('avatar', theme_get_avatar($user)), 'class' => 'avatar'),
array('data' => $content, 'class' => 'status shift')),
'class' => 'tweet');
}
$content = theme('table', array(), $rows, array('class' => 'followers'));
if (!$hide_pagination)
$content .= theme('list_pagination', $feed);
return $content;
}
Whats the problem? It works and doesn't work.
I think you want to loop:
foreach ($feed->users as $user) {
....
}

Categories