Jquery ajax function fails with no reason - javascript

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?

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

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.

how i must using if for this angularjs and php code

I want to make one if for doing if array result was success alart somethings in
this code: if( data.status == 'success'){ is not working!!
it was with one = but result of one = is alwase 200 , I want to check status array if was success alert ...
I testthis code: data.data.statusin other place with just one array and this code work but when i use data.data.status in bottom codes its not working !!
angularjs function code :
$scope.book = function(){
if( $scope.cabs[$scope.active_cab].intialkm >= $scope.trip_distance) {
$scope.trip_rate = $scope.cabs[$scope.active_cab].intailrate ;
}else{
var init_rate = $scope.cabs[$scope.active_cab].intailrate ;
var std_rate = ( $scope.trip_distance - $scope.cabs[$scope.active_cab].intialkm ) * $scope.cabs[$scope.active_cab].standardrate ;
$scope.trip_rate = round_num( parseFloat(init_rate) + parseFloat(std_rate) );
}
$rootScope.user_data = JSON.parse( localStorage.getItem('user_data') );
var link = 'book_cab';
var post_data = {
'user_name' : $rootScope.user_data.User_name,
'token' : $rootScope.user_data.token,
'transfertype' : "Point to Point Transfer" ,
'book_date' : $scope.book_date ,
'pickup_area' : $scope.start_box.location,
'drop_area' : $scope.end_box.location,
'taxi_type' : $scope.selected_cab.cartype,
'km' : $scope.trip_distance,
'amount' : $scope.trip_rate
}
WebService.show_loading();
var promise = WebService.send_data( link,post_data);
promise.then(function(data){
$ionicLoading.hide();
if( data.status == 'success'){
alertPopup = $ionicPopup.alert({
title: '<p class="text-center color-yellow">'+$filter('langTranslate')("SUCCESS",$rootScope.appConvertedLang['SUCCESS'])+'</p>',
template: '<p class="text-center color-gery">'+$scope.trip_distance+' KM</p>'+
'<p class="text-center color-gery"> ₹ '+$scope.trip_rate+'</p>'
});
animateMyPop();
}else{
window.alert(response.data);
window.alert(response.status);
}
});
}
php webservice :
public function book_cab(){
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$request->uneaque_id = 'CMC'.strtotime(date('m/d/Y H:i:s'));
$myDate = new DateTime();
$myDate->setTimestamp( strtotime( $request->book_date) );
$time = $myDate->format("H");
if( $time >= 22 || $time <= 6){
$request->timetype = 'night';
}else{
$request->timetype = 'day';
}
$request->book_date = $myDate->format("m/d/Y");
$request->pickup_time = $myDate->format("h:i a");
$request->token = $this->extract_token( $request->token );
var_dump($request );
$finresult = array( 'status' => 'success',
'message' => 'Successfully registered',
'code' => 'registered'
);
print json_encode($finresult);
$this->model_web_service->book($request);
}
and model_web_service:
function book( $request ){
$table = 'bookingdetails';
$insert_data = array(
'username' => $request->token,
'uneaque_id' => $request->uneaque_id,
'purpose' => "Point to Point Transfer",
'pickup_date' => $request->book_date,
'pickup_time' => $request->pickup_time,
'drop_area' => $request->drop_area,
'pickup_area' => $request->pickup_area,
'taxi_type' => $request->taxi_type,
'status' => "Booking",
// 'item_status' => "Pending",
'timetype' => $request->timetype,
'amount' => $request->amount,
'km' => $request->km
);
$this->insert_table($insert_data, $table);
}
i want to change if for read php status array (success)
plz help me for fixing this code

SyntaxError: Unexpected token l in ajax call

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

Categories

Resources