I need to integrate the mail chimp api with core php I tried more type of codes but not working. Finally, I found the below code. I have created an api key with mailchimp, likewise campaigns, template and list in the mailchimp.
<script src="jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#subscribe').submit(function() {
if (!valid_email_address($("#email").val()))
{
$(".message").html('The email address you entered was invalid. Please make sure you enter a valid email address to subscribe.');
}
else
{
$(".message").html("<span style='color:green;'>Adding your email address...</span>");
$.ajax({
url: 'subscribe.php',
data: $('#subscribe').serialize(),
type: 'POST',
success: function(msg) {
if(msg=="success")
{
$("#email").val("");
$(".message").html('<span style="color:green;">You have successfully subscribed to our mailing list.</span>');
}
else
{
$(".message").html('The email address you entered was invalid. Please make sure you enter a valid email address to subscribe.');
}
}
});
}
return false;
});
});
function valid_email_address(email)
{
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
return pattern.test(email);
}
</script>
<?php
$api_key = "key";
$list_id = "id";
require('inc/MAPI.class.php');
$Mailchimp = #new Mailchimp( $api_key );
echo bool($Mailchimp);
//$Mailchimp_Lists = #new Mailchimp_Lists( $Mailchimp );
//$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => htmlentities($_POST['email']) ) );
if ( ! empty( $subscriber['leid'] ) ) {
echo "success";
}
else
{
echo "fail";
}
?>
<div class="message"></div>
<form role="form" method="post" id="subscribe">
<input type="email" id="email" name="email" placeholder="you#yourself.com" value="">
<button type="submit">SUBSCRIBE</button>
</form>
This is my code, but it's not returning, errors only. Please help me.
Related
I have the invisible reCAPTCHA set up, but it doesn't seem to want to call my callback function. My form looks like:
<form id='ContactAgentForm' name='ContactAgentForm' class='custom-form-widget-form standard_form' action='contact_agent' listing_id=1233445>
...
<div class='field captcha-field recaptcha_field' >
<div id='g-recaptcha-div' class="g-recaptcha" ></div>
</div>
...
<div class="field button-field">
<button class="button button-primary"><span>Send</span></button>
<a class="button button-cancel btn-close" href="#cancel"><span>Cancel</span></a>
</div>
</form>
In the javascript, I want to handle the fact that there might be multiple forms on the page, so I create a list of all the forms. For each form, I attach/render the reCAPTCHA logic, attaching my callback with the form passed as a parameter:
<script>
var $form_list = jQuery("form.custom-form-widget-form");
var onFormPageSubmit = function(token, $form ) {
console.log("Got here! ", token );
var field = $form.find('.g-recaptcha-response')[0];
field.value = token;
$form[0].submit();
};
var onloadCallback = function() {
$form_list.each( function() {
var $form = jQuery(this);
var $recaptcha = $form.find( ".g-recaptcha" );
if ( $recaptcha.length )
{
var recaptchaId = grecaptcha.render($recaptcha[0], {
'callback': function (token) { onFormPageSubmit(token, $form); },
'sitekey': "{$captcha_config.invisible_captcha_site_key}",
'size': 'invisible',
'badge': 'inline'
});
$form.data("recaptchaid", recaptchaId);
}
});
};
</script>
And just below that, I load the recaptcha/api.js file:
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onloadCallback"></script>
With some judicial 'console.log' statements, we get through all of the code EXCEPT for the callback (onFormPageSubmit). The "protected by reCAPTCHA" logo is there, but it seems that the form is just submitted, ignoring the reCAPTCHA call altogether.
All help appreciated.
Somewhere along the line, the validation function for the form was lost (it's in another file). The validation function was attached to the button, and it executed something like this:
$submit_button.on( 'click', function( event ) {
event.preventDefault();
// get the recaptchaid from form data
var $recaptcha_id = $form.data( "recaptchaid" );
if ( $recaptcha_id != undefined )
{
grecaptcha.execute($recaptcha_id);
}
} );
The "grecaptcha.execute" is the important thing - this is what triggers the actual reCAPTCHA call.
When i submit it with no data, it shows like this. but i want it to show on my modal, because i'm using the form_validation library.
enter image description here
This is my Controller:
$this->form_validation->set_rules('category_name','Category name','trim|required');
if($this->form_validation->run() == FALSE){
echo validation_errors();
} else{
$category = array(
"category_name" => $this->input->post('category_name')
);
$this->category_m->insert($category);
echo "Successfully Added.";
}
This is my ajax file:
$(document).on('submit', '#form' ,function(event){
event.preventDefault();
var form = $(this).serialize();
$.ajax({
url:"<?php echo base_url(); ?>category/operation",
type:"POST",
data:form,
success:function(data){
$('#form')[0].reset();
$('#mymodal').modal('hide');
$('#alert').fadeIn().html('<div class="alert alert-info">'+data+'</div>').fadeOut(5000);
table.ajax.reload();
}
})
});
This is not related to Codeigniter. It's JS/jQuery/HTML/...
Assuming that you have something like this in your HTML
<div id="mymodal">...</div>
Create another div#alert inside
<div id="alert">...</div>
And change the Javascript to something like
//You don't neet fadeIn/fadeOut
$('#alert').html('<div class="alert alert-info">'+data+'</div>');
$('#mymodal').modal('show');
I am using the post method in a php script as:
<form method="post" enctype="multipart/form-data" action="file1.php">
after submitting the form it runs the file1.php which takes 20-30 minutes to finish and the page hangs over here. I want to redirect this page to another page file2.php and the file1.php should be run in background without exiting it.
Please suggest me any way to redirect it. I have tried using header('Location: file2.php'); in file1.php but it redirects only after completing the file1.php.
form.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<style>
#console {
width: 100%;
height: 500px;
overflow: auto;
border: 1px solid #4E4E4E;
}
</style>
</head>
<body>
<form id="myForm">
FirstName:
<input type="text" name="firstName">
<br> Second Name:
<input type="text" name="lastName">
<br> Phone No.:
<input type="text" name="phoneNumber">
<br>
</form>
<button id="submitMyForm">submit the form!</button>
<br>
<!-- JUST SOME FEEDBACK TO LET US KNOW WHAT IS SENT -->
<h1>SENT: <span></span></h1>
<div id="console"></div>
<script>
// on click of the button submit form and run php on process.php
$("#submitMyForm").on("click", function() {
// get data from the form and serialize it.
var dataFromForm = $('#myForm').serialize();
// -------------------------------------------
// for your information:
// this is the format of what we are sending over
// -------------------------------------------
$("h1 span").append(dataFromForm + "<br>");
// -------------------------------------------
$.ajax({
type: "POST",
data: dataFromForm,
url: "process.php",
success: function(data) {
// -------------------------------------------
// for your information:
// just show what we got back from the server
// -------------------------------------------
$("#console").append("SUCCESS: " + data + "<br>");
// -------------------------------------------
},
error: function(data) {
// if it does not work do whatever you want.
console.log("ERROR");
console.log(data);
}
});
// ------------------------------------------------
// ADD THIS TO REDIRECT TO WHEREVER
window.location.replace("http://stackoverflow.com");
// ------------------------------------------------
});
</script>
</body>
</html>
process.php
<?php
// ------------------------------------------------------------------------
// Do whatever you want here for the script.
// It will start running and allow you to continue doing whatever on the form page
// you dont need to echo out anything. It is just to show its running the script
// ------------------------------------------------------------------------
echo "
STARTING SCRIPT: USING VARIABLES SENT FORM DATA<br>
first name: " . $_POST['firstName'] . " <br>
last name: " . $_POST['lastName'] . " <br>
phone number: " . $_POST['phoneNumber'] . " <br>
";
?>
I used this helper static method with success for many years.
<?php
namespace Libraries;
class Helper
{
public static function redirect($location = null, $ignoreAbort = true)
{
header('Connection: close');
ob_start();
header('Content-Length: 0');
header('Location: ' . $location);
ob_end_flush();
flush();
if ($ignoreAbort) {
ignore_user_abort(true);
}
}
}
This is how to use it.
<?php
namespace Controllers;
class OrderController{
public function orderCompleted()
{
// If you need to send a message after redirect.
$_SESSION["order_completed"] = "Order completed";
// don't forget to unset the session after the message is seen.
// Redirect should be put before the long duration script
Helper::redirect('https://www.your-url.com/page);
// Run in background
// 1. Send emails
// 2. Generate PDFs
// 3. etc...
}
}
Note:
You also need to check the PHP settings (php.ini)
Some installs do not have output_buffering on, some have 4096, some default to Off
# output_buffering = Off
# Use
output_buffering = 4096
# Or unlimited, but use with caution
output_buffering = On
You can try the curl if you want to execute the php code in background.
A simple example with parameters:
<?php
$url = 'http://yoursite.com/yourbackground-code.php';
$fields = array(
'param1' => "data",
'param2' => "data",
);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//you can var_dump the result after is executed
var_dump($result);
Upon submitting an invalid form via HTTP POST, I expect my Symfony REST service (using FOSRestBundle) to return a 400 Bad Request code. Instead, it is returning 200 OK even though it is returning the errors in JSON format like I want.
Within my entity, I am using
Symfony\Component\Validator\Constraints as Assert;
to ensure no blank entries are given for any of the fields. For example:
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
* #Assert\NotBlank()
*/
private $title;
Here is my controller method:
public function postAvrequestAction(Request $request){
$entity = new AvRequest();
$form = $this->get('form.factory')->createNamed('', new AvRequestType(), $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$serializer = $this->get('serializer');
$serialized = $serializer->serialize($entity, 'json');
return new Response($serialized, 201);
}
return new JsonResponse(array(
'errors' => $this->getFormErrors($form, 400)
));
And here is my HTML form with AJAX code upon submission:
<form id="postform" role="form" method="POST" action="http://localhost:8000/api/avrequests">
Title: <input type="text" name="title" id="title"/>
Request Date: <input type="text" name="requestDate" id="requestDate"/>
Deliver Date: <input type="text" name="deliverDate" id="deliverDate"/>
Return Date: <input type="text" name="returnDate" id="returnDate"/>
<input type="submit" class="button" value="Submit Request" />
</form>
<script>
<!--
$(document).ready(function(){
$('#postform').validate({
debug: true,
rules: {
...
},
messages: {
...
},
submitHandler: function(form){
event.preventDefault();
ajaxObject = {
url: $("#postform").attr("action"),
type: 'POST', // Can be GET, PUT, POST or DELETE only
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({"title":$("#title").val(), "requestDate":$("#requestDate").val(), "deliverDate":$("#deliverDate").val(), "returnDate":$("#returnDate").val()})
};
$.ajax(ajaxObject)
.done(function(data,status,xhr) {
console.log( status );
$(':input','#postform').not(':button, :submit, :reset, :hidden').val('');
$('#postform').hide();
$('#submitmessage').addClass('alert-box success').html('Success! We have received your request and should receive a confirmation email shortly.');
$('#resultsdiv').html('<p><strong>Here is a review of your request:</strong></p><p><strong>Request Date:</strong> ' + data.request_date + '</p><p><strong>Delivery Date:</strong> ' + data.request_date + '</p><p><strong>Return Date:</strong> ' + data.return_date + '</p><p>Submit another request</p>');
})
.fail(function(data,status,xhr) {
console.log( status );
})
.always(function(data,status,xhr) {
console.log( data );
});
}
});
});
-->
</script>
So let's say I sumbit a completely blank form. I'll end up receiving this as a response in the console:
success
{errors: Object}errors: Objectfields: Object
deliverDate: "This value should not be blank."
returnDate: "This value should not be blank."
...
And the code within the success function runs, not the error code.
return new JsonResponse(array(
'errors' => $this->getFormErrors($form)
), 400);
instead of
return new JsonResponse(array(
'errors' => $this->getFormErrors($form, 400)
));
...minor detail...
I am developing a plugin for custom registration form.I have first file customapplicationform.php file , other files in side registration and shortcode folder.
So, My Plugin Directory structure like this :
--->customapplicationform
|--js
|--ajax-registration.js
|--registration
|--registration.php
|--regsubmit.php
|--scripts.php
|--shortcode
|--display.php
|--shortcodes.php
--customapplicatioform.php
It's give error :
Fatal error: Call to undefined function add_action() in E:\xampp\htdocs\aism\wp-content\plugins\customapplicationform\registration\scripts.php on line 17
Please , Tell me what is the problem with this ? and if there any better way than suggest me. Thanks in advance.
1) This is my customapplicationform.php file.
require_once(ABSPATH.'wp-admin/includes/plugin.php');
ob_start();
global $app_db_version;
$app_db_version = '1.0';
function app_install() {
global $wpdb;
global $app_db_version;
$table_name = $wpdb->prefix .'registeration';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
regid mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
fname varchar(50) NOT NULL,
lname varchar(50) NOT NULL,
email varchar(50) NOT NULL,
phno int(12) NOT NULL,
PRIMARY KEY(regid)
) ";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
add_option( 'app_db_version', $app_db_version );
}
register_activation_hook( __FILE__, 'app_install');
include_once('/shortcode/shortcodes.php');
2) This is my shortcodes.php file.
function shortcode_function( $atts ) {
$plugin_dir_path = dirname(__FILE__);
include_once('display.php');
$data = ob_get_clean();
return $data;
}
add_shortcode( 'custom-application', 'shortcode_function' );
3) This is my display.php file.
include_once(''.dirname(dirname(__FILE__)).'/registration/registration.php');
4) This is my registration.php file.
<form action="<?php echo plugins_url();>/customapplicationform/registration/regsubmit.php" method="Post">
<label>First Name:</label>
<input type="text" name="appfname" id="appfname" />
<label>Last Name :</label>
<input type="text" name="applname" id="applname" />
<label>Email :</label>
<input type="email" name="appemail" id="appemail" />
<label>Phone :</label>
<input type="tel" name="appphone" id="appphone" />
<?php// wp_nonce_field('app_new_user','app_new_user_nonce', true, true ); ?>
<input type="Submit" value="Submit" id="btn-new-user">
</form>
5) This is my regsubmit.php file.
require_once('scripts.php');
// Verify nonce
if( ! wp_verify_nonce( $_POST['app_new_user_nonce'], 'app_new_user' ) )
{
die( 'Ooops, something went wrong, please try again later.' );
}
else {
if(isset($_POST['appemail'])) {
// Post values
echo $fname = $_POST['appfname'];
echo $lname = $_POST['applname'];
echo $email = $_POST['appemail'];
echo $phone = $_POST['appphone'];
$userdata = array(
'fname' => $fname,
'lname' => $lname,
'email' => $email,
'phno' => $phone,
);
$user_id = wp_insert_user( $userdata ) ;
// Return
if( !is_wp_error($user_id) ) {
echo '1';
} else {
echo $user_id->get_error_message();
}
}
}
6) This is my scripts.php file .
function app_register_user_scripts() {
// Enqueue script
wp_register_script('app_reg_script', dirname(__FILE__). '/js/ajax- registration.js', array('jquery'), null, false);
wp_enqueue_script('app_reg_script');
wp_localize_script( 'app_reg_script', 'app_reg_vars', array('app_ajax_url' => admin_url( 'admin-ajax.php' )));
}
add_action('wp_enqueue_scripts', 'app_register_user_scripts');
It's a core function and available if your code is activated trough WordPress and accessed trough WordPress. If you try to call your plugin file outside the WordPress scope (for example you approach the file from the browser, directly) then add_action is not available unless you require wp-load.php at the top of your file from the WordPress root.
Since we're calling core functions before $wp->init; we need to include pluggable.php
require_once(ABSPATH .'wp-includes/pluggable.php');