localhost: how to setup XHR-Signaling (connection.openSignalingChannel not getting called) - javascript

I am using RTCMultiConnection v3.4.4
I want to run WebRTC on localhost. I have chosen XHR-Signaling because I want the project to be completely offline. I do not want it to depend on the internet, since everything is on localhost (to be later deployed on LAN)
I have included XHRConnection.js and set connection.setCustomSocketHandler(XHRConnection). I also did the override connection.openSignalingChannel...
However, when I open/start the room, my video shows but the buttons that was disabled by disableInputButtons() still remains disabled. The chat is not working.
I did a console.log at override connection.openSignalingChannel... to confirm if it ever got called, but it does not.
Please help on how to implement XHR-Signaling on localhost.
Thanks.
Code:
File: Audio+Video+TextChat+FileSharing.html
<!-- Demo version: 2017.08.10 -->
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Audio+Video+TextChat+FileSharing using RTCMultiConnection</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<link rel="shortcut icon" href="./logo.png">
<link rel="stylesheet" href="./stylesheet.css">
<script src="./menu.js"></script>
</head>
<body>
<h1>
Audio+Video+TextChat+FileSharing using RTCMultiConnection
<p class="no-mobile">
Multi-user (many-to-many) video streaming + text chat + file sharing using mesh networking model.
</p>
</h1>
<section class="make-center">
<input type="text" id="room-id" value="abcdef" autocorrect=off autocapitalize=off size=20>
<button id="open-room">Open Room</button><button id="join-room">Join Room</button><button id="open-or-join-room">Auto Open Or Join Room</button>
<br><br>
<input type="text" id="input-text-chat" placeholder="Enter Text Chat" disabled>
<button id="share-file" disabled>Share File</button>
<br><br>
<button id="btn-leave-room" disabled>Leave/or close the room</button>
<div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div>
<div id="chat-container">
<div id="file-container"></div>
<div class="chat-output"></div>
</div>
<div id="videos-container"></div>
</section>
<script src="./RTCMultiConnection.min.js"></script>
<script src="./adapter.js"></script>
<script src="./XHRConnection.js"></script>
<!-- custom layout for HTML5 audio/video elements -->
<link rel="stylesheet" href="./getHTMLMediaElement.css">
<script src="./getHTMLMediaElement.js"></script>
<script src="./FileBufferReader.js"></script>
<script>
// ......................................................
// .......................UI Code........................
// ......................................................
document.getElementById('open-room').onclick = function() {
disableInputButtons();
connection.open( document.getElementById('room-id').value , function() {
showRoomURL(connection.sessionid);
xhr
(
'start-broadcast.php' ,
function( responseText ){ console.log( 'Broadcast started [' + document.getElementById('room-id').value + ']' ) },
JSON.stringify( { name: document.getElementById('room-id').value } )
);
});
};
document.getElementById('join-room').onclick = function() {
disableInputButtons();
connection.join(document.getElementById('room-id').value);
};
document.getElementById('open-or-join-room').onclick = function() {
disableInputButtons();
connection.openOrJoin(document.getElementById('room-id').value, function(isRoomExists, roomid) {
if (!isRoomExists) {
showRoomURL(roomid);
}
});
};
document.getElementById('btn-leave-room').onclick = function() {
this.disabled = true;
if (connection.isInitiator) {
// use this method if you did NOT set "autoCloseEntireSession===true"
// for more info: https://github.com/muaz-khan/RTCMultiConnection#closeentiresession
connection.closeEntireSession(function() {
document.querySelector('h1').innerHTML = 'Entire session has been closed.';
});
} else {
connection.leave();
}
};
// ......................................................
// ................FileSharing/TextChat Code.............
// ......................................................
document.getElementById('share-file').onclick = function() {
var fileSelector = new FileSelector();
fileSelector.selectSingleFile(function(file) {
connection.send(file);
});
};
document.getElementById('input-text-chat').onkeyup = function(e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
this.value = this.value.replace(/^\s+|\s+$/g, '');
if (!this.value.length) return;
connection.send(this.value);
appendDIV(this.value);
this.value = '';
};
var chatContainer = document.querySelector('.chat-output');
function appendDIV(event) {
var div = document.createElement('div');
div.innerHTML = event.data || event;
chatContainer.insertBefore(div, chatContainer.firstChild);
div.tabIndex = 0;
div.focus();
document.getElementById('input-text-chat').focus();
}
// ......................................................
// ..................RTCMultiConnection Code.............
// ......................................................
var connection = new RTCMultiConnection();
connection.setCustomSocketHandler(XHRConnection);
connection.direction = 'one-way';
// by default, socket.io server is assumed to be deployed on your own URL
// connection.socketURL = '/';
connection.trickleIce = false;
// comment-out below line if you do not have your own socket.io server
// connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
//connection.socketMessageEvent = 'audio-video-file-chat-demo';
connection.enableLogs = true;
connection.enableFileSharing = true; // by default, it is "false".
// this object is used to store "onmessage" callbacks from "openSignalingChannel handler
var onMessageCallbacks = {};
// this object is used to make sure identical messages are not used multiple times
var messagesReceived = {};
// overriding "openSignalingChannel handler
connection.openSignalingChannel = function (config) {
console.log( 'called: openSignalingChannel' );
var channel = config.channel || this.channel;
onMessageCallbacks[channel] = config.onmessage;
// let RTCMultiConnection know that server connection is opened!
if (config.onopen) {
console.log( 'Calling the config.open object' );
setTimeout(config.onopen, 1);
}
else console.log( 'No config.open object' );
// returning an object to RTCMultiConnection
// so it can send data using "send" method
return {
send: function (data) {
data = {
channel: channel,
message: data,
sender: connection.userid
};
// posting data to server
// data is also JSON-ified.
xhr('xhr-signalhandler-post.php', null, JSON.stringify(data));
},
channel: channel
};
};
connection.session = {
audio: true,
video: true,
data: true
};
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
connection.videosContainer = document.getElementById('videos-container');
connection.onstream = function(event) {
var width = parseInt(connection.videosContainer.clientWidth / 2) - 20;
var mediaElement = getHTMLMediaElement(event.mediaElement, {
title: event.userid,
buttons: ['full-screen'],
width: width,
showOnMouseEnter: false
});
connection.videosContainer.appendChild(mediaElement);
setTimeout(function() {
mediaElement.media.play();
}, 5000);
mediaElement.id = event.streamid;
};
connection.onstreamended = function(event) {
var mediaElement = document.getElementById(event.streamid);
if (mediaElement) {
mediaElement.parentNode.removeChild(mediaElement);
}
};
connection.onmessage = appendDIV;
connection.filesContainer = document.getElementById('file-container');
connection.onopen = function() {
console.log( "com. openend" );
document.getElementById('share-file').disabled = false;
document.getElementById('input-text-chat').disabled = false;
document.getElementById('btn-leave-room').disabled = false;
document.querySelector('h1').innerHTML = 'You are connected with: ' + connection.getAllParticipants().join(', ');
};
connection.onclose = function() {
if (connection.getAllParticipants().length) {
document.querySelector('h1').innerHTML = 'You are still connected with: ' + connection.getAllParticipants().join(', ');
} else {
document.querySelector('h1').innerHTML = 'Seems session has been closed or all participants left.';
}
};
connection.onEntireSessionClosed = function(event) {
document.getElementById('share-file').disabled = true;
document.getElementById('input-text-chat').disabled = true;
document.getElementById('btn-leave-room').disabled = true;
document.getElementById('open-or-join-room').disabled = false;
document.getElementById('open-room').disabled = false;
document.getElementById('join-room').disabled = false;
document.getElementById('room-id').disabled = false;
connection.attachStreams.forEach(function(stream) {
stream.stop();
});
// don't display alert for moderator
if (connection.userid === event.userid) return;
document.querySelector('h1').innerHTML = 'Entire session has been closed by the moderator: ' + event.userid;
};
connection.onUserIdAlreadyTaken = function(useridAlreadyTaken, yourNewUserId) {
// seems room is already opened
connection.join(useridAlreadyTaken);
};
function disableInputButtons() {
document.getElementById('open-or-join-room').disabled = true;
document.getElementById('open-room').disabled = true;
document.getElementById('join-room').disabled = true;
document.getElementById('room-id').disabled = true;
}
// ......................................................
// ......................Handling Room-ID................
// ......................................................
function showRoomURL(roomid) {
var roomHashURL = '#' + roomid;
var roomQueryStringURL = '?roomid=' + roomid;
var html = '<h2>Unique URL for your room:</h2><br>';
html += 'Hash URL: ' + roomHashURL + '';
html += '<br>';
html += 'QueryString URL: ' + roomQueryStringURL + '';
var roomURLsDiv = document.getElementById('room-urls');
roomURLsDiv.innerHTML = html;
roomURLsDiv.style.display = 'block';
}
(function() {
var params = {},
r = /([^&=]+)=?([^&]*)/g;
function d(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
}
var match, search = window.location.search;
while (match = r.exec(search.substring(1)))
params[d(match[1])] = d(match[2]);
window.params = params;
})();
var roomid = '';
if (localStorage.getItem(connection.socketMessageEvent)) {
roomid = localStorage.getItem(connection.socketMessageEvent);
} else {
roomid = connection.token();
}
document.getElementById('room-id').value = roomid;
document.getElementById('room-id').onkeyup = function() {
localStorage.setItem(connection.socketMessageEvent, this.value);
};
var hashString = location.hash.replace('#', '');
if (hashString.length && hashString.indexOf('comment-') == 0) {
hashString = '';
}
var roomid = params.roomid;
if (!roomid && hashString.length) {
roomid = hashString;
}
if (roomid && roomid.length) {
document.getElementById('room-id').value = roomid;
localStorage.setItem(connection.socketMessageEvent, roomid);
// auto-join-room
(function reCheckRoomPresence() {
connection.checkPresence(roomid, function(isRoomExists) {
if (isRoomExists) {
connection.join(roomid);
return;
}
setTimeout(reCheckRoomPresence, 5000);
});
})();
disableInputButtons();
}
</script>
<footer>
<small id="send-message"></small>
</footer>
<script src="common.js"></script>
</body>
</html>
XHRConnection.js:
function XHRConnection(connection, connectCallback) {
connection.socket = {
send: function(data) {
data = {
message: data,
sender: connection.userid
};
// posting data to server
// data is also JSON-ified.
xhr('xhr-signalhandler-post.php', null, JSON.stringify(data));
}
};
// this object is used to make sure identical messages are not used multiple times
var messagesReceived = {};
function repeatedlyCheck() {
xhr('xhr-signalhandler-get.php', function(data) {
// if server says nothing; wait.
if (data == false) return setTimeout(repeatedlyCheck, 400);
// if already receied same message; skip.
if (messagesReceived[data.ID]) return setTimeout(repeatedlyCheck, 400);
messagesReceived[data.ID] = data.Message;
// "Message" property is JSON-ified in "openSignalingChannel handler
data = JSON.parse(data.Message);
if (data.eventName === connection.socketMessageEvent) {
onMessagesCallback(data.data);
}
if (data.eventName === 'presence') {
data = data.data;
if (data.userid === connection.userid) return;
connection.onUserStatusChanged({
userid: data.userid,
status: data.isOnline === true ? 'online' : 'offline',
extra: connection.peers[data.userid] ? connection.peers[data.userid].extra : {}
});
}
// repeatedly check the database
setTimeout(repeatedlyCheck, 1);
});
}
repeatedlyCheck();
setTimeout
(
function() {
if (connection.enableLogs) {
console.info('XHR connection opened');
}
connection.socket.emit('presence', {
userid: connection.userid,
isOnline: true
});
if( connectCallback ) {
console.log( 'Calling connectCallback...' );
connectCallback(connection.socket);
console.log( 'Done' );
}
},
2000
);
connection.socket.emit = function(eventName, data, callback) {
if (eventName === 'changed-uuid') return;
if (data.message && data.message.shiftedModerationControl) return;
connection.socket.send({
eventName: eventName,
data: data
});
if (callback) {
callback();
}
};
var mPeer = connection.multiPeersHandler;
function onMessagesCallback(message) {
if (message.remoteUserId != connection.userid) return;
if (connection.peers[message.sender] && connection.peers[message.sender].extra != message.extra) {
connection.peers[message.sender].extra = message.extra;
connection.onExtraDataUpdated({
userid: message.sender,
extra: message.extra
});
}
if (message.message.streamSyncNeeded && connection.peers[message.sender]) {
var stream = connection.streamEvents[message.message.streamid];
if (!stream || !stream.stream) {
return;
}
var action = message.message.action;
if (action === 'ended' || action === 'stream-removed') {
connection.onstreamended(stream);
return;
}
var type = message.message.type != 'both' ? message.message.type : null;
stream.stream[action](type);
return;
}
if (message.message === 'connectWithAllParticipants') {
if (connection.broadcasters.indexOf(message.sender) === -1) {
connection.broadcasters.push(message.sender);
}
mPeer.onNegotiationNeeded({
allParticipants: connection.getAllParticipants(message.sender)
}, message.sender);
return;
}
if (message.message === 'removeFromBroadcastersList') {
if (connection.broadcasters.indexOf(message.sender) !== -1) {
delete connection.broadcasters[connection.broadcasters.indexOf(message.sender)];
connection.broadcasters = removeNullEntries(connection.broadcasters);
}
return;
}
if (message.message === 'dropPeerConnection') {
connection.deletePeer(message.sender);
return;
}
if (message.message.allParticipants) {
if (message.message.allParticipants.indexOf(message.sender) === -1) {
message.message.allParticipants.push(message.sender);
}
message.message.allParticipants.forEach(function(participant) {
mPeer[!connection.peers[participant] ? 'createNewPeer' : 'renegotiatePeer'](participant, {
localPeerSdpConstraints: {
OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
},
remotePeerSdpConstraints: {
OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
},
isOneWay: !!connection.session.oneway || connection.direction === 'one-way',
isDataOnly: isData(connection.session)
});
});
return;
}
if (message.message.newParticipant) {
if (message.message.newParticipant == connection.userid) return;
if (!!connection.peers[message.message.newParticipant]) return;
mPeer.createNewPeer(message.message.newParticipant, message.message.userPreferences || {
localPeerSdpConstraints: {
OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
},
remotePeerSdpConstraints: {
OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
},
isOneWay: !!connection.session.oneway || connection.direction === 'one-way',
isDataOnly: isData(connection.session)
});
return;
}
if (message.message.readyForOffer || message.message.addMeAsBroadcaster) {
connection.addNewBroadcaster(message.sender);
}
if (message.message.newParticipationRequest && message.sender !== connection.userid) {
if (connection.peers[message.sender]) {
connection.deletePeer(message.sender);
}
var userPreferences = {
extra: message.extra || {},
localPeerSdpConstraints: message.message.remotePeerSdpConstraints || {
OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
},
remotePeerSdpConstraints: message.message.localPeerSdpConstraints || {
OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
},
isOneWay: typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way',
isDataOnly: typeof message.message.isDataOnly !== 'undefined' ? message.message.isDataOnly : isData(connection.session),
dontGetRemoteStream: typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way',
dontAttachLocalStream: !!message.message.dontGetRemoteStream,
connectionDescription: message,
successCallback: function() {
// if its oneway----- todo: THIS SEEMS NOT IMPORTANT.
if (typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way') {
connection.addNewBroadcaster(message.sender, userPreferences);
}
if (!!connection.session.oneway || connection.direction === 'one-way' || isData(connection.session)) {
connection.addNewBroadcaster(message.sender, userPreferences);
}
}
};
connection.onNewParticipant(message.sender, userPreferences);
return;
}
if (message.message.shiftedModerationControl) {
connection.onShiftedModerationControl(message.sender, message.message.broadcasters);
return;
}
if (message.message.changedUUID) {
if (connection.peers[message.message.oldUUID]) {
connection.peers[message.message.newUUID] = connection.peers[message.message.oldUUID];
delete connection.peers[message.message.oldUUID];
}
}
if (message.message.userLeft) {
mPeer.onUserLeft(message.sender);
if (!!message.message.autoCloseEntireSession) {
connection.leave();
}
return;
}
mPeer.addNegotiatedMessage(message.message, message.sender);
}
window.addEventListener('beforeunload', function() {
connection.socket.emit('presence', {
userid: connection.userid,
isOnline: false
});
}, false);
}
// a simple function to make XMLHttpRequests
function xhr( url, callback, data ) {
// if( data ) console.log('[' + url + '] sending: ' + JSON.stringify( data ) );
if (!window.XMLHttpRequest || !window.JSON){
console.log( 'No JSON and/or XMLHttpRequest support' );
return;
}
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (callback && request.readyState == 4 && request.status == 200) {
// server MUST return JSON text
if( request.responseText != 'false' )
console.log('Logging non-false data [from ' + url + ']: ' + request.responseText + "[...data POST'ed: " + JSON.stringify( data ) + "]" );
callback(JSON.parse(request.responseText));
}
};
request.open( 'POST', url );
var formData = new FormData();
// you're passing "message" parameter
formData.append( 'message', data );
request.send(formData);
}
start-broadcast.php:
<?php
require( "connection.inc.php" );
if( isset( $_POST['message'] ) )
{
$data = json_decode( $_POST['message'] , true );
// Now, if someone initiates WebRTC session; you should make an XHR request to create a record in the room-table; and
// set "Owner-id" equals to that user's "user-id".
//{"message":{"eventName":"presence","data":{"userid":"winey","isOnline":true}},"sender":"winey"}
$query = " INSERT INTO active_broadcasts ( name ) VALUES ( '{$data['name']}' ) ";
if( $mysqli->query( $query ) )
{
$transport = json_encode( false );
exit( $transport );
}
else
exit( $mysqli->error );
}
else
exit( 'No data sent' );
?>
xhr-signalhandler-post.php:
<?php
require( "connection.inc.php" );
$response = array();
//{"message":{"eventName":"presence","data":{"userid":"winey","isOnline":true}},"sender":"winey"}
// var_dump( $_POST );
// exit;
if( isset( $_POST['message'] ) )
{
$query = " INSERT INTO webrtc-messages ( name ) VALUES ( '{$_POST['name']}' ) ";
if( $mysqli->query( $query ) )
{
$transport = json_encode( false );
exit( $transport );
}
else
exit( $mysqli->error );
// Now, if someone else joins the room; you can update above record; and append his "user-id" in the "Participants-id" column.
}
if( #$_POST["message"] = "undefined" )
$response = false;
$transport = json_encode( $response );
exit( $transport );
?>
xhr-signalhandler-get.php:
<?php
require( "connection.inc.php" );
$response = array();
// var_dump( $_POST );
if( isset( $_POST['message'] ) )
{
$query = "SELECT id , message , channel , `sender-id` FROM `webrtc-messages` ";
if( $mysqli->connect_errno )
exit ( "Failed to connect to MySQL: " . $mysqli->connect_error );
if( $res = $mysqli->query( $query ) )
{
if( $res->num_rows > 0 )
{
while( $value = mysqli_fetch_assoc( $res ) )
{
//
}
}
}
else
{
echo "<center class='text-danger'>Server error</center>";
exit( $mysqli->error );
}
}
if( #$_POST["message"] = "undefined" )
$response = false;
$transport = json_encode( $response );
exit( $transport );
?>

I've never played with WebRTC nor RTCMultiConnection but I think I understand where your problem comes from.
As you're using XHR, there is no direct connection between your client (web browser) and your server. So, there is no way for the server to push information to the client thus, the openSignalingChannel override will never be triggered.
The trick is to call a function on a regular basis to check the server status (aka. long polling).
If you check the documentation of RTCMultiConnection about the openSignalingChannel override ( http://www.rtcmulticonnection.org/docs/openSignalingChannel/#xhr-signaling ), you'll notice the use of repeatedlyCheck();. I think this is the missing piece of your puzzle.
Hope it helps.

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

Remote Video Element shows nothing in webrtc

I am new to WebRTC, I want to setup a video call by using web socket over node.js,I am Unable Display the Remote video screen but local video element works fine.
May be I am missing the flow which i could not figure it out.
I am posting my html code with java script here.
HTML Code
<!---display sharing screen--->
<div id="video_container" style="display:none;">
This Streams Remote Video
<video controls autoplay id="remotevideo"></video><br>
This Streams Local Video
<video controls autoplay id="local_video"></video>
</div>
The below is my javascript
var webrtc_capable = true;
var rtc_peer_connection = null;
var rtc_session_description = null;
var get_user_media = null;
var connect_stream_to_src = null;
var stun_server = "stun.l.google.com:19302";
if (navigator.getUserMedia) { // WebRTC 1.0 standard compliant browser
rtc_peer_connection = RTCPeerConnection;
rtc_session_description = RTCSessionDescription;
get_user_media = navigator.getUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.srcObject = media_stream;
media_element.play();
};
} else if (navigator.mozGetUserMedia) { // early firefox webrtc implementation
rtc_peer_connection = mozRTCPeerConnection;
rtc_session_description = mozRTCSessionDescription;
get_user_media = navigator.mozGetUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.mozSrcObject = media_stream;
media_element.play();
};
stun_server = "74.125.31.127:19302";
} else if (navigator.webkitGetUserMedia) { // early webkit webrtc implementation
rtc_peer_connection = webkitRTCPeerConnection;
rtc_session_description = RTCSessionDescription;
get_user_media = navigator.webkitGetUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.src = URL.createObjectURL(media_stream);
};
} else {
alert("This browser does not support WebRTC - visit WebRTC.org for more info");
webrtc_capable = false;
}
</script>
<!---Javascript for splitting screen--->
<script>
function splitScreen()
{
var z;
document.getElementById("chat").style.display="block";
z=document.getElementById("video_container");
z.className="videoContainer";
z.style.display="block";
}
var call_token; // unique token for this call
var signaling_server; // signaling server for this call
var local_peer_connection;
//function to establish webrtc connection
function start(){
peer_connection=new rtc_peer_connection({ // RTCPeerConnection configuration
"iceServers": [ // information about ice servers
{ "url": "stun:"+stun_server }, // stun server info
]
});
setup_video();
peer_connection.onicecandidate== function (ice_event) {
if (ice_event.candidate) {
signaling_server.send(
JSON.stringify({
token:call_token,
type: "new_ice_candidate",
candidate: ice_event.candidate ,
})
);
}
};
peer_connection.onaddstream=function(event){
//alert("remote video is getting called!!");
connect_stream_to_src(event.stream,document.getElementById("remotevideo"));
};
signaling_server = new WebSocket("ws://localhost:3455");
if (document.location.hash === "" || document.location.hash === undefined) { // you are the Caller
// create the unique token for this call
var token = Date.now()+"-"+Math.round(Math.random()*10000);
call_token = "#"+token;
// set location.hash to the unique token for this call
document.location.hash = token;
signaling_server.onopen = function() {
// setup caller signal handler
signaling_server.onmessage = caller_signal_handler;
// tell the signaling server you have joined the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"join",
})
);
}
document.title = "You are the Caller";
//document.getElementById("loading_state").innerHTML = "Ready for a call...ask your friend to visit:<br/><br/>"+document.location;
} else { // you have a hash fragment so you must be the Callee
// get the unique token for this call from location.hash
call_token = document.location.hash;
signaling_server.onopen = function() {
// setup caller signal handler
signaling_server.onmessage = callee_signal_handler;
// tell the signaling server you have joined the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"join",
})
);
// let the caller know you have arrived so they can start the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"callee_arrived",
})
);
}
document.title = "You are the Callee";
// document.getElementById("loading_state").innerHTML = "One moment please...connecting your call...";
}
// setup message bar handlers
document.getElementById("message_input").onkeydown = send_chat_message;
document.getElementById("message_input").onfocus = function() { this.value = ""; }
}
/* functions used above are defined below */
// handler to process new descriptions
function new_description_created(description) {
peer_connection.setLocalDescription(
description,
function () {
// connect_stream_to_src(event.stream,document.getElementById("remotevideo"));
signaling_server.send(
JSON.stringify({
token:call_token,
type:"new_description",
sdp:description
})
);
},
log_error
);
}
// handle signals as a caller
function caller_signal_handler(event) {
var signal = JSON.parse(event.data);
if (signal.type === "callee_arrived") {
peer_connection.createOffer(
new_description_created,
log_error
);
} else if (signal.type === "new_ice_candidate") {
peer_connection.addIceCandidate(
new RTCIceCandidate(signal.candidate)
);
} else if (signal.type === "new_description") {
peer_connection.setRemoteDescription(
new rtc_session_description(signal.sdp),
function () {
peer_connection.addStream(remotevideo);
connect_stream_to_src(event.stream, document.getElementById("remotevideo"));
if (peer_connection.remoteDescription.type == "answer") {
// extend with your own custom answer handling here
//connect_stream_to_src(remotevideo, document.getElementById("remotevideo"));
}
},
log_error
);
} else if (signal.type === "new_chat_message") {
add_chat_message(signal);
} else {
// extend with your own signal types here
}
}
// handle signals as a callee
function callee_signal_handler(event) {
var signal = JSON.parse(event.data);
if (signal.type === "new_ice_candidate") {
peer_connection.addIceCandidate(
new RTCIceCandidate(signal.candidate)
);
} else if (signal.type === "new_description") {
peer_connection.setRemoteDescription(
new rtc_session_description(signal.sdp),
function () {
if (peer_connection.remoteDescription.type == "offer") {
peer_connection.createAnswer(new_description_created, log_error);
connect_stream_to_src(event.stream, document.getElementById("remotevideo"));
}
},
log_error
);
} else if (signal.type === "new_chat_message") {
add_chat_message(signal);
}
}
// add new chat message to messages list
function add_chat_message(signal) {
var messages = document.getElementById("messages");
var user = signal.user || "them";
messages.innerHTML = user+": "+signal.message+"<br/>\n"+messages.innerHTML;
}
// send new chat message to the other browser
function send_chat_message(e) {
if (e.keyCode == 13)
{
var new_message = this.value;
this.value = "";
signaling_server.send(
JSON.stringify(
{
token:call_token,
type: "new_chat_message",
message: new_message
})
);
add_chat_message({ user: "you", message: new_message });
}
}
function setup_video()
{//alert("In setup_video function");
get_user_media({
"audio":true,
"video":true
},
function (local_stream) { // success callback
// display preview from the local camera & microphone using local <video> MediaElement
connect_stream_to_src(local_stream, document.getElementById("local_video"));
// add local camera stream to peer_connection ready to be sent to the remote peer
peer_connection.addStream(local_stream);
},
log_error
);
}
// generic error handler
function log_error(error) {
console.log(error);
}
Server.js
// useful libs
var http = require("http");
var fs=require("fs");
var websocket = require("websocket").server;
// general variables
var port = 3455;
var webrtc_clients = [];
var webrtc_discussions = {};
// web server functions
var http_server = http.createServer(function(request, response) {
var matches = undefined;
if (matches = request.url.match("^/images/(.*)")) {
var path = process.cwd()+"/images/"+matches[1];
fs.readFile(path, function(error, data) {
if (error) {
log_error(error);
} else {
response.end(data);
}
});
} else {
response.end(page);
}
});
http_server.listen(port, function() {
log_comment("server listening (port "+port+")");
});
var page = undefined;
fs.readFile("htmlfilename",function(error,data){
if(error){
log_comment(error);
}
else{
page=data;
}
});
// web socket functions
var websocket_server = new websocket({
httpServer: http_server
});
websocket_server.on("request", function(request) {
log_comment("new request ("+request.origin+")");
var connection = request.accept(null, request.origin);
log_comment("new connection ("+connection.remoteAddress+")");
webrtc_clients.push(connection);
connection.id = webrtc_clients.length-1;
connection.on("message", function(message) {
if (message.type === "utf8") {
log_comment("got message "+message.utf8Data);
var signal = undefined;
try { signal = JSON.parse(message.utf8Data); } catch(e) { };
if (signal) {
if (signal.type === "join" && signal.token !== undefined) {
try {
if (webrtc_discussions[signal.token] === undefined) {
webrtc_discussions[signal.token] = {};
}
} catch(e) { };
try {
webrtc_discussions[signal.token][connection.id] = true;
} catch(e) { };
} else if (signal.token !== undefined) {
try {
Object.keys(webrtc_discussions[signal.token]).forEach(function(id) {
if (id != connection.id) {
webrtc_clients[id].send(message.utf8Data, log_error);
}
});
} catch(e) { };
} else {
log_comment("invalid signal: "+message.utf8Data);
}
} else {
log_comment("invalid signal: "+message.utf8Data);
}
}
});
connection.on("close", function(connection) {
log_comment("connection closed ("+connection.remoteAddress+")");
Object.keys(webrtc_discussions).forEach(function(token) {
Object.keys(webrtc_discussions[token]).forEach(function(id) {
if (id === connection.id) {
delete webrtc_discussions[token][id];
}
});
});
});
});
// utility functions
function log_error(error) {
if (error !== "Connection closed" && error !== undefined) {
log_comment("ERROR: "+error);
}
}
function log_comment(comment) {
console.log((new Date())+" "+comment);
}

ajax send data based on checkbox value

I need to send ajax requests with checkbox values (on each click/check). I have three lists with checkboxes, each list filters the data returend from php (with mysql AND condition):
$('body').on('click', '.click, :checkbox, .pag_link', function() {
var self = this;
// radio buttons
if ($('#res_prop').is(':checked')) {
var use = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
var use = $('#com_prop').val();
}
else {
$('p.error').show();
die();
}
//checkboxes from each list have the same class, is this ok?
if ($(self).is(':checkbox')) {
$(self).on('change', function() {
if ($(self).prop('class') == 'filter1' || $('.filter1').is(':checked')) {
if ($('.filter1').is(':checked'))
var type = $(self).val(); // maybe should be an array
else var type = null;
} else var type = null;
if ($(self).prop('class') == 'filter2' || $('.filter2').is(':checked')) {
if ($('.filter2').is(':checked'))
var status = $(self).val(); // maybe should be an array
else var status = null;
} else var status = null;
if ($(self).prop('class') == 'filter3' || $('.filter3').is(':checked')) {
if ($('.filter3').is(':checked'))
var bhk = $(self).val(); // maybe should be an array
else var bhk = null;
} else var bhk = null;
});
}
else {
var type = status = bhk = null;
}
if ($(self).is('.pag_link')) {
if ($(self).text() == '«')
var page = (parseInt($('.active').text()) - 1);
else if ($(self).text() == '»')
var page = (parseInt($('.active').text()) + 1);
else
var page = parseInt($(self).text());
}
else {
var page = 1;
}
$.ajax({
method: 'POST',
url: '/search',
data: {
'do': getUrlParameter('do'),
'use': use,
'type': type,
'status': status,
'bhk': bhk,
'city': $('select[name="city"]').val(),
'zone': $('select[name="zone"]').val(),
'page': page
}
}).done(function(data) {
if ($( '#search' ).is(':visible'))
$( '#search' ).hide();
if ($(self).is(':checkbox')) {
alert('should work');
var new_content = $(data).find( '#scroll-to-list' );
$( '#scroll-to-list' ).replaceWith( new_content );
}
else {
var new_content = $(data).find( '#search-filters, #scroll-to-list' );
$( '#results' ).html( new_content );
$( 'html, body' ).animate({
scrollTop: $( '#scroll-to-list' ).offset().top
}, 1000);
}
});
});
I'm looking on each click/check to do the ajax request and print the new results (relying on server is performance-wise?). If checked, the variable gets the value and is sent, if unchecked the variable gets null. The search.php script handles the mysql Select query (with ifs adding the AND conditions to the query).
I just have 1 example in the db but the checkboxes script is not working (or the mysql select query is not including the and condition, i think the problem is in the jquery, the php script is fine).
$use = isset( $_POST['use'] ) ? (int) $_POST['use'] : ''; // int AJAX
$filter_type = isset( $_POST['type'] ) ? (int) $_POST['type'] : ''; // int AJAX
$filter_status = isset( $_POST['status'] ) ? (int) $_POST['status'] : ''; // int AJAX
$filter_bhk = isset( $_POST['bhk'] ) ? (int) $_POST['bhk'] : ''; // int AJAX
$filter_city = isset( $_POST['city'] ) ? (int) $_POST['city'] : 0; // int AJAX
$filter_zone = isset( $_POST['zone'] ) ? (int) $_POST['zone'] : 0; // int AJAX
$page_number = isset( $_POST['page'] ) ? (int) $_POST['page'] : ''; // int AJAX
if ($filter_type != NULL || $filter_type != '') {
$filter_type = 'AND t2.type = ' . $filter_type;
} else $filter_type = NULL;
if ($filter_status != NULL || $filter_status != '') {
$filter_status = 'AND t2.status = ' . $filter_status;
} else $filter_status = NULL;
if ($filter_bhk != NULL || $filter_bhk != '') {
$filter_bhk = 'AND t2.bhk = ' . $filter_bhk;
} else $filter_bhk = NULL;
if ($filter_city > 0) {
$filter_city = 'AND t2.city = ' . $filter_city;
$filter_zone = NULL;
if ($filter_zone > 0) {
$filter_zone = 'AND t2.zone = ' . $filter_zone;
}
} else $filter_city = $filter_zone = NULL;
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1 // not from get/post
INNER JOIN property t2 ON t2.id = t1.id
WHERE t2.use = ?
' . $filter_type
. $filter_status
. $filter_bhk
. $filter_city
. $filter_zone . '
LIMIT ?, ?')) {
$stmt->bind_param('iii', $use, $start, $limit);
$stmt->execute();
I just found this JQuery method .serialize()... and it changed my life :)
$('body').on('click', '.click, :checkbox, .pag_link', function() {
var self = this;
if (!$(':radio').is(':checked')) {
$('p.error').show();
die();
}
var data = $('input, select').serializeArray(),
mode = getUrlParameter('do'),
page = 1;
if ($(self).is('.pag_link')) {
if ($(self).text() == '«')
page = (parseInt($('.active').text()) - 1);
else if ($(self).text() == '»')
page = (parseInt($('.active').text()) + 1);
else
page = parseInt($(self).text());
}
data.push({ name : 'do', value : mode});
data.push({ name : 'page', value : page});
alert($.param(data));
$.ajax({
method: 'POST',
url: '/search',
data: $.param(data)
}).done(function (data) {
if ($( '#search' ).is(':visible'))
$( '#search' ).hide();
if ($(self).is(':checkbox')) {
var new_content = $(data).find( '#scroll-to-list' );
$( '#scroll-to-list' ).replaceWith( new_content );
}
else {
var new_content = $(data).find( '#search-filters, #scroll-to-list' );
$( '#results' ).html( new_content );
$( 'html, body' ).animate({
scrollTop: $( '#scroll-to-list' ).offset().top
}, 1000);
}
});
});
Hope it helps someone.

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

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