jQuery AJAX post only finds first line of mult line textbox - php

I've got a POST form on WordPress that I'm using to pass data to MailChimp via its API.
In and of itself (i.e. not using jQuery), it works as expected. However, when instead of using the form's action to navigate to a new page I try to pass the data via an AJAX post action, it only finds the first row of the multi line text box.
FORM
<?php
// Template Name: MailChimp Form
get_header();
?>
<form id="mailchimp_actions" method="post" action="/ajax-curl-actions/">
<select name="action" id="action">
<option>Subscribe</option>
<option>Unsubscribe</option>
<option>Find</option>
</select>
<textarea name="import_data" id="import_data" placeholder="Email Address,First Name,Last Name"></textarea>
<input type="submit">
</form>
<?php get_footer(); ?>
PAGE THAT PROCESSES THE $_POST DATA
<?php
// Template: AJAX - cURL actions.
###############################################################################
# #
# Available options: #
# #
# Add New Subscriber - Create a new subscriber and add them to a list. #
# Subscribe - Add an existing email to the specified list. #
# Unsubscribe - Completely unsubscribe an email from all mailers. #
# Update - Change subscriber information. #
# #
###############################################################################
$subscribers = bfm_data_format($_POST);
$final_report = array('successes'=>0,'failures'=>array());
foreach($subscribers as $subscriber) :
$post_data = array('email' => $subscriber[0], 'fname' => $subscriber[1], 'lname' => $subscriber[2]);
$action = $_POST['action'];
if(!bfm_subscriber_exists($subscriber[0]) && $action=='Subscribe') $action = 'Add New Subscriber';
$report = bfm_curl_actions(bfm_list_id(),bfm_api_key(),$post_data,$action);
if($report['success']) :
$final_report['successes']++;
else:
$final_report['failures'][] = $report['error'];
endif;
endforeach;
?>
FUNCTIONS
// Format data
function bfm_data_format($data) {
$import_data = $data['import_data'];
$import_data_lines = explode("\n",$import_data);
$i=0;
foreach($import_data_lines as $import_data_line) :
$import_data_lines[$i] = explode(',',$import_data_line);
$i++;
endforeach;
return $import_data_lines;
}
// MailChimp data manipulation
function bfm_curl_actions($list_id,$api_key,$post_data,$action) {
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $post_data['email'],
'merge_fields' => array(
'FNAME' => $post_data['fname'],
'LNAME' => $post_data['lname'],
)
);
if($action == 'Subscribe' || $action == 'Add New Subscriber') :
$data['status']='subscribed';
elseif($action == 'Unsubscribe'):
$data['status']='unsubscribed';
endif;
$member_id = md5($post_data['email']);
$json_data = json_encode($data);
$ch = curl_init();
$curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/";
if($action!='Add New Subscriber') $curlopt_url.=$member_id; // Member ID needs to be excluded if adding an entirely new person.
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
if($action == 'Subscribe' || $action == 'Unsubscribe' || $action == 'Update') :
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
endif;
if($action == 'Find'):
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
endif;
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
$status = "undefined";
$msg = "";
$myArray = json_decode($result, true);
foreach($myArray as $key => $value)
{
if( $key == "status" )
{
$status=$value;
}
else if ($key == "title")
{
$msg=$value;
}
}
$email = $post_data['email'];
if($action == 'Subscribe' || $action == 'Add New Subscriber'):
if($status == "subscribed") :
$report = array ('success'=>true,'error'=>'');
else:
$report = array('success'=>false,'error'=>array('email'=>$email,'message'=>$msg));
endif;
endif;
return $report;
}
function bfm_subscriber_exists($email) {
$api_key = bfm_api_key();
$list_id = bfm_list_id();
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $email,
);
$member_id = md5($email);
$json_data = json_encode($data);
$ch = curl_init();
$curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/$member_id";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = json_decode(curl_exec($ch),true);
if ($result['status']=='404') return false;
return true;
die(' '); // Free up memory.
}
This, as is, works as expected. The second page imports the data from the first into MailChimp.
However, if I try to do the same via AJAX by using the following jQuery, it still imports into MailChimp, but only the first line of the multi line text box is included; all other lines are ignored.
$(document).on("submit","#mailchimp_actions",
function(event) {
event.preventDefault();
var bfm_action = $('#action').val();
var bfm_import = encodeURIComponent($('#import_data').val());
console.log(bfm_action);
console.log(bfm_import);
$.post("/ajax-curl-actions/",
{
import_data: bfm_import,
action: bfm_action,
},
function () {
alert("Successful import.");
}
);
}
);
What am I missing? How do I get it to recognise all the lines in the textbox?

It seems the problem is caused by double-escaping your variables: Once by you and then again by jQuery when you send the key-value pairs as an object.
If you send key-value pairs to any of jQuery's ajax methods, jQuery takes care of the escaping for you so you can remove encodeURIComponent:
$(document).on("submit","#mailchimp_actions",
function(event) {
event.preventDefault();
var bfm_action = $('#action').val();
var bfm_import = $('#import_data').val();
^^^^^^^^^^^^^^^^^^^^^^^ here
console.log(bfm_action);
console.log(bfm_import);
...

Please try by changing this lines of code
function bfm_data_format($data) {
$import_data = nl2br(urldecode($data['import_data']));
$import_data_lines = explode("\n", $import_data);
$i = 0;
foreach ($import_data_lines as $import_data_line) :
$import_data_lines[$i] = explode(',', $import_data_line);
$i++;
endforeach;
return $import_data_lines;
}

Related

Translation On Telegram Bot

if (strpos($message, "/translate") === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
file_get_contents($apiURL."/sendmessage?chat_id=".$chatID."&text=Hasil translate: ".$word." : $mymemori ");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_string);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if(($html = curl_exec($ch)) === false) {
echo 'Curl error: ' . curl_error($ch);
die('111');
}
}
Hello guys i was trying to make translation bot on telegram using php but the output is still error or no output at all. Am using this API https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|id
Please help how to get the translation
Error output IMAGES
First, I suggest using cURL, Not file_get_contents.
Second, No need to echo anything, Because the URL will be visited by webhook, Not a human.
Third, You need a method to send requests to Telegram Bot API.
Use this new code:
define('Token', '<your_bot_token>');
# Reading the update from Telegram
$update = json_decode(file_get_contents('php://input'));
$message = $update->message;
$text = $message->text;
if (strpos($text, '/translate') === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
//
Bot('sendMessage', [
'chat_id' => $update->message->chat->id,
'text' => "Hasil translate: $word : $mymemori "
]);
}
function Bot(string $method, array $params = [])
{
$ch = curl_init();
$api_url = 'https://api.telegram.org/bot' . Token . "/$method";
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
if ($result->ok == false)
{
throw new Exception($result->description, $result->error_code);
}
return $result->result;
}

How to use AZURE face recognition Rest API?

I am using Face API with curl in PHP. But I am having issue when matching images.
I am able to generate faceId's but when matching I get different results than expected. I have two images belonges to same person but API indicates that these images are different. But when using Microsoft demo to compare images I get right result.
Here is microsoft demo link:
https://azure.microsoft.com/en-in/services/cognitive-services/face/#demo
Here are My images url
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
Here is my code
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$headers = ["Ocp-Apim-Subscription-Key: ********* ","Content-Type:application/json" ];
/* Getting faceId */
foreach($images as $data)
{
/* First step is to detect face */
$request_url='https://nexever.cognitiveservices.azure.com/face/v1.0/detect?detectionModel=detection_03&returnFaceId=true&returnFaceLandmarks=false';
/* Image to get faceid */
$detect = array('url' => $data);
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($detect)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl);
$curlErrno = curl_errno($curl);
if ($curlErrno) { $curlError = curl_error($curl);throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl);
$strResponse = json_decode($strResponse , true);
print_r($strResponse);
array_push($faceid , $strResponse[0]['faceId']);
}
// comparing by face ID
/* Match face url */
$request_url = 'https://nexever.cognitiveservices.azure.com/face/v1.0/verify';
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($match)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl); $curlErrno = curl_errno($curl);
if ($curlErrno) {$curlError = curl_error($curl); throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return json_decode($strResponse, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
I have successfully got face id but unable to match. If I try some other images of same person it matches sometimes. The problem is result is not accurate.
but on microsoft demo it is working fine.
Pls try to use specify request param: recognitionModel=recognition_04 when you detect faces as official doc recommanded:
I modified your code as below, it works for me perfectly:
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$faceAPIName = "nexever";
$apikey = "<your api key>";
$faceidAPIHost = "https://$faceAPIName.cognitiveservices.azure.com";
foreach($images as $data)
{
$detect = array('url' => $data);
$result = do_post("$faceidAPIHost/face/v1.0/detect?recognitionModel=recognition_04&detectionModel=detection_03",json_encode($detect),$apikey);
array_push($faceid , $result[0]['faceId']);
}
$request_url = "$faceidAPIHost/face/v1.0/verify";
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
return do_post($request_url,json_encode($match),$apikey);
}
function do_post($url, $params,$key) {
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\nOcp-Apim-Subscription-Key: $key",
'method' => 'POST',
'content' => $params
)
);
$result = file_get_contents($url, false, stream_context_create($options));
return json_decode($result, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
Result of your code:

pushcrew - send notification with PHP curl

This is the code:
$title = 'Du hast neue Nachricht';
$message = 'Besuch meine Website';
$url = 'https://www.bla.com';
$subscriberId = 'xxx51a002dec08a1690fcbe6e';
$apiToken = 'xxxe0b282d9c886456de0e294ad';
$curlUrl = 'https://pushcrew.com/api/v1/send/individual/';
//set POST variables
$fields = array(
'title' => $title,
'message' => $message,
'url' => $url,
'subscriber_id' => $subscriberId
);
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
if($resultArray['status'] == 'success') {
echo $resultArray['request_id']; //ID of Notification Request
}
else if($resultArray['status'] == 'failure')
{
echo 'fail';
}
else
{
echo 'dono';
}
echo '<pre>';
var_dump($result);
echo '</pre>';
And I get:
dono
string(36) "{"message":"You are not authorized"}"
And nothing in the console and no other errors. The apitoken is 100% correct. What could be the trouble here? Do I have to wait till pushcrew decide to allow my website or something?
Ignore this: I must add some more text to ask this question..
There is typo here:
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
Correct is with
CURLOPT_HTTPHEADER
(without the S)

SugarCRM Use REST API With Custom Module

I created a custom module in SugarCRM (V7.8 I think, hosted, not on premise)
The module is named "Customers", and is for testing purposes - I made the structure the same as "Accounts".
I'm using the example on this page: http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.6/API/Web_Services/Examples/v10/module_POST/
When I run the code for the Accounts module it works. When I try to POST a record to the Customers module I get:
[error] => no_method
[error_message] => Could not find a route with 1 elements
My understanding is that the APIs are supposed to work for custom modules, is this incorrect? My ultimate goal is to create 5 or 6 custom modules and push data into them from our ERP system in real time via the REST APIs.
Here's the example code:
<?php
$base_url = "https://my.domain/rest/v10";
$username = "admin";
$password = "*********";
function call($url,$oauthtoken='',$type='GET',$arguments=array(),$encodeData=true,$returnHeaders=false){
$type = strtoupper($type);
if ($type == 'GET')
{
$url .= "?" . http_build_query($arguments);
}
$curl_request = curl_init($url);
if ($type == 'POST')
{
curl_setopt($curl_request, CURLOPT_POST, 1);
}
elseif ($type == 'PUT')
{
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "PUT");
}
elseif ($type == 'DELETE')
{
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "DELETE");
}
curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($curl_request, CURLOPT_HEADER, $returnHeaders);
curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);
if (!empty($oauthtoken))
{
$token = array("oauth-token: {$oauthtoken}","Content-Type: application/json");
curl_setopt($curl_request, CURLOPT_HTTPHEADER, $token);
}
if (!empty($arguments) && $type !== 'GET')
{
if ($encodeData)
{
//encode the arguments as JSON
$arguments = json_encode($arguments);
}
curl_setopt($curl_request, CURLOPT_POSTFIELDS, $arguments);
}
$result = curl_exec($curl_request);
if ($returnHeaders)
{
//set headers from response
list($headers, $content) = explode("\r\n\r\n", $result ,2);
foreach (explode("\r\n",$headers) as $header)
{
header($header);
}
//return the nonheader data
return trim($content);
}
curl_close($curl_request);
//decode the response from JSON
$response = json_decode($result);
return $response;
}
//Login - POST /oauth2/token
$url = $base_url . "/oauth2/token";
$oauth2_token_arguments = array(
"grant_type" => "password",
//client id/secret you created in Admin > OAuth Keys
"client_id" => "sugar",
"client_secret" => "",
"username" => $username,
"password" => $password,
"platform" => "base"
);
$oauth2_token_response = call($url, '', 'POST', $oauth2_token_arguments);
//Create record - POST /<module>/
$url = $base_url . "/Customers"; //works id this is "Accounts"
$record_arguments = array(
"name" => "ACME Inc.",
"description" => "Not for Coyotes"
);
$record_response = call($url, $oauth2_token_response->access_token, 'POST', $record_arguments);
echo "<pre>";
print_r($record_response);
echo "</pre>";
Custom modules will have a prefix key to avoid conflicts, so rather than $url = $base_url . "/Customers"; it will be something like $base_url . "/xxx_Customers";.
If you developed the module, you should know the prefix key used, otherwise check the DB schema or Studio/Module Builder
Ensure your prefix to the module, also check your endpoint method by hitting this URL for required API method and parameter: yourdomain/rest/v10/help.

curl_exec to Mailchimp doesn't work when using AJAX

I've created a form in Wordpress that posts data to Mailchimp using the Mailchimp API. If I use just a regular form, with an action that goes to the appropriate page, it works fine; all the data imports as expected.
However, I want to do it via an AJAX POST command. I'm sending all the same information as when doing it using a traditional posted form, but it doesn't work. The AJAX success condition triggers to show that the page loaded successfully, so there must be something in that page that isn't working.
Here's my form:
<div class="card full">
<form id="mailchimp_actions" method="post" action="/ajax-curl-actions/">
<select name="action" id="action">
<option>Subscribe</option>
<option>Unsubscribe</option>
<option>Find</option>
</select>
<textarea name="import_data" id="import_data" placeholder="Email Address,First Name,Last Name"></textarea>
<input type="submit">
</form>
</div>
Here's the page it posts to:
<?php
// Template Name: AJAX - cURL actions.
$subscribers = bfm_data_format($_POST);
$final_report = array('successes'=>0,'failures'=>array());
foreach($subscribers as $subscriber) :
$post_data = array('email' => $subscriber[0], 'fname' => $subscriber[1], 'lname' => $subscriber[2]);
$action = $_POST['action'];
if(!bfm_subscriber_exists($subscriber[0]) && $action=='Subscribe') $action = 'Add New Subscriber';
$report = bfm_curl_actions(bfm_list_id(),bfm_api_key(),$post_data,$action);
if($report['success']) :
$final_report['successes']++;
else:
$final_report['failures'][] = $report['error'];
endif;
endforeach;
?>
<h1>Import Completed</h1>
<p><?=$final_report['successes']?> records were imported successfully.</p>
<h2>Failed imports</h2>
<table>
<tr>
<th>Email</th>
<th>Reason</th>
</tr>
<?php foreach($final_report['failures'] as $failure): ?>
<tr>
<td><?=$failure['email']?></td>
<td><?=$failure['message']?></td>
</tr>
<?php endforeach; ?>
</table>
Here are the various functions that make it work:
<?php
function bfm_fudge_timeout(){
$wpmetetxt = "
# WP Maximum Execution Time Exceeded
<IfModule mod_php5.c>
php_value max_execution_time 10000
</IfModule>";
$htaccess = ABSPATH .'/.htaccess';
$contents = #file_get_contents($htaccess);
if(!strpos($htaccess,$wpmetetxt))
file_put_contents($htaccess,$contents.$wpmetetxt);
}
add_action("after_switch_theme", "bfm_fudge_timeout");
// Format data
function bfm_data_format($data) {
$import_data = $data['import_data'];
$import_data_lines = explode("\n",$import_data);
$i=0;
foreach($import_data_lines as $import_data_line) :
$import_data_lines[$i] = explode(',',$import_data_line);
$i++;
endforeach;
return $import_data_lines;
}
// MailChimp data manipulation
function bfm_curl_actions($list_id,$api_key,$post_data,$action) {
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $post_data['email'],
'merge_fields' => array(
'FNAME' => $post_data['fname'],
'LNAME' => $post_data['lname'],
)
);
if($action == 'Subscribe' || $action == 'Add New Subscriber') :
$data['status']='subscribed';
elseif($action == 'Unsubscribe'):
$data['status']='unsubscribed';
endif;
$member_id = md5($post_data['email']);
$json_data = json_encode($data);
$ch = curl_init();
$curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/";
if($action!='Add New Subscriber') $curlopt_url.=$member_id; // Member ID needs to be excluded if adding an entirely new person.
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
if($action == 'Subscribe' || $action == 'Unsubscribe' || $action == 'Update') :
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
endif;
if($action == 'Find'):
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
endif;
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
$status = "undefined";
$msg = "";
$myArray = json_decode($result, true);
foreach($myArray as $key => $value)
{
if( $key == "status" )
{
$status=$value;
}
else if ($key == "title")
{
$msg=$value;
}
}
$email = $post_data['email'];
if($action == 'Subscribe' || $action == 'Add New Subscriber'):
if($status == "subscribed") :
$report = array ('success'=>true,'error'=>'');
else:
$report = array ('success'=>false,'error'=>array('email'=>$email,'message'=>$msg));
endif;
endif;
return $report;
}
function bfm_subscriber_exists($email) {
$api_key = bfm_api_key();
$list_id = bfm_list_id();
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $email,
);
$member_id = md5($email);
$json_data = json_encode($data);
$ch = curl_init();
$curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/$member_id";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = json_decode(curl_exec($ch),true);
if ($result['status']=='404') return false;
return true;
die(' '); // Free up memory.
}
?>
All of the above works. Here's the jQuery I'm trying to use to do the same but via AJAX, and it fails.
// MailChimp Functions
$(document).on("submit","#mailchimp_actions",
function(event) {
event.preventDefault();
var import_data = $('#action').val();
var action = $('#import_data').val();
$.post("/ajax-curl-actions/",
{
import_data: import_data,
action: action
},
function () {
alert("All done!");
}
);
}
);
Solved it! I'd transposed the two variables in the AJAX request:
var import_data = $('#action').val();
var action = $('#import_data').val();
should have been:
var import_data = $('#import_data').val();
var action = $('#action').val();

Categories