Can not deserialize instance of String out of START_OBJECT token - php

I've gone through the other answers to this question, but no one seems to be able to apply it universally. Other questions just go unanswered.
Obviously, I'm getting "Can not deserialize instance of String out of START_OBJECT token." in my console. I believe it happens when I attempt to stringify(response) from my websocketdata.
Here is the code.
<?php /**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
*/ ?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<script type="text/javascript"
src='http://martialparks.com/wp-content/themes/js/gamesparks-rt.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/gamesparks.js'></script>
<script type='text/javascript'
src='http://martialparks.com/wp-content/themes/js/gamesparks-functions.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/hmac-sha256.js'></script>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php
wp_head();
?>
</head>
<body <?php body_class() ?>>
<body onload="init()">
<!--Start Header Wrapper-->
<div class="header_wrapper">
<div class="header">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<div class="logo"> <a href="<?php echo esc_url(home_url()); ?>"><img src="<?php if (business_directory_get_option('business_directory_logo') != '') { ?><?php echo esc_url(business_directory_get_option('business_directory_logo')); ?><?php
} else {
echo esc_url(get_template_directory_uri() . '/images/logo.png');
}
?>" alt="<?php bloginfo('name'); ?>" /></a></div>
</div>
<div class="clear"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<div class="clear"></div>
<!--Start Menu Wrapper-->
<div class="menu_wrapper">
<div class="top_arc"></div>
<div class="menu-container">
<div class="container_24">
<div class="grid_24">
<?php business_directory_nav(); ?>
</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="bottom_arc"></div>
</div>
<!--End Container-->
<div class="clear"></div>
</div>
<!--End Header Wrapper-->
<div class="clear"></div>
<div class="wrapper">
<!--Start Container-->
<div class="container_24">
<div class="grid_24">
<br/>
<br/>
<br/>
<input id="apiKey" type="hidden" value="A319082inSk2"/>
<input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
<label for="apiCredential">Api Credential</label><input id="apiCredential"/>
<label for="username">User Name</label><input id="username"/>
<label for="password">Password</label><input id="password"/>
<button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
<button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>
<button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
<button onClick='customEvent()'>Custom Event</button>
<button onClick='testRT()'>Test RT</button>
<i>Special thanks to the awesome team at GameSparks!</i>
<div id="messages"></div>
<br/>
<br/>
User Name
<div id="displayName" style="color: blue;"></div>
Coins
<div id="Coins" style="color: red;"></div>
Exp
<div id="Exp" style="color: green;"></div>
Leader Points
<div id="LeadP" style="color: darkgreen;"></div>
Hero Points
<div id="HeroP" style="color: purple;"></div>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
<h3>Find a Park</h3>
<div id="map"></div>
<script>
function initMap() {
var Velocity = {lat: 38.308101, lng: -85.815464};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: Velocity
});
var marker = new google.maps.Marker({
position: Velocity,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDSHCinT3IVWFCLUudbsMZV6644GNrGiwc&callback=initMap">
</script>
<script type="text/javascript">
//Create a gamesparks object to be used
var gamesparks = new GameSparks();
//Initialse the SDK
function init() {
gamesparks.initPreview({
key: document.getElementById('apiKey').value,
secret: document.getElementById('apiSecret').value,
credential: document.getElementById('apiCredential').value,
onNonce: onNonce,
onInit: onInit,
onMessage: onMessage,
logger: console.log,
});
}
function accountDetailsResponseCreator() {
var response = {
displayName: 'A User',
currencies: {Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p'}
}
accountDetailsResponse(response)
}
//Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
function onNonce(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
}
//Callback to handle when the SDK is initialised and ready to go
function onInit() {
console.log("Initialised");
}
//Callback to handle async messages from the gamesparks platform
function onMessage(message) {
console.log("onMessage");
}
//Response handler examples
function registerResponse(response) {
console.log(JSON.stringify(response));
}
function loginResponse(response) {
console.log(JSON.stringify(response));
}
function accountDetailsResponse(response) {
console.log (JSON.stringify(response));//logs the string to console
document.getElementById("displayName").innerHTML = (response.displayName);
document.getElementById("Coins").innerHTML = (response.currencies.Coins);
document.getElementById("Exp").innerHTML = (response.currencies.Exp);
document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string. I've tried doing each line with semicolons at the end, and all in a group with commas separating them. Both just give me the first variable and delete the rest.
}
function customEvent() {
gamesparks.sendWithData(
"LogEventRequest",
{
eventKey: "FIRST_EVENT",
NUMBER_ATTR: 123,
STRING_ATTR: "this is a string",
JSON_ATTR: {key1: 12, key2: "abc"}
},
function (response) {
console.log(JSON.stringify(response));
}
);
}
var apiKey = "2974660weiMa";
var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
var myTimer = null;
var myRTSession = function () {
};
var numCycles = 0;
myRTSession.started = false;
myRTSession.onPlayerConnectCB = null;
myRTSession.onPlayerDisconnectCB = null;
myRTSession.onReadyCB = null;
myRTSession.onPacketCB = null;
myRTSession.session = null;
myRTSession.start = function (connectToken, host, port) {
var index = host.indexOf(":");
var theHost;
if (index > 0) {
theHost = host.slice(0, index);
} else {
theHost = host;
}
console.log(theHost + " : " + port);
myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
if (myRTSession.session != null) {
myRTSession.started = true;
myRTSession.session.start();
} else {
myRTSession.started = false;
}
};
myRTSession.stop = function () {
myRTSession.started = false;
if (myRTSession.session != null) {
myRTSession.session.stop();
}
};
myRTSession.log = function (message) {
var peers = "|";
for (var k in myRTSession.session.activePeers) {
peers = peers + myRTSession.session.activePeers[k] + "|";
}
console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
};
myRTSession.onPlayerConnect = function (peerId) {
myRTSession.log(" OnPlayerConnect:" + peerId);
if (myRTSession.onPlayerConnectCB != null) {
myRTSession.onPlayerConnectCB(peerId);
}
};
myRTSession.onPlayerDisconnect = function (peerId) {
myRTSession.log(" OnPlayerDisconnect:" + peerId);
if (myRTSession.onPlayerDisconnectCB != null) {
myRTSession.onPlayerDisconnectCB(peerId);
}
};
myRTSession.onReady = function (ready) {
myRTSession.log(" OnReady:" + ready.toString());
if (myRTSession.onReadyCB != null) {
myRTSession.onReadyCB(ready);
}
};
myRTSession.onPacket = function (packet) {
myRTSession.log(" OnPacket:" + packet.toString());
if (myRTSession.onPacketCB != null) {
myRTSession.onPacketCB(packet);
}
};
function testRT() {
myRTSession.stop();
gamesparks.initPreview({
key: apiKey,
secret: apiSecret,
credential: "",
onNonce: onNonceRT,
onInit: onInitRT,
onMessage: onMessageRT,
logger: console.log,
});
}
function onNonceRT(nonce) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
}
function onInitRT() {
console.log("Initialised");
gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
sendMatchmakingRequest();
}
});
}
//Callback to handle async messages from the gamesparks platform
function onMessageRT(message) {
//console.log("message " + JSON.stringify(message));
if (message["#class"] === ".MatchFoundMessage") {
var accessToken = message["accessToken"];
var host = message["host"];
var port = message["port"];
myRTSession.stop();
if (myTimer) {
clearTimeout(myTimer);
}
myTimer = setInterval(mainRTLoop, 10);
myRTSession.start(accessToken, host, port);
} else if (message["#class"] === ".MatchNotFoundMessage") {
console.log("MATCH NOT FOUND");
sendMatchmakingRequest();
}
}
function sendMatchmakingRequest() {
gamesparks.sendWithData("MatchmakingRequest",
{
skill: 1,
matchShortCode: "Match_STD"
},
function (response) {
if (response.error) {
console.error(JSON.stringify(response.error));
} else {
console.log("Match OK...");
}
}
);
}
function mainRTLoop() {
if (myRTSession.started) {
myRTSession.session.update();
var data = RTData.get();
data.setLong(1, numCycles);
myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);
numCycles++;
}
}
</script>
</body>
</html>
For the life of me, I have no idea what is happening or how to fix it. The problem pops up when I activate a button that references line 173
function loginResponse(response) {
console.log(JSON.stringify(response));
}
But don't let that affect your impartiality. I compared this code to earlier versions of the code I have and could not identify a change in any of my functions.

Well, bottom line is this: When you are an idiot, don't post questions to stackoverflow. No one will respond. Not because they are mean, but because learning the basics is important.
So the problem originated for me in the top of my code with this:
<button onClick='gamesparks.authenticationRequest(username, password, loginResponse)'>Login</button>
Weird, right? Not really. What had done was try to alter the input for the authentication request to match my html element inputs (see where my elements are labeled as username and password?) It didn't work, and I obviously just shelved that and moved on...and forgot. What I did was change "username" to "testuser". This matched the value I was trying to authenticate. Now, my baby is returning values on my testuser, and running like a dream.
Thanks for the tough love, stackoverflow.

Related

Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.<anonymous>

I had look to the similar question and its doesn't solve my problem
I want to create file multiple upload system with progressbar using php
and i have this error
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.<anonymous>
my code is
<?php
error_reporting(0);
$state="white";
$count=0;
if(isset($_GET["state"])){
$state=$_GET["state"];
$count=$_GET["count"];
}
?>
<html >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="كتابك القريب,أدهم شرقاوي,روايات, كتب pdf,تحميل كتب,كتب دراسية,pdf,books">
<meta name="google-site-verification" content="ieyWI-BKgki1_LGBMFqdFYkGyEeHlMSEAodDuxKcN7A" />
<link rel="stylesheet" href="controls.css">
<!--
-->
<style>
.bar
{
position: absolute;
height: 15px;
background-color: rgb(27, 26, 26);
box-shadow:inset 1px 1px 1px 1px #fff5;
width: 80%;
bottom: 45px;
border-radius:15px ;
}
.pbar
{
position: absolute;
height: 15px;
background-color:#941ab4;
width: 0;
border-radius:15px ;
}
</style>
<title>كتابك القريب</title>
<script src="jquery.js"></script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
var Vcount= <?php echo $count; ?>;
if (state=="succsses") {$(document).ready(function() { $(".succsses").css("display","block");}); }
</script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
if (state=="error") { $(document).ready(function() { $(".error").css("display","block"); }); }
</script>
<script>
$(document).ready(function() {
$(".x").click(function() {
$(".succsses").css("display","none");
});
});
$(document).ready(function() {
$(".x").click(function() {
$(".error").css("display","none");
});
});
</script>
</head>
<body>
<div class="succsses" id="succsses" >
<p><?php if ($state=="succsses") { echo"تم تحميل ($count) ملفات بنجاح" ;}?></p>
<span class="x">x</span>
</div>
<div class="error" id="error" >
<p><?php if ($state=="error") { echo"فشل التحميل " ;}?></p>
<span class="x">x</span>
</div>
<div class="login-form">
<img src="https://yourclosebook.com/res/logos/ryhan.png" alt="" class="ava">
<form action="upload.php" method="post" enctype="multipart/form-data" id="frm">
<input type="email" name="email" id="" placeholder="email (اختياري)">
<input type="file" name="file[]" id="costum-file" accept="application/pdf,application/msword,.docx" multiple >
<input type="submit" value="تحميل" id="upload">
</form>
<div class="bar">
<span class="pbar" id="pb"></span> <span class="ptext " id="pt"></span>
</div>
<P> (*.pdf,*.docx,*.doc,*.ppt,*pptx)يمكنكم تحميل ملفات من الصيغ المدرجة جانبا</P>
<h3 id="friend"> <a href="https://www.yourclosebook.com" target="_blank" > كتابك القريب !</a> صديقك المقرب</h3>
</div>
<style>
</style>
<script src="upload.js"></script>
<script>
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
</body>
</html>
uploade.php
<?php
require_once("conn.php");
header("Content-Type:application/json");
$err="";
$UPLOADED=NULL;
$count=0;
$i=0;
$succeded=[];
$faild=[];
for ($i; $i <count($_FILES['file']['name']) ; $i++) {
$target_path="uploads/";
$file=$_FILES['file']['name'][$i];
$file_temp=$_FILES['file']['tmp_name'][$i];
$fileSize =$_FILES['file']['size'][$i];
$fileError =$_FILES['file']['error'][$i];
$fileType =$_FILES['file']['type'][$i];
$fileEXT =explode('.',$file);
$fileRealExt=strtolower(end($fileEXT));
$target_path= $target_path.$file;
$allowed =array('pdf','doc','docx');
if (!empty($file)) {
if (in_array($fileRealExt,$allowed)) {
if ($fileError===0) {
$helpTimes=1;
$email=$_POST['email'];
$email= $db->real_escape_string($email);
$file= $db->real_escape_string($file);
$UPLOADED=move_uploaded_file($file_temp,$target_path);
if ($UPLOADED) {
$insert = $db->query("INSERT INTO user_uploads(email,filepath,upload_time,help_times) VALUES('".$email."','".$file."',NOW(),'".$helpTimes."')");
$count=$i+1;
$succeded=array(
'name'=>$name,
'file'=>$file
);
}else{
$faild= array('name' => $name);
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
$err= "حدث خطأ غير متوقع";
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
echo header("Location:index.php?state=error&error=notAcceptedFileFormat");
}
}else{
$err=" يجب اختيار ملف واحد على الاقل";
echo header("Location:index.php?state=error&error=empty");
}
// --------------------
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
}
}
echo $err;
if ($count>0) {
//index.php
echo header("Location:index.php?state=succsses&count=$count");
if (!empty($_POST['email'])) {
$email=$_POST['email'];
$from = "MIME-Version: 1.0" . "\r\n";
$from .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$from .= 'From: YOUR CLOSE BOOK TEAM <contact#yourclosebook.com>' . "\r\n";
$s=" رسالة شكر";
$messagge="<H1>باسمنا نحن فريق موقع كتابك القريب نقد لكم فائق الشكر لاجل مساعدتنا بتقديم كتبكم الثمينة</H1>";
$mail= mail($email,$s,$messagge,$from);
if (!$mail) {
echo"email sending error";
}
else{
echo"check your email";
}
}
}else{
echo header("Location:index.php?state=error");
}
upload.js
var app=app ||{};
(function(o){
"use strict";
var ajax,getFormData,setProgress;
ajax =function (data)
{
var xhr= new XMLHttpRequest(),uploaded;
xhr.addEventListener('readystatechange',function()
{
//readyState===4 => done
if (this.readyState===4)
{
/*
status===200=> ok*/
if (this.status===200)
{
uploaded= JSON.parse(this.response);
if (typeof o.options.finished==='function')
{
o.options.finished(uploaded);
}
}
else
{
if (typeof o.options.error==='function')
{
o.options.error();
}
}
}
});
xhr.upload.addEventListener('progress',function(event)
{
var percent;//%
if (event.lengthComputable===true)
{
percent= Math.round((event.loaded/event.total)/100);
setProgress(percent);
}
});
xhr.open('post',o.options.processor);
xhr.send(data);
};
getFormData =function (source) {
var data = new FormData(),i;
for ( i = 0; i < source.length; i++) {
data.append('costum-file[]',source[i]);
}
data.append('ajax',true);
return data;
};
setProgress =function (value) {
if (o.options.porgressBar !== undefined) {
o.options.porgressBar.style.width=value?value+'%':0;
}
};
o.uploader=function (options) {
o.options=options;
if (o.options.files!==undefined) {
ajax(getFormData(o.options.files.files));
}
}
}(app));
There are some issues with your code:
In your main file you have an email element but in your upload.js file you are not adding it to your FormDara object. So in your uploade.php file you don't have access to it and $email=$_POST['email']; will throw an error
In your upload.js you are naming your file objects costum-file fun in your upload.php you are looking for file objects with the name of file. These two should have same name.
echo header("Location:index.php"); is incorrect and you should only use header("Location:index.php");
If you are calling upload.php file via ajax request then you can not do php redirect(header("Location:index.php");). What you should do is to return some json response and then pars it in your main file JavaScript and show relevant messages(Error or success)
So to sum them up what you need to change to fix the error you are getting is(I'm just highlighting the changes and not the whole code):
main(index.php?) file
You need to provide an id for the email element:
<input type="email" name="email" id="email" placeholder="email (اختياري)">
You need to add this email element to your JavaScript call
<script type="text/javascript">
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
var eml = document.getElementById('email');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
email:eml,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
upload.js
You need to change the file element to file and also add the email element in the FormData object
getFormData =function (source) {
var data = new FormData(), i;
for ( i = 0; i < source.length; i++) {
data.append('file[]',source[i]);
}
data.append('email', o.options.email.value);
data.append('ajax', true);
return data;
};
And finally in your upload.php file change all the echo header("Location:index.php") instances with a json encoded string like what you have here:
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
With proper response which then you can parse in your index.php file.
Please give it a try and see if it fixes your issue.

SEE server not working with join room at screen sharing RTCMultiConnection

I am creating screen share with SEE server, everything is working properly
when the user opens a room for screen share he enters a room
But when the second user wants to turn it on room nothing happens
I checked and error gives no room found
How I can resolve that?
(i test script with socket.io server it's working properly)
my front end code :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>SSE+PHP Signaling 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>
<header>
<a class="logo" href="/"><img src="logo.png" alt="RTCMultiConnection"></a>
Menu<img src="menu-icon.png" alt="Menu">
<nav>
<li>
Home
</li>
<li>
Demos
</li>
<li>
Getting Started
</li>
<li>
FAQ
</li>
<li>
YouTube
</li>
<li>
Wiki
</li>
<li>
Github
</li>
</nav>
</header>
<h1>
SSE+PHP Signaling using RTCMultiConnection
<p class="no-mobile">This demo is using SSE (Server Sent Events) to setup WebRTC one-to-one connection. Check PHP Source Codes</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">Open or Join 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="videos-container"></div>
</section>
<script src="adapter.js"></script>
<script src="RTCMultiConnection.js"></script>
<script src="SSEConnection.js"></script>
<link rel="stylesheet" href="getHTMLMediaElement.css">
<script src="getHTMLMediaElement.js"></script>
<script>
window.enableAdapter = true; // enable adapter.js
// ......................................................
// .......................UI Code........................
// ......................................................
document.getElementById('open-room').onclick = function() {
disableInputButtons();
connection.open(document.getElementById('room-id').value, function() {
showRoomURL(connection.sessionid);
});
};
document.getElementById('join-room').onclick = function() {
disableInputButtons();
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: false,
OfferToReceiveVideo: true
};
console.log(document.getElementById('room-id').value);
connection.join(document.getElementById('room-id').value);
};
document.getElementById('open-or-join-room').onclick = function() {
disableInputButtons();
// connection.openOrJoin(document.getElementById('room-id').value);
connection.checkPresence(document.getElementById('room-id').value, function(isRoomExist, roomid) {
console.info('checkPresence', isRoomExist, roomid);
if(isRoomExist) {
connection.join(roomid);
}
else {
connection.open(roomid);
}
});
};
// ......................................................
// ..................RTCMultiConnection Code.............
// ......................................................
var connection = new RTCMultiConnection();
// Using SSE (Server Sent Events) for signaling
connection.socketURL = 'https://127.0.0.1/see/';
connection.setCustomSocketHandler(SSEConnection);
connection.session = {
screen: true,
oneway: true
};
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
// https://www.rtcmulticonnection.org/docs/iceServers/
// use your own TURN-server here!
connection.iceServers = [{
'urls': [
'stun:stun.l.google.com:19302',
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
'stun:stun.l.google.com:19302?transport=udp',
]
}];
connection.videosContainer = document.getElementById('videos-container');
connection.onstream = function(event) {
event.mediaElement.id = event.streamid;
connection.videosContainer.appendChild(event.mediaElement);
if (event.type === 'remote') {
connection.socket.close(); // release SSE connection
}
};
connection.onstreamended = function(event) {
var mediaElement = document.getElementById(event.streamid);
if (mediaElement && mediaElement.parentNode) {
mediaElement.parentNode.removeChild(mediaElement);
}
};
function disableInputButtons() {
document.getElementById('open-room').disabled = true;
document.getElementById('join-room').disabled = true;
document.getElementById('open-or-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
connection.join(roomid);
disableInputButtons();
}
</script>
<footer>
<small id="send-message"></small>
</footer>
</body>
</html>
PHP side :
https://github.com/muaz-khan/RTCMultiConnection/tree/master/demos/SSEConnection

Ajax request to the same PHP page gives no errors but doesn't work

I am making a product displaying page of an ecommerce website. The products are to be filtered by brands on the basis of brands that are checked by the customer. For this I have used an ajax request everytime a brand is checked. The problem is that the page cannot receive the get variables that i am sending to the same page. The ajax request is not giving any errors and also the chrome debugger side is also not showing any error at all. This is the page:
snapshot of the products page
And this is the code of the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<?php
session_start();
include('includes/pdo_connect.php');
include('includes/pdo_functions.php');
$logged_in;
$user_first_name;
if(isset($_SESSION['user'])){ //Determining if the user is logged in or not.
if($_SESSION['user']=='user'){
$user_id = $_SESSION['user_id'];
global $logged_in;
$logged_in = true;
global $user_first_name;
$user_first_name = $_SESSION['user_first_name'];
}
} else {
$_SESSION['user'] = 'guest';
$user_id = $_SERVER['REMOTE_ADDR'];
}
$cat;
if(isset($_GET['cat'])){
global $cat;
$cat = $_GET['cat'];
}
include('includes/logged_in.php');
if(isset($_GET['brand_list'])){
$brand_list = $_GET['brand_list'];
} else {
echo "<script>alert('value not received');</script>";
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="styles/list_style.css?<?php echo time(); ?>">
<link rel="stylesheet" type="text/css" href="styles/thickbox.css" media="screen">
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<?php
$where = array();
if(!empty($brand_list)){
echo "ajax working";
if(strpos($brand_list, ',')!==false){
$brand_choices = explode(',', $brand_list);
$barray = array();
foreach($brand_choices as $value) {
$barray[] = "brand_id = $value";
}
$where[] = '('.implode(' OR ', $barray).')';
} else {
$where[] = '(brand_id= '.$brand_list.')';
}
} else {
//echo "ajax not working ";
}
$w = implode(' AND ', $where);
$w = "where product_cat=$cat ".$w;
$filter_query = "select * from products $w ";
echo "filter query: ".$filter_query;
$first_load = 'filter';
function show_filtered(){
//echo "<script>alert('filter query working');</script>";
global $filter_query;
global $con;
global $brand_name;
try{
$stmt = $con->prepare($filter_query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $data) {
$product_id = $data['product_id'];
$product_cat = $data['product_cat'];
$product_brand = $data['product_brand'];
$product_title = $data['product_title'];
$product_price = $data['product_price'];
$product_desc = $data['product_desc'];
$product_image = $data['product_image'];
echo "
<div class='product_container $brand_name'>
<a href='details.php?pid=".$product_id."' alt='".$product_title."'>
<div class='img_div'>
<img src='admin/product_images/".$product_image."?".time()."' alt='".$product_title."'/>
</div>
<div class='index_product_desc'>".$product_title."</div>
<div class='index_product_price'>₹".$product_price."</div>
</a>
</div>
";
}
} catch(PDOException $e){
echo "Error in show_list(): ".$e->getMessage();
}
}
function show_brands(){
global $con;
global $cat;
global $brand_name;
try{
$query = "select * from cat_brand where cat_id = $cat";
$stmt = $con->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
//$brand = array();
foreach ($result as $data) {
$brand_id = $data['brand_id'];
//echo "<script>alert('$brand_id');</script>";
$query1 = "select * from brands where brand_id = $brand_id";
$stmt1 = $con->prepare($query1);
$stmt1->execute();
$result1 = $stmt1->fetchAll();
echo "<ul>";
foreach ($result1 as $data1) {
$brand_name = $data1['brand_title'];
echo "<li><input type='checkbox' value='$brand_id' id='$brand_name' class='brand_check' name='brandchoice'> $brand_name</li>";
}
echo "</ul>";
}
} catch(PDOException $e){
echo "Error in show_brands: ".$e->getMessage();
}
}
function show_price(){
}
?>
</head>
<body>
<div class="wrapper">
<header>
<div class="home_logo">
<a href="index.php">
<img src="images/skyshop_sumopaint.png" alt="Site Home">
</a>
</div>
<div class="login">
<?php user();?> |
<?php login_status(); ?>
</div>
<div class="form">
<form method="get" target="" name="searchbar_form">
<input type="text" name="searchbar" id="searchbar">
<input type="submit" id="search_button" value="Search">
</form>
</div>
</header>
<div class="menubar">
<div class="dropdown">
<button onclick="dropdownToggle()" class="dropdown-button">Shop By Category</button>
<ul class="dropdown-content" id="dropdownContent">
Categories
<?php getcats(); ?>
</ul>
</div>
<div class="menubar-div">
<ul class="menu-items">
<?php getcats(); ?>
</ul>
</div>
<div class="cart">
Cart (0)
</div>
</div>
<div class="content">
<div class="nav">
</div>
<div class="list_wrapper">
<!--/////////////////////////////////////////////// Filter div /////////////////////////////////////////////////////-->
<div class="filter">
<span class="filter_heading">Select Brands</span>
<a href="" class="clear" id="clear_brands">Clear<a>
<div class="brand_div">
<?php
show_brands();
?>
</div>
<div class="price_div">
</div>
</div>
<!--/////////////////////////////////////////////// List div ///////////////////////////////////////////////////////-->
<div class="list">
<div class="loading">
<img src="images/loadingAnimation.gif">
</div>
<?php
show_filtered();
?>
</div>
</div>
<div class="footer">
FOOTER
</div>
</div>
</div>
<?php
?>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
</script>
</body>
</html>
I am using alert() in the beforeSend in the ajax request and it returns the correct data as expected. But the PHP section of the page does not received the values. There are no errors on the PHP side or the browser debug window.
I checked your code line by line. and figure out that you have code for ajax inside the function named "filter" function filter().
Now you are calling this filter function on by onclick event of the element with id clear_brands
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
and by this code i came to know that at the end your ajax call is not being made because you click event was not triggered,
So either you should trigger this event on your document get ready or you have to do it by clicking on that element.
Just think about the flow once.
i was testing your script in my local and
with some modification i have made it working.
did some changes like
at the end of the script i just putted this code below.
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
And ajax call was executed..
check out my entire HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<a href="" class="clear" id="clear_brands">Clear<a>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
</script>
</body>
</html>
In Chrome do Ctrl+Shift+I to open Developer Tools and check Console for errors and Network tab to see if the data is passed in request.

How to generate Dynamic HTML body in c#

I am trying to generate shopping kart kind of application, but i found similar kind of functionality. in PHP. in this they are fetching some data from db, and binding to div in PHP code.Similar kind of functionality
<BODY>
<div id="product-grid">
<div class="txt-heading">Products</div>
<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
?>
<div class="product-item" data-name="<?php echo $product_array[$key]["name"]; ?>" data-price="<?php echo "$".$product_array[$key]["price"]; ?>">
<div class="product-image"><img class="draggable" src="<?php echo $product_array[$key]["image"]; ?>" id="<?php echo $product_array[$key]["code"]; ?>"></div>
<div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
</div>
<?php
}
}
?>
</div>
<div class="clear-float"></div>
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart <a id="btnEmpty" onClick="cartAction('empty','');">Empty Cart</a></div>
<div id="cart-item"></div>
</div>
<script>
$(document).ready(function () {
cartAction('', '');
})
</script>
</BODY>
.txt-heading{padding: 5px 10px;font-size:1.1em;font-weight:bold;color:#999;}
a.btnRemoveAction{color:#D60202;border:0;padding:2px 10px;font-size:0.9em;}
#btnEmpty{background-color:#E27E7E;border:0;padding:2px 10px;color:#333; font-size:0.8em;font-weight:normal;float:right;text-decoration:none;cursor:pointer;}
#shopping-cart .txt-heading{border-top: #79b946 2px solid;margin:30px 0px;background-color: #D3F5B8;}
#cart-item{height: 200px;background-color: #FFFFFF;}
#product-grid .txt-heading{border-top: #F08426 2px solid;background-color: #FFD0A6;}
.product-item { float:left; background:#F0F0F0; margin:15px; padding:5px;}
.product-item div{text-align:center; margin:2px;}
.product-price {color:#F08426;}
.product-image {height:100px;background-color:#FFF;cursor:move;}
.clear-float{clear:both;margin-bottom:40px;}
body{width:610px;}
<HTML>
<HEAD>
<TITLE>PHP Shopping Cart with jQuery AJAX</TITLE>
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$('.draggable').on('dragstart', function (e) {
var source_id = $(this).attr('id');
e.originalEvent.dataTransfer.setData("source_id", source_id);
});
$("#cart-item").on('dragenter', function (e) {
e.preventDefault();
$(this).css('background', '#BBD5B8');
});
$("#cart-item").on('dragover', function (e) {
e.preventDefault();
});
$("#cart-item").on('drop', function (e) {
e.preventDefault();
$(this).css('background', '#FFFFFF');
var product_code = e.originalEvent.dataTransfer.getData('source_id');
cartAction('add', product_code);
});
});
function cartAction(action, product_code) {
var queryString = "";
if (action != "") {
switch (action) {
case "add":
queryString = 'action=' + action + '&code=' + product_code;
break;
case "remove":
queryString = 'action=' + action + '&code=' + product_code;
break;
case "empty":
queryString = 'action=' + action;
break;
}
}
jQuery.ajax({
url: "AddToCart.aspx",
data: queryString,
type: "POST",
success: function (data) {
$("#cart-item").html(data);
},
error: function () { }
});
}
function calculateTotal(qty, qty_new, price) {
var total = $('#totalAmount').html();
total = parseInt(total) - (parseInt(qty) * parseInt(price));
total = parseInt(total) + (parseInt(qty_new) * parseInt(price));
$('#totalAmount').html(total);
}
</script>
This is the code i am looking to convert into .net , for this i can get the data from the database, but i am not getting how to generate the div part , could any body help me on this?
runQuery("SELECT * FROM tblproduct
ORDER BY id ASC"); if (!empty($product_array)) {
foreach($product_array as $key=>$value){ ?> " data-price=""> " id="">

Gigya User Object is Missing

I've just started using Gigya to allow users to connect to my site. I already have a login system so I just want to connect existing users to the Gigya service.
To do this I have called the "gigya.services.socialize.notifyLogin" function which returns a Gigya User object with the UID provided by my site. [fig 1]
Do I need to do anything with this User object, like add it to a cookie or is it just for reference.
The problem that Im having is on another page, I want to allow users to connect to their social media accounts. I use the "showAddConnectionsUI" function passing my api key, but the returned object does NOT have the User object in, although the documentation says it should. How do I get the users conenctions and the key information from this function. Do I need to send any additional information along with my api key. [fig 2]
I have spent several days reading the wiki, documentation and forum for advice but I am still stuck. Any help would be greatly appreciated. Thanks in advance, Ben
[fig 1]
<script type="text/javascript" src="http://cdn.gigya.com/js/socialize.js?apiKey=<?php echo $key; ?>"></script>
<script type="text/javascript">
var gigyaConf = { APIKey: "<?php echo $key; ?>", signIDs: "true" }
var signature = "<?php echo $signature; ?>";
var siteUID = "<?php echo $userId; ?>";
var timestamp = "<?php echo $timestamp; ?>";
var gigyaParams =
{
siteUID:siteUID,
timestamp:timestamp,
signature:signature,
callback:gigyaNotifyLoginCallback
};
gigya.services.socialize.notifyLogin(gigyaConf, gigyaParams);
function gigyaNotifyLoginCallback(eventObj) {
if ( eventObj.errorCode != 0 ) {
alert('Gigya Error: ' + eventObj.errorMessage);
}
}
</script>
[fig 2]
<script type="text/javascript" lang="javascript" src="http://cdn.gigya.com/JS/socialize.js?apikey=<?php echo $key; ?>"></script>
<script>
var conf = { APIKey: '<?php echo $key; ?>', signIDs: 'true' };
$(document).ready(function(){
gigya.services.socialize.getUserInfo(conf, { callback: renderUI });
gigya.services.socialize.addEventHandlers(conf,
{
onConnectionAdded: renderUI,
onConnectionRemoved: renderUI
});
});
</script>
<script>
function renderUI(res) {
if (res.user != null && res.user.isConnected) {
document.getElementById("name").innerHTML = res.user.nickname;
if (res.user.thumbnailURL.length > 0)
document.getElementById("photo").src = res.user.thumbnailURL;
else
document.getElementById("photo").src = "http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif";
document.getElementById("profile").style.display = "block";
} else {
document.getElementById("profile").style.display = "none";
}
}
</script>
<div id="content">
<h5>Step 1: Connect</h5>
<div id="divConnect"></div>
<script type="text/javascript">
gigya.services.socialize.showAddConnectionsUI(conf, {
height:65,
width:175,
showTermsLink:false,
hideGigyaLink:true,
useHTML:true,
containerID: "divConnect"
});
</script>
<br />
<h5>Step 2: See User Info</h5><br />
<div id=profile style="display:none;">
<img id="photo" src="" width="60" />
<br />
<span id="name" ></span>
</div>
</div>
Any help, advice, code snippits that would help will be greatly appreciated
Re: your first question, not required to do anything special with the Gigya User object. It's for your reference.
Re: your code, I can't tell if you're using JQuery but I was getting an error with your $(document).ready function. I modified your code slightly by adding body onLoad and everything worked. This assumes you have connected with a provider. Here's my code... hope it helps:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" lang="javascript" src="http://cdn.gigya.com/JS/socialize.js?apikey=<?php echo $key; ?>"></script>
<script>
var conf = { APIKey: '<?php echo $key; ?>', signIDs: 'true' };
function onLoad() {
gigya.services.socialize.getUserInfo(conf, { callback: renderUI });
gigya.services.socialize.addEventHandlers(conf,
{
onConnectionAdded: renderUI,
onConnectionRemoved: renderUI
});
}
</script>
<script>
function renderUI(res) {
if (res.user != null && res.user.isConnected) {
document.getElementById("name").innerHTML = res.user.nickname;
if (res.user.thumbnailURL.length > 0)
document.getElementById("photo").src = res.user.thumbnailURL;
else
document.getElementById("photo").src = "http://cdn.gigya.com/site/images/bsAPI/Placeholder.gif";
document.getElementById("profile").style.display = "block";
} else {
document.getElementById("profile").style.display = "none";
}
}
</script>
<body onload="onLoad()">
<div id="content">
<h5>Step 1: Connect</h5>
<div id="divConnect"></div>
<script type="text/javascript">
gigya.services.socialize.showAddConnectionsUI(conf, {
height:65,
width:175,
showTermsLink:false,
hideGigyaLink:true,
useHTML:true,
containerID: "divConnect"
});
</script>
<br />
<h5>Step 2: See User Info</h5><br />
<div id=profile style="display:none;">
<img id="photo" src="" width="60" />
<br />
<span id="name" ></span>
</div>
</div>
</body>
</html>

Categories