I want to make an API request using a simple wp plugin I created by submitting a form and the form will submit to action.php
<?php
/** * Plugin Name: Taofeeq Wodpress Plugin demo
* Plugin URI: #
* Description: Display content using a shortcode to insert in a page or post
* Version: 0.1
* Text Domain: tbare-wordpress-plugin-demo
* Author: Taofeeq Tajudeen
* Author URI: #
*/
function tt_wordpress_plugin_demo($atts) {
?>
<form id="ct" method="POST">
<label for="source">Source:</label>
<input type="txt" name="source" required>
<label for="target">Target:</label>
<input type="text" name="target" id= "trg" required>
<input type="submit" value="Submit">
</form>
<?php
}
add_shortcode('tt-plugin-demo', 'tt_wordpress_plugin_demo');
action.php
`<?php
if (isset($_post['submit'])){
$source = $_post['source'];
$target = $_post['target'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.apyhub.com/data/convert/currency',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"source":$source,
"target":$target
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'apy-token: my_api_token'
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
What I need assistance with is submitting the form without reloading the page where I insert the form shortcode. Also how to submit it to action.php since the file is in a plugin? Maybe you guys can assist me in a way that instead of submitting to action.php, it will submit to the same page where i will insert the action.php codes and action.php will no longer be needed.
I tried adding everything on the same page and after submission, the page will reload and return nothing.
I tried submitting it to action.php, it says page not found.
I tried submitting it to
action="<?php echo esc_attr(admin_url( 'admin-post.php' ) ); ?>"
but it brought me to the admin login page and after logging in it displays nothing.
Lastly, I don't know how to submit without reloading the page.
Related
I'm trying to implement Google Invisible Recaptcha on a website online after the domain registration on google recaptcha site, I followed the documentation, but not works. When send the form, show the alert error:
Cannot contact reCAPTCHA. Check your connection and try again.
This is my code (only the interesting points), HTML/JS:
<script src='https://www.google.com/recaptcha/api.js?
onload=onloadCallback&render=explicit&hl=it' async defer></script>
</head>
<body>
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset>
<input name="email" type="text" id="email" required/>
<input type="submit" class="submit" id="submit" value="Contact!" />
</fieldset>
</form>
<script type="text/javascript">
var onSubmit = function(token) {
// ajax call
};
var onloadCallback = function() {
grecaptcha.render('submit', {
'sitekey' : 'PUBLIC_KEY',
'callback' : onSubmit
});
};
</script>
and the contact.php file:
class Captcha
{
private $key = 'PRIVATE_KEY';
public $goo;
public function verify()
{
$postData = http_build_query(
array(
'secret' => $this->key,
'response' => $this->goo,
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$options = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postData
)
);
$context = stream_context_create($options);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
return json_decode($response);
}
}
$captcha = new Captcha();
$captcha->goo = $_POST['g-recaptcha-response'];
$response = $captcha->verify();
if (!$response->success) {
// not works
}
else {
// works
}
I don't understand what is incorrect.
Thanks for help!
I've been trying to figure this out for days with no luck.
I'm trying to implement Stripe Payments Checkout into my website. The payment amount is on the payments page as a JS variable. I was able to get Basic Checkout working, but apparently that can't use a custom amount, or send any data to the PHP processing page (email, and some order attributes). I've been trying to use the Custom Checkout but I can't figure it out. Any help?
So far I have this in config.php:
<?php
require_once('vendor/autoload.php');
$stripe = array(
"secret_key" => "MY SECRET KEY IS HERE",
"publishable_key" => "MY PUBLISHED KEY IS HERE"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
?>
and this is in a file called process.php:
<?php
require_once('./config.php');
$token = $_POST['stripeToken'];
$input = $_POST["totalprice"];
$customer = \Stripe\Customer::create(array(
'email' => 'customer#example.com',
'source' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $input,
'currency' => 'usd'
));
echo $input;
?>
And in the initial PHP file I have:
<?php require_once('./config.php'); ?>
<form action="process.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="MY PUBLIC TEST KEY IS HERE"
data-amount= amt * 100
data-name="Test Name"
data-description="Widget"
data-image="/img/logo.jpg"
data-locale="auto"
>
<form type=hidden name="totalprice" value=amt*100 action="process.php" method="POST">
</script>
</form>
With that said though, I've had a bunch of other code I've tried before that hasn't worked, so this current code probably should be scrapped. I'd really appreciate any help I can get!
Well, following is the sample code of Custom Integration.
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Purchase</button>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Stripe.com',
description: '2 widgets',
zipCode: true,
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
The source code is given on this page
So is that what you are looking for?
After user clicks on submit form, I need to call Zend validation of that form without refreshing whole page. I also use zend_Layout in my website. I have seen a lot of tutorials here, but still cant make it working.
Index Controller:
class IndexController extends Zend_Controller_Action {
public function init() {
}
public function indexAction() {
$this->view->static_data = "eg. ABCDEFG";
$this->view->form = new Application_Form_Test();
}
public function ajaxAction() {
// probably some code to hande ajax
}
}
View for index/index:
...
<?php
echo date('m/d/Y h:i:s a', time());
echo $this->static_data;
?>
<hr />
<?php echo $this->form ?>
...
Form:
class Application_Form_Test extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAttrib('class', 'form1');
$this->addElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
)
));
$this->addElement('text', 'name', array(
'label' => 'Your name:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(3, 20))
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Send',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}
So how can i validate form without refreshing rest of that page and see Zend Error Messages in case that form is not valid.
You can post the form to your Ajax action where you will instantiate the form and inject data from the request.
$form = new Form();
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
//save data
....
}
}
$this->view->form = $form;
You have two options:
Render the form in the view and respond with HTML. Using JavaScript replace current form with HTML returned by the Ajax request.
Get error messages using Zend_Form::getMessages() and respond with JSON.
$this-view->messages = $form->getMessages();
I have created a view with tabs and each tab has a form with ajax submit and gridview. I am using renderpartial in tabs widget to render the form and gridview and after clicking submit it filters the gridview. Everything looks fine within the tab till I click the submit button. After clicking submit it filters the gridview as expected.. but it does not load the bootstrap javascript and css so the layout is totally messed up and the tabs and menu bar all appears as a list and the page keeps on loading.
Anyone know why is it not loading the required scripts and css which I have preload in main config. Do I have to specify something seperately when calling ajax function from a view.
EDIT: Code Added
Code for tabs widget(producers.php)
<?php $this->widget(
'bootstrap.widgets.TbTabs',
array(
'type' => 'tabs',
'tabs' => array(
array('label' => 'Monthly' ,'id' => 'tab1',
'content' => $this->renderPartial('_prod_monthly',array('dataProvider' => $dataProvider,'dataProvider2' => $dataProvider2 ,'dataProvider3' => $dataProvider3, 'opm' => $opm, 'month' => $month),true,true),
'active' => true),
array('label' => 'Weekly' ,'id' => 'tab2',
'content' => $this->renderPartial('_prod_weekly',array('dataProvider4' => $dataProvider4,'dataProvider5' => $dataProvider5 ,'dataProvider3' => $dataProvider3, 'opm' => $opm, 'week' => $week),true,true)),
array('label' => 'Daily', 'id' => 'tab3', 'content' => 'ABC' )),
)); ?>
Code for partial view (_prod_monthly.php):
$form = $this->beginWidget(
'bootstrap.widgets.TbActiveForm',array(
'id' => 'form_monthly',
'enableAjaxValidation'=>true,
'type' => 'inline',
'method' => 'get',
'htmlOptions' => array('class' => 'well','onsubmit'=>"return false;",/* Disable normal form submit */
'onkeypress'=>" if(event.keyCode == 13){ send2(); } " /* Do ajax call when user presses enter key */),)); ?>
Select Month:
<?php echo CHtml::dropDownList('month', $month,
$sel_month); ?>
Select Employee:
<?php echo CHtml::dropDownList('opm', $opm,
$sel_opm); ?>
<?php $this->widget('bootstrap.widgets.TbButton',
array(
'buttonType'=>'button',
'label'=>'Submit',
'type' =>'primary',
'htmlOptions'=> array('onclick' => 'send2()'),)
);
$this->endWidget();
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'sortableRows'=>true,
'afterSortableUpdate' => 'js:function(id, position){ console.log("id: "+id+", position:"+position);}',
'type'=>'striped bordered hover',
'dataProvider'=>$dataProvider,
'type'=>'striped bordered responsive',
'template' => "{summary}\n{items}\n{extendedSummary}\n{exportButtons}"));?>
<script type="text/javascript">
function send2()
{
var data=$("#form_monthly").serialize();
$.ajax({
type: 'GET',
url: '<?php echo Yii::app()->createAbsoluteUrl("op/producers"); ?>',
data:data,
success:function(data){
document.write(data);
},
error: function(data) { // if error occured
alert("Error occured.please try again");
alert(data);
},
dataType:'html'});
}
</script>
Thanks.
There is no Yii based solution for handling UI-Widgets with AJAX right now and will never come.
Probably, this will never happen again in Yii2. The main Problem is about your missing JS-Ressources and Binding (as you know already). Yii will generate those codes (which you are missing) within the layout process, which is not called on "AJAX"-Requests. Don't try to put in your JS-Ressources by yourself. Yii generated JS-Cods are realy tricky ... and not that easy to handle manualy. This will come up with a lot of problems.
My solution: I dont use any of the "UI"-Features included in Yii. They come along with a lot of problems (Ajax, Multiple announces, etc.). Its not hard to write that features yourself or using jQueryUI.
Take a look at the Tab feature and try write it yourself .. and be happy ! :)
Experimenting with JsHelper in CakePHP 2.0, I got a Request method to update the value of a form field with the results of an AJAX call - so far, so good. However, on inspecting the form field it says:
<input type="hidden" id="JobsPartUnitcost" name="data[JobsPart][unitcost]">5.55</input>
but when I copied it and first pasted it above it said
<input type="hidden" id="JobsPartUnitcost" name="data[JobsPart][unitcost]"></input>
and when I submitted the form the value was empty. Why is the browser showing the value but the underlying DOM not registering it?
Using Mac/Safari, CakePHP 2.0, JQuery
EDIT
As requested here is form data dump
Array ( [JobsPart] => Array ( [job_id] => 1 [company_id] => 4 [part_id] => 2 [qty] => 3 [unitcost] => ) )
and here is AJAX code
$this->Js->get('#JobsPartPartId')->event('change',
$this->Js->request(
array(
'controller'=>'JobsParts',
'action'=>'getPart'
),
array(
'update'=>'#JobsPartUnitcost',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => false,
'inline' => true
))
)
)
);
You need to set the value attribute:
<input type="hidden" value="YOUR VALUE HERE" name="data[Etc][field]" />
You don't wrap a value in input tags.
OK. I have found a workaround and no one else seems to have found a direct solution.
In my static view I now have just <td id="part"></td> where the input field was. My Ajax call now updates '#part' and my dynamic view (the one called by the controller ajax action) now outputs the whole field - <?php echo $this->Form->input('unitcost', array('type' => 'text', 'value' => $part['Part']['costamount'])); ?>. Ugly but it works.
$this->Js->get('#JobsPartPartId')->event('change',
$this->Js->request(
array(
'controller'=>'JobsParts',
'action'=>'getPart'
),
array(
'success'=>'$("#JobsPartUnitcost").val(data)',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => false,
'inline' => true
))
)
)
);