Trigger url after success of order placed in magento - javascript

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.

Related

WordPress callback function is called twice

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();
}

Save values of dynamic generated HTML using javascript

I m generating dynamic html with its id. You can see the below link for the dynamic generated HTML.
Dymanic Generated HTML
So for saving this, I need some suggestion on how to save it in javascript. I tried the other fields of the HTML..
function SaveNPEDetails() {
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
// Need to write saving logic for dynamic generated html here.
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
As per our discussion you can try something like
function SaveNPEDetails() {
var data = [];
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
var chs = $("#dvNPEAddData").children(".addNPEData")
for (var i = 0; i < chs.length; i++) {
var d = {};
var ch = chs[i];
var val = $(ch).find("input[name='TerRouteName']").val();
d[$(ch).find("input[name='TerRouteName']").attr("name")] = val;
val = $(ch).find("select[name='CableType']").val();
d[$(ch).find("select[name='CableType']").attr("name")] = val;
val = $(ch).find("select[name='CableSize']").val();
d[$(ch).find("select[name='CableSize']").attr("name")] = val;
val = $(ch).find("input[name='NoLiveFibre']").val();
d[$(ch).find("input[name='NoLiveFibre']").attr("name")] = val;
data.push(d);
}
var d = JSON.stringify(data);
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields , myJsonXML : d}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
Using your example in the fiddle I've done the following
$('#submit').click(function() {
var DashboardFields = {},
status = true;
$.each($('input[type="text"]'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '') {
alert(id + ' field is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
$.each($('select'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '--Select--' || $(v).val() == null) {
alert(id + ' select is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
if(!status){
alert('you have empty fields');
} else {
console.log(DashboardFields); //Here should be your Ajax Call
}
});
JsFiddle
I've used your example with ID's and created a filter in order to take dynamically the fields not by ID's, I used the ID's to map the DashboardFields object but I strongly encourage to use name or other data- param and change the jQuery code after (the line with var id=$(v).attr('id'))
Hope this helps you

How do I call a vendor library from my main.js?

I have a basic electron app where I am trying to use vendor supplied js library. The example they supplied provides a static html page which includes their custom library and an example js file. This is the html
<HTML>
<HEAD>
<TITLE> MWD Library </TITLE>
</HEAD>
<BODY>
<h2>MWD Library Example</h2>
<input id="authAndConnect" type="button" value="authenticate and connect to stream" onclick="authenticateAndConnectToStream()" /></br></br>
<input id="clickMe" type="button" value="place position" onclick="placePosition()" /></br></br>
<input id="unsubscribeMe" type="button" value="unsubscribe" onclick="unsubscribe()" />
<input id="streamError" type="button" value="reconn to stream" onclick="reconnectToStream()" />
<input id="historicalData" type="button" value="historical data for GOLD" onclick="getHistoricalData()" />
<input id="goldExpiries" type="button" value="expiries for GOLD" onclick="getCurrentGoldExpiries()" /></br></br>
<input id="userTrades" type="button" value="active&completed trades" onclick="getUserTrades()" />
</BODY>
<SCRIPT SRC="jquery.ajax.js"></SCRIPT>
<SCRIPT SRC="mwdlib.js"></SCRIPT>
<SCRIPT SRC="app.js"></SCRIPT>
</HTML>
In the example above the button click calls authenticateAndConnectToStream in their example apps.js
//DEMO
//provide API key
MWDLibrary.config("dwR4jXn9ng9U2TbaPG2TzP1FTMqWMOuSrCWSK5vRIW7N9hefYEapvkXuYfVhzmdyFypxdayfkUT07HltIs4pwT0FIqEJ6PyzUz0mIqGj1GtmAlyeuVmSC5IcjO4gz14q");
//authenticate on MarketsWorld
var getAuthTokenParams = {email:"rtmarchionne#gmail.com", password:"Pitts4318AEM"};
var authenticateAndConnectToStream = function(){
MWDLibrary.getAuthDetails(getAuthTokenParams, function(authDetails) {
//optional: get older data
var marketsToSubscribeTo = ['GOLD', 'AUDNZD'];
for (var i = 0; i < marketsToSubscribeTo.length; i++){
MWDLibrary.getHistoricalData(marketsToSubscribeTo[i], function(response) {
console.log(response);
}, function(errorMessage) {
console.log(errorMessage);
});
}
//now you can connect to stream
MWDLibrary.connect(marketsToSubscribeTo, function() {
addMarketsListeners();
}, function(errorMessage) {
console.log(errorMessage);
});
}, function(errorMessage) {
console.log(errorMessage);
});
};
I want to call the same methods that start with MWDLibrary. from my main js like MWDLibrary.config("dwR4jXn9")
My main.js:
const electron = require('electron')
var path = require('path');
var countdown = require(path.resolve( __dirname, "./tradescaler.js" ) );
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
let mainWindow
app.on('ready', _ => {
mainWindow = new BrowserWindow({
height: 360,
width: 700,
title: "TradeScaler Beta - Creative Solutions",
//frame: false,
alwaysOnTop: true,
autoHideMenuBar: true,
backgroundColor: "#FF7E47",
})
mainWindow.loadURL('file://' + __dirname + '/tradescaler.html')
mainWindow
//mainWindow.setAlwaysOnTop(true, 'screen');
mainWindow.on('closed', _ => {
mainWindow = null
})
})
ipc.on('countdown-start', _ => {
console.log('caught it!');
MWDLibrary.config();
countdown(count => {
mainWindow.webContents.send('countdown', count)
})
})
In my main.js above I get an error that says MWDLibrary is not defined.
Is it the structure of the library that is the problem? do i have to pass a window or modify the library?
Here is the library I'm trying to use:
(function(window){
'use strict';
function init(){
var MWDLibrary = {};
var transferProtocol = "https://"
var streamTransferProtocol = "https://"
var baseTLD = "www.marketsworld.com"
var basePort = ""
var streamBaseTLD = "www.marketsworld.com"
var streamPort = ""
var authToken = "";
var publicId = "";
var userLevel = "user";
var apiKey = "-";
var streamUrl = "";
var streamToken = "";
var subscribedChannels = [];
var streamEvents = {};
var offersWithExpiries = [];
var filteredExpiries = {};
var positions = {};
var evtSource;
MWDLibrary.config = function(apiUserKey){
apiKey = apiUserKey;
}
MWDLibrary.expiries = function(market){
return filteredExpiries[market];
}
MWDLibrary.connect = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Connecting...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var dispatchUrl = streamTransferProtocol+streamBaseTLD+streamPort+'/api/dispatcher';
getJSON(dispatchUrl, apiKey, authToken, function(data){
var data_from_json = JSON.parse(data);
if(data_from_json.url){
var url = data_from_json.url+'/announce?callback=__callback&publicToken='+publicId+'&userLevel='+userLevel+'&_='+(new Date().getTime() / 1000);
getJSON(url, apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
if(data_from_json.url){
streamUrl = data_from_json.url.substring(0,data_from_json.url.lastIndexOf("/user"));
streamToken = data_from_json.url.split("token=")[1];
MWDLibrary.subscribe(channelsToSubscribeTo, function(subscribeResponseData) {
evtSource = new EventSource(streamTransferProtocol+data_from_json.url);
evtSource.onopen = sseOpen;
evtSource.onmessage = sseMessage;
evtSource.onerror = sseError;
successHandler('connected');
return;
}, function(errorMessage) {
errorHandler(errorMessage);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
MWDLibrary.subscribe = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Subscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var channels = 'ALL|TEST|private.'+publicId;
if (channelsToSubscribeTo.length > 0){
var auxChannels = '';
if(subscribedChannels.length > 0){
channels = subscribedChannels[0];
for(var j = 1; j < subscribedChannels.length; j++){
channels = channels +'|'+subscribedChannels[j];
}
}
for(var i = 0; i < channelsToSubscribeTo.length; i++)
{
if(subscribedChannels.indexOf(channelsToSubscribeTo[i])==-1){
auxChannels = auxChannels+'|'+channelsToSubscribeTo[i]+'|'+channelsToSubscribeTo[i]+'.game#1';
}
}
channels = channels+auxChannels;
}
else{
if (subscribedChannels.length == 0)
{
channels = channels+'|GOLD|GOLD.game#1';
}
else{
channels = subscribedChannels[0];
for (var j = 1; j < subscribedChannels.length; j++){
channels = channels + '|' + subscribedChannels[j];
}
}
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/subscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(subscribeData) {
var subscribeData_from_json = JSON.parse(subscribeData);
subscribedChannels = subscribeData_from_json.channels;
//console.log(subscribedChannels);
for (var i = 0; i < subscribedChannels.length; i++)
{
if (subscribedChannels[i] == 'ALL')
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['heartbeat'] = new CustomEvent('ALL.heartbeat', {'detail':'-'});
streamEvents[subscribedChannels[i]]['status'] = new CustomEvent('ALL.status', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('private') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['positions'] = new CustomEvent('PRIVATE.positions', {'detail':'-'});
streamEvents[subscribedChannels[i]]['balance'] = new CustomEvent('PRIVATE.balance', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('game') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['expiry'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.expiry', {'detail':'-'});
streamEvents[subscribedChannels[i]]['spread'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.spread', {'detail':'-'});
streamEvents[subscribedChannels[i]]['payout'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.payout', {'detail':'-'});
streamEvents[subscribedChannels[i]]['offer'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.offer', {'detail':'-'});
continue;
}
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['value'] = new CustomEvent(subscribedChannels[i]+'.value', {'detail':'-'});
}
successHandler(subscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.unsubscribe = function(channelsToUnsubscribeFrom, successHandler, errorHandler){
//console.log("Unsubscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
if(channelsToUnsubscribeFrom.length == 0){
errorHandler("Please select markets to unsubscribe from.");
return;
}
var channels = channelsToUnsubscribeFrom[0]+'|'+channelsToUnsubscribeFrom[0]+'.game#1';
for(var i = 1; i < channelsToUnsubscribeFrom.length; i++)
{
channels = channels+'|'+channelsToUnsubscribeFrom[i]+'|'+channelsToUnsubscribeFrom[i]+'.game#1';
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/unsubscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(unsubscribeData) {
var unsubscribeData_from_json = JSON.parse(unsubscribeData);
var unsubscribedChannels = unsubscribeData_from_json.channels;
for(var i = 0; i < unsubscribedChannels.length; i++)
{
var index = subscribedChannels.indexOf(unsubscribedChannels[i]);
if(index != -1) {
subscribedChannels.splice(index, 1);
}
}
//console.log(subscribedChannels);
successHandler(unsubscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.getAuthDetails = function(params, successHandler, errorHandler){
//console.log("getting auth token...");
var url = transferProtocol+baseTLD+basePort+'/api/v2/sessions';
postJSON(url, apiKey, authToken, params, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
authToken = data_from_json.api_session_token.token;
publicId = data_from_json.api_session_token.user.public_id;
successHandler(data_from_json.api_session_token);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status);
return;
});
}
MWDLibrary.placePosition = function(params, successHandler, errorHandler){
//console.log("placing a position...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var url = transferProtocol+baseTLD+basePort+'/api/v2/positions';
if(params.market == ''){
errorHandler('Market code is missing.');
return;
}
var position = positions[params.market];
if(!position || position.market_value <= 0){
errorHandler('No data for this market.');
return;
}
if(!params.offer_id || params.offer_id == ''){
errorHandler('Offer id is missing.');
return;
}
if(!params.resolution_at || params.resolution_at <= 0){
errorHandler('Expiry time is missing.');
return;
}
if(!params.type || params.type == ''){
errorHandler('Position type is missing.');
return;
}
if(!params.wager || params.wager <= 0){
errorHandler('Wager is missing.');
return;
}
position.offer_id = params.offer_id;
position.resolution_at = params.resolution_at;
position.type = params.type;
position.wager = params.wager;
//console.log(position);
postJSON(url, apiKey, authToken, position, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
successHandler(data_from_json);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status+' - make sure all parameters are set correctly and wait 10 seconds between bets');
return;
});
}
MWDLibrary.getMarkets = function(successHandler, errorHandler){
//console.log("getting markets list...");
getJSON(transferProtocol+baseTLD+basePort+'/api/v2/markets.json', apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
for (var i = 0; i < data_from_json.length; i++) {
var status = "closed";
if (data_from_json[i].market.next_open_time > data_from_json[i].market.next_close_time)
{
status = "open";
}
data_from_json[i].market.status = status;
}
successHandler(data_from_json);
}, function(status) {
errorHandler(status);
});
}
var sortedOffersWithExpiries = offers.sort(compareOffersBtOrder);
for (var i=0; i<sortedOffersWithExpiries.length;i++)
{
expiryValue = 0;
expiryResult = 0;
var expiriesCopy = sortedOffersWithExpiries[i].expiries;
for (var index = 0; index<expiriesCopy.length;index++)
{
expiryValue = expiriesCopy[index]
if (expiryValue > lastExpiry)
{
expiryResult = expiryValue
break
}
}
if (expiryResult != 0)
{
var tuple = {};
tuple.timestamp = expiryValue/1000;
tuple.offerId = sortedOffersWithExpiries[i].offer;
tuple.cutout = sortedOffersWithExpiries[i].cutout;
expiriesFinalList.push(tuple);
lastExpiry = expiryValue
}
}
return expiriesFinalList;
}
function compareOffersBtOrder(a,b) {
if (a.order < b.order)
return -1;
if (a.order > b.order)
return 1;
return 0;
}
})/*(window)-->*/;
You're missing the .js file extension at the end of mwdlib
And you may need to require it using the full system path, instead of a relative one.
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );

How to send javascript variable to php to change the file name of the uploaded file?

How to change the filename for the upload to id+filename?
Example:
I have the id in a javascript variable item_id.
Is there a chance to add data on data.append and use this in the "upload.php"?
I want that the file name have instead of time and date the prefix id. Example id = 00002, file name = "picturewhatever.jpg".
The to be uploaded file should be "00002PictureWhatever.jpg"
<div id="mulitplefileuploader" title="">
<br>
Upload
</div>
<div id="status"></div>
<script>
$(document).ready(function() {
var settings = {
url: "upload.php",
method: "POST",
allowedTypes:"jpg,png,gif",
fileName: "myfile",
multiple: true,
onSuccess:function(files,data,xhr) {
$("#status").html("<font color='green'>Upload successful</font>");
},
onError: function(files,status,errMsg) {
$("#status").html("<font color='red'>Upload failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
</div>
File: multifileuploader.js
function multiUploader(config){
this.config = config;
this.items = "";
this.all = []
var self = this;
multiUploader.prototype._init = function(){
if (window.File &&
window.FileReader &&
window.FileList &&
window.Blob) {
var inputId = $("#"+this.config.form).find("input[type='file']").eq(0).attr("id");
document.getElementById(inputId).addEventListener("change", this._read, false);
document.getElementById(this.config.dragArea).addEventListener("dragover", function(e){ e.stopPropagation(); e.preventDefault(); }, false);
document.getElementById(this.config.dragArea).addEventListener("drop", this._dropFiles, false);
document.getElementById(this.config.form).addEventListener("submit", this._submit, false);
} else
console.log("Browser supports failed");
}
multiUploader.prototype._submit = function(e){
e.stopPropagation(); e.preventDefault();
self._startUpload();
}
multiUploader.prototype._preview = function(data){
this.items = data;
if(this.items.length > 0){
var html = "";
var uId = "";
for(var i = 0; i<this.items.length; i++){
uId = this.items[i].name._unique();
var sampleIcon = '<img src="images/image.png" />';
var errorClass = "";
if(typeof this.items[i] != undefined){
if(self._validate(this.items[i].type) <= 0) {
sampleIcon = '<img src="images/unknown.png" />';
errorClass =" invalid";
}
html += '<div class="dfiles'+errorClass+'" rel="'+uId+'"><h5>'+sampleIcon+this.items[i].name+'</h5><div id="'+uId+'" class="progress" style="display:none;"><img src="images/ajax-loader.gif" /></div></div>';
}
}
$("#dragAndDropFiles").append(html);
}
}
multiUploader.prototype._read = function(evt){
if(evt.target.files){
self._preview(evt.target.files);
self.all.push(evt.target.files);
} else
console.log("Failed file reading");
}
multiUploader.prototype._validate = function(format){
var arr = this.config.support.split(",");
return arr.indexOf(format);
}
multiUploader.prototype._dropFiles = function(e){
e.stopPropagation(); e.preventDefault();
self._preview(e.dataTransfer.files);
self.all.push(e.dataTransfer.files);
}
multiUploader.prototype._uploader = function(file,f){
if(typeof file[f] != undefined && self._validate(file[f].type) > 0){
var data = new FormData();
var ids = file[f].name._unique();
data.append('file',file[f]);
data.append('index',ids);
$(".dfiles[rel='"+ids+"']").find(".progress").show();
$.ajax({
type:"POST",
url:this.config.uploadUrl,
data:data,
cache: false,
contentType: false,
processData: false,
success:function(rponse){
$("#"+ids).hide();
var obj = $(".dfiles").get();
$.each(obj,function(k,fle){
if($(fle).attr("rel") == rponse){
$(fle).slideUp("normal", function(){ $(this).remove(); });
}
});
if (f+1 < file.length) {
self._uploader(file,f+1);
}
}
});
} else
console.log("Invalid file format - "+file[f].name);
}
multiUploader.prototype._startUpload = function(){
if(this.all.length > 0){
for(var k=0; k<this.all.length; k++){
var file = this.all[k];
this._uploader(file,0);
}
}
}
String.prototype._unique = function(){
return this.replace(/[a-zA-Z]/g, function(c){
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
});
}
this._init();
}
function initMultiUploader(){
new multiUploader(config);
}
Try to modify multiUploader.prototype._uploader = function(file,f)
and add a line after data.append('index',ids); with something like:
data.append('item_id','12345'); <-- you can extract the item_id by a url param, div id....
Then in your upload.php you will catch the item_id POST data

Pubnub getting duplicated message when changing channel

I have a problem with pubnub.
I have friends list and I need to change pubnub channel on clicking them, by switching to another friend, to chat with him.
I have global channel variable, and I am changing it on friend click. The problem is, when I switch to another friend and write a message, the message appears in panel is duplicated.
Here is the code I am using.
base = "/";
pubnub = "";
channel ="";
messageListContent = "ul.chat-messages-block";
function handleMessage(message,$index) {
if ( $index != 'me' ) {
var $index = 'left';
} else {
var $index = 'right';
}
var $imageUrl = "";
if ( message.picture != '' && message.picture != null ) {
$imageUrl = message.picture;
if ( (/^http:\/\//.test( $imageUrl ) ) ) {
$imageUrl = $imageUrl;
} else {
$imageUrl = "uploads/user/"+ $imageUrl;
}
} else {
$imageUrl = 'resources/images/user-male.png';
}
var messageEl = jQuery('<li class="'+$index+' clearfix">'+
'<div class="user-img pull-'+$index+'"> <img src="' + $imageUrl +'" alt="'+message.username+'"> </div>'+
'<div class="chat-body clearfix">'+
'<div class="">'+
'<span class="name">'+message.username+'</span><span class="name"></span><span class="badge"><i class="fa fa-clock-o"></i>'+message.chat_date+'</span></div>'+
'<p>'+ message.message + '</p>'+
' </div>'+
'</li>');
jQuery(messageListContent).append(messageEl);
};
jQuery.getJSON( "/chat/read", function( data ) {
var items = [];
if ( data != null && data != "" ){
pubnub = PUBNUB.init({
publish_key: data.publish_key,
subscribe_key: data.subscribe_key,
});
if ( data.messages.length > 0 ) {
var $my_id = data.current_user;
for( var i = 0; i < data.messages.length; i++ ) {
if ( data.messages[i].user_id == $my_id ) {
$index = "me";
} else {
var $index = "";
}
handleMessage(data.messages[i],$index);
}
}
}
});
jQuery(document).ready(function () {
jQuery('#sendMessageButton').click(function (event) {
var message = jQuery('#messageContent').val();
var friend_id = jQuery('li.activeChannel').attr('data-id');
if ( message != '' ) {
jQuery.ajax({
url: base+"chat/sendChat",
type:'POST',
data:{
friend_id: friend_id,
text:message
},
success:function(data){
var data = JSON.parse(data);
//sounds.play( 'chat' );
pubnub.publish({
channel: channel,
message: {
username: data.messages.username,
message: data.messages.message,
user_id: data.messages.friend_id,
current_user: data.messages.user_id,
picture: data.messages.picture,
type:'message',
chat_date: data.messages.chat_date
}
});
},
error: function(err){
jQuery('.errorText').fadeIn();
}
});
jQuery('#messageContent').val("");
}
});
// Also send a message when the user hits the enter button in the text area.
jQuery('#messageContent').bind('keydown', function (event) {
if((event.keyCode || event.charCode) !== 13) return true;
jQuery('#sendMessageButton').click();
return false;
});
jQuery('ul.chat-users li').click(function(){
var friend_id = jQuery(this).attr('data-id');
jQuery('ul.chat-users li').removeClass('activeChannel');
jQuery(this).addClass('activeChannel');
jQuery.ajax({
url: base+"chat/getUsersChat",
type:'POST',
data:{
friend_id: friend_id
},
success:function(data){
var data = JSON.parse(data);
jQuery('.chat-messages ul').html("");
//id = pubnub.uuid();
//channel = 'oo-chat-' + id+friend_id;
channel = 'oo-chat-' + data.channel;
if ( data.messages.length > 0 ) {
var $my_id = data.current_user;
for( var i = 0; i < data.messages.length; i++ ) {
if ( data.messages[i].user_id == $my_id ) {
$index = "me";
} else {
var $index = "";
}
//messageListContent = "ul.activeChannel"+channel;
//console.log(channel);
handleMessage(data.messages[i],$index);
}
}
pubnub.subscribe({
channel: channel,
message: function(message) {
console.log("Pubnub callback", message);
handleMessage(message,"me");
},
connect: function(message) {
console.log("Pubnub is connected", message);
},
//callback:
});
},
error: function(err){
jQuery('.errorText').fadeIn();
}
});
});
});
And here is how it is looking
Any Idea?
I had even tried to unsubscribe the previous channel on friend click, but no result.
What am I doing wrong?
I solved the problem. The problem was in pubnub.js version, it was 3.4, I switched to 3.7.1 and added the following code
jQuery('ul.chat-users li').click(function(){
var friend_id = jQuery(this).attr('data-id');
jQuery('ul.chat-users li').removeClass('activeChannel');
jQuery(this).addClass('activeChannel');
if ( channel != "" ) {
pubnub.unsubscribe({
channel : channel,
});
}

Categories

Resources