WordPress callback function is called twice - javascript

i have been developing a WordPress plugin that has a form that sends some data to a Database.
My problem is that every time i click the submit button the callback runs twice, and the information that appears in my database is duplicated.
My jQuery code is:
$("#submit_btn").click( function (event) {
event.preventDefault();
let uuid = uuidv4()
let form_serialize = $("form").serializeArray();
let dataForm = {
"id": uuid,
'submitId': uuid
}
$.each(form_serialize, function (i, field) {
dataForm[field.name] = field.value
});
$.ajax({
url: ccandidates.ajax_url,
type: "POST",
crossDomain: true,
cache: false,
data: {
security: candidates.ajax_nonce,
action: 'SendToFormApi',
data: dataForm
},
dataType: 'json',
success: function (data, status, xhttp) {
// event.preventDefault();
if (data === true) {
window.location = candidates.merci_page_url;
} else {
window.location.href = candidates.error_page_url;
$("form").trigger('reset')
}
},
}
);
});
Callback function
function SendToFormApi_callback()
{
$formRandyValues = $_POST['data'];
$virtualagencyApiEmail = new virtualagencyApiEmail();
$result = $virtualagencyApiEmail->NyFormApi($formRandyValues);
$response = $virtualagencyApiEmail->NyFormApiCall($result,$formMyValues['id']);
$code = wp_remote_retrieve_response_code($response);
// if code 503 == service unavailable
// if code 401 == auth fail
// if code 400 == object fail
// if code 201 == success response
if ($code === 201) {
echo json_encode(true);
wp_die();
} else {
echo json_encode(false);
wp_die();
}
}
add_action('wp_ajax_SendToFormApi', 'SendToFormApi_callback', 1);
add_action('wp_ajax_nopriv_SendToFormApi', 'SendToFormApi_callback', 1);
public function NyFormApi($params): array
{
$uuidId = $params['id'] ?? $this->getUid();
$position_criteria_object = new Position_Criteria();
$position_criteria_object->type = 'string';
$position_criteria_object->label = 'besoin';
$position_criteria_object->question = 'votre_besoin';
$position_criteria_object->answer = $params['votreBesoin'];
$position_criteria_object->value = $params['votreBesoin'];
$origin_object = new Position_Criteria();
$origin_object->type = 'string';
$origin_object->label = 'origin';
$origin_object->question = 'candidature_oringin';
$origin_object->answer = 'My form';
$origin_object->value = 'My form';
$secteur_object = new Position_Criteria();
$secteur_object->type = 'string';
$secteur_object->label = 'secteur';
$secteur_object->question = 'secteur';
$secteur_object->answer = $params['secteur'];
$secteur_object->value = $params['secteur'];
$region_object = new Position_Criteria();
$region_object->type = 'string';
$region_object->label = 'region';
$region_object->question = 'region';
$region_object->answer = $params['region'];
$region_object->value = $params['region'];
$metier_object = new Position_Criteria();
$metier_object->type = 'string';
$metier_object->label = 'metier';
$metier_object->question = 'metier';
$metier_object->answer = $params['metier'];
$metier_object->value = $params['metier'];
$talent_object = new Talent();
$talent_object->id = $uuidId;
$talent_object->firstName = $params['firstName'];
$talent_object->lastName = $params['lastName'];
$talent_object->email = $params['email'];
$talent_object->phone = $params['phone'];
if(empty($params['qualificationCode'])){
$qualificationCode = "none";
} else {
$qualificationCode = $params['qualificationCode'];
}
return array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode($this->keyEncoded)
),
'body' => array(
'id' => $uuidId, //$params['id'], // str
'workTeamId' => $params['postClient'], // str
'priority' => 1, // int
'positionCriteria' => array(
$position_criteria_object,
$origin_object,
$secteur_object,
$region_object,
$metier_object
), // [{...},{...},...]
'occupationCode' => $qualificationCode, // str,
'occupationLabel' => $params['qualification'], // str
'talent' => $talent_object, // { key = value, ... }
)
);
}
public function MyFormApiCall($params, $id)
{
$url = $this->apiPathRandy . "/" . $id;
return wp_remote_post($url, $params);
}
// Get an RFC-4122 compliant globaly unique identifier
private function getUid(): string
{
$data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
After reading and trying some solutions that i found, no of them work in my case.
Thank you for your help.
(note: there are some vars names that were changed for privacy)

I would remove all javascript from the form and do
if ($code === 201) {
header("location: merci.html");
wp_die();
} else {
header("location: erreur.html");
wp_die();
}

Related

How do I submit form without page reload taking into consideration the php script?

So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});

XMLHttpRequest - append php function to .json?add_fields ajax request

I am trying to update someone else's code, which uses a XMLHttpRequest setup to get product information from the server for use on some SilverStripe templates. I want to grab the url() function from Product.php so I can use it to get the url for the Product data object and send it to Google Analytics. However, simply appending it to the existing add_fields data does not work--the url function does not get retrieved.
I'm not very familiar with XMLHttpRequests so I'm kind of clueless as to what to do here.
Here is the JavaScript code that is getting the product data:
document.addEventListener("DOMContentLoaded", function(event) {
var productCatalogService = (function() {
var endpoint = "/api/v1/Product/";
return {
'getProductById': function(id, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', endpoint + id + ".json?add_fields=NutritionalInformationLabelURL,SortOrder,BeautyShotURL,url,Recipe"); //url function is not grabbed
xhr.onload = function() {
if (xhr.status === 200) {
callback && callback(JSON.parse(xhr.responseText));
}
else {
console.error('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
}
};
})();
var utils = (function() {
return {
'removeClass': function(node, className) {
node.className = node.className.replace(className, '');
return node;
},
'addClass': function(node, className) {
node.className = node.className.replace(className, '');
node.className += " " + className;
},
'hasClass': function(node, className) {
return node.className.indexOf(className) >= 0;
}
}
})();
var changeProduct = function(product) {
var name = document.querySelector('.product-name'),
subname = document.querySelector('.product-subname'),
tagline = document.querySelector('.product-tagline'),
description = document.querySelector('.product-description'),
beautyShot = document.querySelector('.beauty-shot'),
nutritionFacts = document.querySelector('.ingredients-list'),
mobileNutritionLabel = document.querySelector('.mobile-nutrition-label img'),
nutritionLabel = document.querySelector('.nutritional-label img'),
recipeName = document.querySelector('.recipe-name'),
recipeDescription = document.querySelector('.recipe-description'),
recipeContainer = document.querySelector('.recipe-container');
name.innerHTML = product.Name;
subname.innerHTML = product.SubName;
description.innerHTML = product.Description;
tagline.innerHTML = product.Tagline;
beautyShot.src = product.BeautyShotURL;
if(product.NutritionalInformationLabelURL){
nutritionLabel.src = product.NutritionalInformationLabelURL;
mobileNutritionLabel.src = product.NutritionalInformationLabelURL;
}
if(product.NutritionFacts){
nutritionFacts.innerHTML = product.NutritionFacts;
if(utils.hasClass(nutritionFacts, 'hidden')) {
utils.removeClass(nutritionFacts, 'hidden');
}
} else {
utils.addClass(nutritionFacts, 'hidden');
}
// var pagePath = product.url();
console.log(product.url); //returns undefined
typeof(ga) !== "undefined" && ga('send', 'pageview', {
'page': location.pathname, //want to use the url() function in Product.php here
'title': product.PageTitle
});
};
NodeList.prototype.forEach = Array.prototype.forEach;
var products = document.querySelectorAll('.carousel-products .product');
products.forEach(function(product) {
product.onclick = function() {
var productId = product.getAttribute('data-product-id');
productCatalogService.getProductById(productId, function(product) {
console.log(product);
changeProduct(product); //add recipe data to be pulled in here (fields are above)
});
};
});
});
Product.php
<?php
class Product extends DataObject implements Pageable, Searchable {
private static $api_access = true;
private static $db = [
'Name' => 'varchar(255)',
'SubName' => 'varchar(255)',
'Tagline' => 'varchar(255)',
'Description' => 'HTMLText',
'WhereToBuy' => 'varchar(500)', // external link
'NutritionFacts' => 'HTMLText',
'PageTitle' => 'varchar(250)',
'MetaKeywords' => 'Text',
'MetaDescription' => 'Text',
'SortOrder' =>'Int'
];
private static $has_one = [
'BeautyShot' => 'Image',
'ThumbImage' => 'Image',
'NutritionalInformationLabel' => 'Image',
'Category' => 'Category',
];
private static $summary_fields = [
'GridThumbnail' => 'Photo',
'Name' => 'Name'
];
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Main', new TextField("Name", "Name"));
$fields->addFieldToTab('Root.Main', new TextField("SubName", "SubName"));
$fields->addFieldToTab('Root.Main', new TextField("Tagline", "Tagline"));
$fields->addFieldToTab("Root.Main", new HtmlEditorField("Description", "Description"));
$fields->addFieldToTab('Root.Main', new TextField("WhereToBuy", "WhereToBuy"));
$fields->addFieldToTab("Root.Main", new HtmlEditorField("NutritionFacts", "NutritionFacts"));
$fields->addFieldToTab("Root.Main", new UploadField("BeautyShot", "BeautyShot"));
$fields->addFieldToTab("Root.Main", new UploadField("ThumbImage", "ThumbImage"));
$fields->addFieldToTab("Root.Main", new UploadField("NutritionalInformationLabel", "NutritionalInformationLabel"));
$fields->addFieldToTab('Root.SEO', new TextField("PageTitle", "PageTitle"));
$fields->addFieldToTab('Root.SEO', new TextareaField("MetaKeywords", "MetaKeywords"));
$fields->addFieldToTab('Root.SEO', new TextareaField("MetaDescription", "MetaDescription"));
$fields->removeByName('SortOrder');
return $fields;
}
public function getGridThumbNail() {
if ($this->BeautyShot()->exists()) {
return $this->BeautyShot()->SetWidth(100);
}
return '(no image)';
}
public function getBeautyShotURL() {
return $this->BeautyShot()->URL;
}
public function getNutritionalInformationLabelURL() {
if ($this->NutritionalInformationLabel()->Exists()) {
return $this->NutritionalInformationLabel()->URL;
} else {
return "";
}
}
public function getCouponImageURL() {
if ($this->CouponImage()->Exists()) {
return $this->CouponImage()->URL;
} else {
return "";
}
}
public function getProductFullName(){
return $this->Name." ".$this->SubName;
}
public function AbsoluteLink() {
return Director::absoluteURL($this->url());
}
private function url() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
// lifted from Artisa
public function MetaTags() {
$tags = "";
$generator = trim(Config::inst()->get('SiteTree', 'meta_generator'));
if (!empty($generator)) {
$tags .= "<meta name=\"generator\" content=\"" . Convert::raw2att($generator) . "\" />\n";
}
$charset = Config::inst()->get('ContentNegotiator', 'encoding');
$tags .= "<meta http-equiv=\"Content-type\" content=\"text/html; charset=$charset\" />\n";
if($this->MetaDescription) {
$tags .= "<meta name=\"description\" content=\"" . Convert::raw2att($this->MetaDescription) . "\" />\n";
}
if($this->MetaKeywords) {
$tags .= "<meta name=\"keywords\" content=\"" . Convert::raw2att($this->MetaKeywords) . "\" />\n";
}
if(Permission::check('CMS_ACCESS_CMSMain')
&& in_array('CMSPreviewable', class_implements($this))
&& !$this instanceof ErrorPage
&& $this->ID > 0
) {
$tags .= "<meta name=\"x-page-id\" content=\"{$this->ID}\" />\n";
$tags .= "<meta name=\"x-cms-edit-link\" content=\"" . $this->CMSEditLink() . "\" />\n";
}
$this->extend('MetaTags', $tags);
return $tags;
}
public function canView($member = null){
return true;
}
public function canEdit($member = null) {
return true;
}
public function canCreate($member = null) {
return true;
}
public function slug()
{
return Utilities::friendlyName($this->Name);
}
public function Link()
{
return $this->url();
}
public function getTitleFields() {
return ['Name', 'SubName'];
}
public function getContentFields() {
return ['Description'];
}
public static function getSearchFilter() {
return [];
}
}
// Handles Products and categories
class ProductCsvBulkImporter extends CsvBulkLoader {
protected function processRecord($record, $columnMap, &$results, $preview = false) {
$categoryName = $record['Main Category'];
$productName = $record['Product ID'];
$productSubName = $record['Product Type'];
$productTagline = $record['Product Label'];
$productDescription = $record['Product Description'];
$productKeywords = $record['Keyphrase'];
$category = Category::get()
->filter(['Name' => $categoryName])
->first();
if (!$category) {
$category = new Category();
$category->Name = $categoryName;
$category->write();
}
$product = Product::get()
->filter(['Name' => $productName])
->first();
if (!$product) {
$product = new Product();
}
$product->PageTitle = sprintf("%s %s", $productName, $productSubName);
$product->Name = $productName;
$product->SubName = $productSubName;
$product->Tagline = $productTagline;
$product->Description = $productDescription;
$product->MetaKeywords = $productKeywords;
$product->CategoryID = $category->ID;
$product->write();
return $product->ID;
}
}
I don't know if the code, as it's setup now, is best practice or not as I didn't make it, so if there are mistakes, I can't tell for sure.
Is there some way to append the url() function from Product.php to the .json?add_fields ajax response?
As you can see in the Product class, the url() method it's private, so you don't have access to it outside that class:
private function url() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
If you change that to:
public function url() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
it'll probably work... That's all I can say based on the code you submitted. You should know, there's probably a reason why that url() method is private - most probably it's only used internally in the Product class.
If it's still not working, try to duplicate that function like this:
public function getUrl() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
...and then in the JS code you can use it like this:
console.log(product.Url);
As you can see, you have calls like this in the JS code: product.BeautyShotURL, but the actual method in the Product class it's called getBeautyShotURL(), so it should work with product.Url (this might also work tough: product.getUrl)

Trigger url after success of order placed in magento

I am using magento 1.8.1 and I am working on sms integration. I am trying to trigger a api url after clicking on placed order button. But as I new on magento I don't know where I put that url. After finding, I get these code of button
<div class="clear"></div>
<button style="float:left" onclick="oscPlaceOrder(this);"
id="onestepcheckout-button-place-order" type="button"
title="<?php echo $this->__('Place Order') ?>"
class="btn-proceed-checkout onestepcheckout-btn-checkout onestepcheckout-place">
<span>
<span><?php echo $this->__('Place order now') ?></span>
</span>
</button>
</div>
now here is one function oscPlaceOrder:
function oscPlaceOrder(element) {
var validator = new Validation('one-step-checkout-form');
var form = $('one-step-checkout-form');
if (validator.validate()) {
if (($('p_method_hosted_pro') && $('p_method_hosted_pro').checked) || ($('p_method_payflow_advanced') && $('p_method_payflow_advanced').checked)) {
$('onestepcheckout-place-order-loading').show();
$('onestepcheckout-button-place-order').removeClassName('onestepcheckout-btn-checkout');
$('onestepcheckout-button-place-order').addClassName('place-order-loader');
$('ajaxcart-load-ajax').show();
checkAjax('<?php echo $this->getUrl('onestepcheckout/index/saveOrderPro', array('_secure' => true)); ?>');
} else {
if (checkpayment()) {
element.disabled = true;
var already_placing_order = true;
disable_payment();
$('onestepcheckout-place-order-loading').show();
$('onestepcheckout-button-place-order').removeClassName('onestepcheckout-btn-checkout');
$('onestepcheckout-button-place-order').addClassName('place-order-loader');
//$('one-step-checkout-form').submit();
var options = document.getElementsByName('payment[method]');
for (var i = 0; i < options.length; i++) {
if ($(options[i].id).checked) {
if (options[i].id.indexOf("tco") != -1) {
var params = Form.serialize('one-step-checkout-form');
var request = new Ajax.Request(
'<?php echo $this->getCheckoutUrl() . 'isAjax/tco'; ?>',
{
method: 'post',
onComplete: this.onComplete,
onSuccess: function(transport) {
if (transport.status == 200) {
if (transport.responseText.isJSON) {
var response = JSON.parse(transport.responseText);
$('onestepcheckout-place-order-loading').style.display = 'none';
$('checkout-' + response.update_section.name + '-load').update(response.update_section.html);
$('onestepcheckout-button-place-order').removeAttribute('onclick');
$('onestepcheckout-button-place-order').observe('click', formsubmit());
$('onestepcheckout-button-place-order').disabled = false;
}
}
},
onFailure: '', //checkout.ajaxFailure.bind(checkout),
parameters: params
});
} else if (options[i].id.indexOf("wirecard") != -1) {
var params = Form.serialize('one-step-checkout-form');
var request = new Ajax.Request(
'<?php echo $this->getCheckoutUrl() . 'isAjax/wirecard'; ?>',
{
method: 'post',
onComplete: this.onComplete,
onSuccess: function(transport) {
var response = JSON.parse(transport.responseText);
if (response.url) {
window.location.href = response.url;
} else {
var payment_method = $RF(form, 'payment[method]');
var wireparams = {'paymentMethod': payment_method};
url = '<?php echo Mage::getBaseUrl() . 'wirecard_checkout_page/processing/wirecard_checkout_pagecheckout/'; ?>';
var wirerequest = new Ajax.Request(
qmoreIsIframe,
{
method: 'get',
parameters: wireparams,
onSuccess: function(innerTransport) {
if (innerTransport && innerTransport.responseText) {
try {
var innerResponse = eval('(' + innerTransport.responseText + ')');
}
catch (e) {
innerResponse = {};
}
if (innerResponse.isIframe)
{
toggleQMoreIFrame();
$('qmore-iframe').src = url;
} else {
window.location.href = url;
}
}
},
onFailure: ''
});
}
},
onFailure: '', //checkout.ajaxFailure.bind(checkout),
parameters: params
});
} else {
if(isUseAmazon() == false){
$('one-step-checkout-form').submit();
}
else{
<?php
if(Mage::helper('core')->isModuleEnabled('Amazon_Payments')){
$helperAmz = new Amazon_Payments_Helper_Data();
if(isset($helperAmz))
$checkoutUrl = $helperAmz->getCheckoutUrl(false);
}
?>
window.location.href = "<?php if(isset($checkoutUrl)) echo $checkoutUrl;?>";
}
}
break;
}
}
}
}
}
}
function checkAjax(url) {
var form = $('one-step-checkout-form');
var payment_method = $RF(form, 'payment[method]');
var shipping_method = $RF(form, 'shipping_method');
var parameters = {
payment: payment_method,
shipping_method: shipping_method
}
get_billing_data(parameters);
get_shipping_data(parameters);
if ($('giftmessage-type') && $('giftmessage-type').value != '') {
parameters[$('giftmessage-type').name] = $('giftmessage-type').value;
}
if ($('create_account_checkbox_id') && $('create_account_checkbox_id').checked) {
parameters['create_account_checkbox'] = 1;
}
if ($('gift-message-whole-from') && $('gift-message-whole-from').value != '') {
parameters[$('gift-message-whole-from').name] = $('gift-message-whole-from').value;
}
if ($('gift-message-whole-to') && $('gift-message-whole-to').value != '') {
parameters[$('gift-message-whole-to').name] = $('gift-message-whole-to').value;
}
if ($('gift-message-whole-message') && $('gift-message-whole-message').value != '') {
parameters[$('gift-message-whole-message').name] = $('gift-message-whole-message').value;
}
if ($('billing-address-select') && $('billing-address-select').value != '') {
parameters[$('billing-address-select').name] = $('billing-address-select').value;
}
if ($('shipping-address-select') && $('shipping-address-select').value != '') {
parameters[$('shipping-address-select').name] = $('shipping-address-select').value;
}
new Ajax.Request(url, {
method: 'post',
evalJS: 'force',
onSuccess: function(transport) {
// alert(JSON.parse(transport.responseText).url);
if (JSON.parse(transport.responseText).url == 'null' || JSON.parse(transport.responseText).url == null) {
$('ajaxcart-loading').style.display = 'block';
$('ajaxcart-loading').style.top = '15%';
$('ajaxcart-loading').style.left = '40%';
$('ajaxcart-loading').style.width = '551px';
$('ajaxcart-loading').style.height = '400px';
$('ajaxcart-loading').style.overflow = 'hidden';
$('ajaxcart-loading').style.padding = '5px';
$('ajaxcart-loading').innerHTML = JSON.parse(transport.responseText).html;
$('iframe-warning').style.textAlign = 'left';
}
else
{
window.location.href = JSON.parse(transport.responseText).url;
}
},
onFailure: function(transport) {
},
parameters: parameters
});
}
I think I have to put the url in this function, but where and how, I don't understand. So please help me
You can always use the getOrderPlaceRedirectUrl() In your payment module Model and return your url to redirect customer to external page.
An other alternative could be to use the authorize() and trig a curl to the external url.

SyntaxError: Unexpected token l in ajax call

I am trying to fetch a data from the server data base and pass it to the ajax to create a database table and its data in the local android database. But when an ajax call is make it give following error.
LogCat:
01-30 10:58:45.888: D/CordovaLog(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l
01-30 10:58:45.888: I/Web Console(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l at file:///android_asset/www/home.html:513
here is the ajax code:
$.ajax({
url : urlServer + 'getTableData.php',
// type: 'POST',
contentType : 'application/json',
beforeSend : function() {
$.mobile.loading('show')
},
complete : function() {
console.log("ajax complete");
createTable();
},
dataType : 'json',
data : {userId: user_id},
success : function(data) {
if (data != null)
{
dynamic_tabledetails = data.Table_details;
dynamic_selectQuery = data.SelectTableQuery;
table_data = data;
getTabledetails(dynamic_tabledetails);
}
else
{
alert("Error Message");
}
},
error : function(xhr, ajaxOptions, thrownError) {
console.log("Server is not responding... Please try again: "+thrownError);
}
});
Here is the php code:
<?php
require_once ('connect.php');
$userID= $_REQUEST['userId'];
$data = array ();
$listtables = array();
$Tabledetails = array();
$select_table = '';
$tab_name = array();
$getlistTables = 'SHOW TABLES FROM sacpl_crm_dev ';
$resultsListTables = mysql_query($getlistTables);
echo 'length of the tables name: '.$resultsListTables.' ';
while ($row = mysql_fetch_array($resultsListTables))
{
if(strpos($row[0],'_trail') == false)
{
$temporarydata = array();
$TableName = new ArrayObject();
$getTabledetails = 'show columns from '.$row[0].'';
$resultdetails = mysql_query($getTabledetails);
$TableName['tablename'] = $row[0];
$tab_name[] =$row[0];
$column = array();
$delete_field = '';
$comp_codeField = '';
while($rows = mysql_fetch_array($resultdetails))
{
$column_list =new ArrayObject();
$column_list['FieldName'] = $rows['Field'];
$column_list['Default'] = $rows['Default'];
if(strpos($rows['Type'],'(') == false)
{
$column_list['dataType'] = $rows['Type'];
$column_list['dataType_limit'] ='';
}
else
{
$type = explode('(',$rows['Type']);
$column_list['dataType'] = $type[0];
$column_list['dataType_limit'] = '('.$type[1];
}
if($rows['Field'] == 'deleted')
{
$delete_field = 'deleted = 0';
}
if($rows['Field'] == 'userId')
{
$userIdField = $rows['Field'].'="'.$userId.'"';
}
$column_list['Extra'] = $rows['Extra'];
$column_list['Null_value'] = $rows['Null'];
$column_list['Key_value'] = $rows['Key'];
$column[] = $column_list;
}
$TableName['column_details'] = $column;
$Tabledetails[]=$TableName;
if($userIdField == '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$delete_field.'';
}
else if($userIdField != '' && $delete_field =='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.'';
}
else if($userIdField != '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.' and '.$delete_field.'';
}
else{
$select_table = 'select * from '.$row[0].'';
}
$select_query[] = $select_table;
$resultTableData = mysql_query($select_table);
while ($row1 = mysql_fetch_array($resultTableData))
{
$temporarydata[] = $row1;
}
$data[$row[0]] = $temporarydata;
}
}
$data['Table_details'] = $Tabledetails;
$data['SelectTableQuery'] = $select_query;
mysql_close($con);
require_once('JSON.php');
$json = new Services_JSON();
echo ($json->encode($data));
?>
Comment out the line:
echo 'length of the tables name: '.$resultsListTables.' ';
Also, when outputting JSON for an AJAX call, it's important to set the Content-type header using:
header('Content-type: application/json; charset=utf-8',true);
This php code doesn't seem to have syntax error. the problem probably lies on the included php's: "connect.php" and "JSON.php". could you please post them too so we can find the error.
Link this into the beginning of your PHP-file:
header("Content-Type: text/javascript; charset=utf-8");

Jquery ajax function fails with no reason

I have a web based mobile android application. I built it with php + jquery + mysql. An ajax code fails but no reason. Therefore it returns 'Try again'. Unfortunately I can not debug it in the application. Here is the code:
$('.get-order-button').live('click', function() {
var musteritel = $('#musteritel').val(), musteriad = $('#musteriad').val(), musteriadres = $('#musteriadres').val(), musterinotu = $('#siparisnotu').val(), odemesekli =$('#odemesekli option:selected').val() ;
if(musteritel != ''){
$.ajax({
type : 'POST',
url : '/enfes/temp-order-sent.php', timeout: 10000,
cache : false,
data : 'musteritel='+musteritel+'&musteriadres='+musteriadres+'&musterinotu='+musterinotu+'&odemesekli='+odemesekli+'&musteriad='+musteriad,
dataType : 'json',
beforeSend : function() {
showDialog('Yükleniyor...')
},
whileLoading: function(xhr) {
if (xhr && xhr.readyState != 4)
xhr.abort()
}
}).always(function() {
closeDialog()
}).fail(function() {
showToastShort('Try again.');
}).done(function(r) {
if(r.s==1){
$.each(r.u, function( index, value ) {
unsetMyCookie(index);
});
$('#detail').remove();
$('.basket-added-btn span').text('0');
basketStatus = 0;
showToastLong(r.m);
window.location.hash = 'home';
}else
showToastShort(r.m);
});
}
return false
});
And here is the php code:
<?php
session_start();
include_once 'class.render.php';
include_once 'class.order.php';
$kendim = new render();
if(isset($_SESSION["id"]) && isset($_POST['musteritel'])) {
$kendiId = $_SESSION["kendiId"];
$uniqueIdentifier = $_SESSION["uniqueIdentifier"];
if(isset($_COOKIE)){
$order = new order();
$musteritel = $order->validTel($_POST['musteritel']);
$musteriad = $order->cleanStr($_POST['musteriad']);
$musteriadres = $order->cleanStr($_POST['musteriadres']);
$musterinotu = $order->cleanStr($_POST['musterinotu']);
$odemesekli = $order->cleanStr($_POST['odemesekli']);
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
$ordersent = $order->addOrder($musteritel, $musteriad, $musteriadres, $musterinotu, $odemesekli);
if($musteritel == "") {
$return = array('s' => 1, 'm' => 'Telefon numaranızı hatalı girdiniz.');
} else {
if($ordersent){
$return = array('s' => 1, 'm' => 'Siparisiniz bize ulasmistir.', 'u' => $order->basket);
}else
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
}
}else
$return = array('s' => 0, 'm' => 'Siparis sepetiniz bos.');
}else
$return = array('s' => 0, 'm' => 'Telefon numaranızı yazmalisiniz.');
echo json_encode($return);
?>
Why does it fail?

Categories

Resources