ajax send data based on checkbox value - javascript

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.

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

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

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.

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

Cordova/Phonegap calendar plugin iOS create event

I'm using Cordova/Phonegap plugin found here:
https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin
My app is an RSS feed that had different events everyday, I would like to change the javascript code so that the user is able to add to calendar and the function reads the title date at least.
In my main.js the function is:
function Calendar_Add(){
// prep some variables
var startDate = new Date("March 18, 2014 13:00:00");
var endDate = new Date("March 18, 2014 14:30:00");
var title = "Event Added!";
var location = "Home";
var notes = "Some notes about this event.";
var success = function(message) { alert("Success: " + JSON.stringify(message)); };
var error = function(message) { alert("Error: " + message); };
// create
window.plugins.calendar.createEventWithCalendar(title,location,notes,startDate,endDate,success,error);
}
This is creating an event but again I am having trouble making the variables. This is my full javascript page of what I have tried:
//jQuery get target page
function IE_navigate(index) {
Bindex = index;
$.mobile.changePage('#eventPage', 'slidefade');
$.each(data, function(i,item){
if (i == Bindex) {
//Clear if page was previously populated
//Populate page
$('#page-title').html(item.title + "<br />");
$('#page-region').html(item.Region + "<br />");
$('#page-content').html(item.fullInfo + "<br />");
/*
startDate = new Date(item.Date);
endDate = new Date(item.Date);
title = item.title;
place = item.Region;
*/
$(this).ready(function(e) {
$('#page-content').on('click','a', function(e){
e.preventDefault();
currentPage = $(this).attr('href');
window.open(currentPage, '_system', 'location=yes')
});
});
// return false;
return false
}
});
};
var Aindex = "";
var Bindex = "";
var data = [];
$(function () { Load_Content() });
function Load_Content() {
$('#feed').empty();
data = [];
$.ajax({
type: 'GET',
url:'http://www.e-grid.net/BayAreaTech/wp-rss2.php?cat=1',
dataType: 'xml',
success: function (xml) {
$('#header-title').html("e-Grid Mobile");
$(xml).find("item:lt(60)").each(function () {
var dateText = $(this).find("Date").text().toString();
var eventDate = moment(dateText,"YYYY-MM-DD");
var title = $(this).find("title").text();
var region = dateText.substr(8).toUpperCase();
if (region == "SCV") { region = "Santa Clara Valley";}
if (region == "OEB") { region = "Oakland/East Bay";}
if (region == "SF") { region = "San Francisco";}
if (region == "ALL") { region = "All regions";}
var description = $(this).find("description").text();
var infoDisplay = description.substr(0, description.indexOf(",")+120) + "..."; //Parsed DATE from description
var fullDescription = $(this).find('encoded').text();
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var displayTitle = title;
var item = {title: displayTitle,
link: linkUrl,
infoDescription: infoDisplay,
Date: new Date(eventDate),
Region: region,
fullInfo: fullDescription,}
var now = moment().subtract('days', 1);
if (item.Date >= now){ data.push(item); }
});
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a<b ? -1 : a>b ? 1 : 0;
});
if (data.length > 0) {
$.each(data, function (index, item) {
Aindex = data.indexOf(this)
var h_feedList = '<li';
h_feedList += '><a href="#" onclick="IE_navigate(' + Aindex + ')" target="_blank">';
h_feedList += '<h3>'; // Start Title Text
h_feedList += item.title; // Title Text
h_feedList += '</h3><p>'; // End the title text - start the description text
h_feedList += item.infoDescription; // Description text
h_feedList += '</p>'; // End description text
h_feedList += '</a>'; // End list link
h_feedList += '</li>'; // End List Item
$('#feed').append(h_feedList);
});
}
else
{
var message = "No upcoming events within your selection; check back soon!";
$('#feed').append('<h3>' + message + '</h3>');
}
}
});
};
function next_event() {
Bindex++;
if (Bindex > data.length){ Bindex = 0; }
$('#page-title').html(data[Bindex].title);
$('#page-region').html(data[Bindex].Region);
$('#page-content').html(data[Bindex].fullInfo);
startDate = new Date(data[Bindex].Date);
endDate = new Date(data[Bindex].Date);
title = data[Bindex].title;
place = data[Bindex].Region;
}
function previous_event() {
Bindex--;
if (Bindex <= 0){ Bindex = data.length; }
$('#page-title').html(data[Bindex].title);
$('#page-region').html(data[Bindex].Region);
$('#page-content').html(data[Bindex].fullInfo);
startDate = new Date(data[Bindex].Date);
endDate = new Date(data[Bindex].Date);
title = data[Bindex].title;
place = data[Bindex].Region;
}
$(document).ajaxStart(function() {
$.mobile.loading('show', {text: 'Loading BayArea Events...', textVisible: true, textonly: true});
});
$(document).ajaxStop(function() {
$.mobile.loading('hide');
});
$( document ).on( "pagecreate", "#home", function() {
$( document ).on( "swipeleft swiperight", "#home", function( e ) {
// We check if there is no open panel on the page because otherwise
// a swipe to close the left panel would also open the right panel (and v.v.).
// We do this by checking the data that the framework stores on the page element (panel: open).
if ( $( ".ui-page-active" ).jqmData( "panel" ) !== "open" ) {
if ( e.type === "swipeleft" ) {
$( "#settingspanel" ).panel( "open" );
} else if ( e.type === "swiperight" ) {
$( "#fieldpanel" ).panel( "open" );
}
}
});
});
$( document ).on( "pagecreate", "#eventPage", function() {
$( document ).on( "swipeleft swiperight", "#eventPage", function( e ) {
if ( e.type === "swipeleft" ) {
next_event();
} else if ( e.type === "swiperight" ) {
previous_event();
}
});
});
function Calendar_Add(){
// prep some variables
var startDate = new Date(item.Date);
var endDate = new Date(item.Date);
var title = item.title;
var location = item.region;
var notes = "";
var success = function(message) { alert("Success: " + JSON.stringify(message)); };
var error = function(message) { alert("Error: " + message); };
// create
window.plugins.calendar.createEventWithCalendar(title,location,notes,startDate,endDate,success,error);
}
The function createEventWithCalendar does not exist for the Calendar plugin. You should use createEvent with the same parameters.
You would probably have been warned by a Javascript error if you had a function like this somewhere:
window.onerror = function(a,b,c) {
alert(a);
alert(b);
alert(c);
}
Hope this helps you getting my plugin to work,
Eddy

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