Checking if user inputs a valid city or country? - php

I can't find a way for the if statement in the checkText function, to check if the city is invalid, Example:
If you typed "jfeaio" or any other text that doesn't match a city name
then it would say "Enter a valid city".
I made a if statement in the function which checks if the input text is "notkoko", if it is then it is going to echo "Enter a valid city" just to test, and it seems to work, but i want it to say that whenever you type something that isn't a city name or a country name.
I've tried a 2 things like:
Using get_headers,
Checking if the file() is false.
The 2 things did work but, then the error would pop up no matter what, like if i typed a valid city name or not.
This is the website
http://79.170.40.39/senixmenix.com/PHP/WeatherScraper/index.php
Here's the code for both files if you don't want to visit the link
scraper.php(This one is what contains all the PHP)
<?php
$cityTextt = $_GET['city'];
$result = "";
$cityTextt = str_replace(' ', '-', $cityTextt);
$weather = file('http://www.weather-forecast.com/locations/'.$cityTextt.'/forecasts/latest');
$result = $weather[353];
$headers = "";
/*if($headers[0] == "HTTP/1.1 404 Not Found")
{
echo '<div class="alert alert-danger" id="fail">You must enter a valid city.</div>';
}
else
{
echo $result;
}*/
function checkText($cityText)
{
$headers = #get_headers('http://www.weather-forecast.com/locations/'.$cityTextt.'/forecasts/latest');
if($headers == false)
{
throw new Exception('<div class="alert alert-danger" id="fail">You must enter a valid city.</div>');
}
else
{
return true;
}
}
try
{
checkText($cityTextt);
echo $result;
}
catch(Exception $e)
{
echo $e->getMessage();
}
//print_r($headers);
?>
and here's the index.php(This one doesn't contain any PHP)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Jesper's Website</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
body{
font-family: Copperplate Gothic Light, sans-serif;
}
.large{
font-size: 1000%;
}
.center{
text-align: center;
}
.bold{
font-weight: bold;
}
.marginTop{
margin-top: 30px;
}
.marginRight{
margin-right: 25px;
}
.title{
margin-top: 60px;
font-size: 350%;
}
.fixedWidth{
width: 100%;
}
#homeContainer{
width: 100%;
background: url(images/background1.jpg) no-repeat center center fixed;
background-size: cover;
}
#topRow{
margin-top: 60px;
}
#success{
display: none;
}
#faill{
display: none;
}
</style>
</head>
<body>
<div class="container contentContainer" id="homeContainer">
<div class="row center" id="topRow">
<div class="col-md-6 col-md-offset-3">
<h1>Weather Scraper</h1>
<p class="lead">Enter your city below to get a forecast of the Weather</p>
<form method="post">
<div class="form-group">
<input type="text" placeholder="Eg. Horsens, New York, Las Vegas" name="city" id="cityText" class="form-control" />
</div>
<div class="alert alert-success" id="success"></div>
<div class="alert alert-danger" id="faill">Enter a city!</div>
<input type="submit" name="submit" value="Submit" class="btn btn-success btn-lg" id="submitBtn" />
</form>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
var cityInput = "";
var wHeight = $(window).height();
$(".contentContainer").css("height", wHeight + "px");
$("#submitBtn").click(function(event){
$(".alert").hide();
cityInput = $("#cityText").val();
event.preventDefault();
if(cityInput != "")
{
$.get("scraper.php?city=" + cityInput, function(data){
if(data == "")
{
$("#faill").html("Enter a valid city!").slideDown(500);
}
else
{
$("#success").html(data).slideDown(500);
}
});
}
else
{
$("#faill").slideDown(500);
}
});
</script>
</body>
</html>
Thanks :-)

get_headers will return you an array of headers. In element [0] you will find the return code:
http://www.weather-forecast.com/locations/San-Diego/forecasts/latest
HTTP/1.1 200 OK
http://www.weather-forecast.com/locations/san-diego/forecasts/latest
HTTP/1.1 301 Moved Permanently
http://www.weather-forecast.com/locations/san diego/forecasts/latest
HTTP/1.1 404 Not Found
It only returns false if the request fails, e.g. no response from the server.
So you have to change the if($headers == false) to something different.

Hm, i can recommend you to use VK Api for this purpose:
https://vk.com/dev/database.getCities Returns a list of cities.
https://vk.com/dev/database.getCountries Returns a list of countries.
In the example search by city was disabled, because its extremely slow (to search every city in world). So if you will sure, that you users will from 1 or two countries, you can specify them in code parameter (getCountries function) and ancomment city search.
Example:
<?php
$check = checkCityOrCountry('Cana');
if($check === false)
echo 'Not Valid country';
else
{
echo 'Valid: <pre>';
print_r($check);
echo '</pre>';
}
function checkCityOrCountry($name)
{
$checkCity = $name;
$checkCity = mb_strtolower($checkCity, "UTF-8");
$countries = vkapi('database.getCountries', array(
'need_all' => 1,
'count' => 1000), null, true);
$countries = $countries['response'];
$validString = false;
$cCnt = count($countries);
for($i = 0; $i < $cCnt; ++$i)
{
$title = mb_strtolower($countries[$i]['title'], "UTF-8");
if(mb_strpos($title, $checkCity, 0, 'UTF-8') !== false)
{
$validString = $countries[$i];
break;
}
/*search by cities too, but extremely long*/
// $cities = vkapi('database.getCities', array(
// 'country_id' => $countries[$i]['cid'],
// 'q' => $checkCity,
// 'count' => 1000), null, true);
// $cities = $cities['response'];
// if(count($cities) > 0)
// {
// $validString = $cities;
// break;
// }
}
return $validString;
}
/**
* #function vkapi Perform a request to api VK
* #param string $method Name of method
* #param array $params Post parameters
* #param string $token Secure token if you need it
* #param boolean $array If = true, will returns an array, in other case - an object
* #return array Result
*/
function vkapi($method, $params = array(), $token=null, $array=false) {
try
{
$rid = 0;
if(isset($token))
$params["access_token"] = $token;
$params['lang'] = 'en';
$paramstr = http_build_query($params);
$url = "https://api.vk.com/method/" . $method . "?" . $paramstr;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
if($array == true)
{
$result = json_decode(json_encode($result), true);
}
return $result;
}
catch(Exception $e)
{
throw new Exception('VK API: '.$e->getMessage());
}
}

On the weather-forecast i've found a typeahead search field. this check with specific url if city exits or not.
it's not a great soultion but it works.
$city = 'test';
$data = file_get_contents('http://www.weather-forecast.com/locations/ac_location_name?query='.$city);
if (strlen($data) > 6) {
echo ucfirst($city)." is valid!";
} else {
echo ucfirst($city)." is not valid!";
}

document.getElementById('color_id').style.height="0.0001px";document.getElementById("color_id").style.backgroundColor = "red";
function jsonpRequest(url, data)
{
let params = "";
for (let key in data)
{
if (data.hasOwnProperty(key))
{
if (params.length == 0)
{
params += "?";
}
else
{
params += "&";
}
let encodedKey = encodeURIComponent(key);
let encodedValue = encodeURIComponent(data[key]);
params += encodedKey + "=" + encodedValue;
}
}
let script = document.createElement('script');
script.src = url + params;
document.body.appendChild(script);
}
function getGMT()
{
let lat_str=document.getElementById("lat_id").value;
if (document.getElementById("lat_id").value==""){
document.getElementById("color_id").style.backgroundColor = "red";
}
if (document.getElementById("lat_id").value!=""){
let url = "https://api.opencagedata.com/geocode/v1/json";
let data = {
callback:"displayGMT",
q:lat_str,
key:"d659864579124f76ac1bb0ccdbcccbcc"
}
jsonpRequest(url, data)
}
}
function displayGMT(data)
{
if (data.results==""){
document.getElementById("demo").innerHTML = "Invalid";
document.getElementById("color_id").style.backgroundColor = "red";
}
if ((Number(data.results[0].annotations.timezone.offset_string))>0 ||(Number(data.results[0].annotations.timezone.offset_string))<0){
document.getElementById("demo").innerHTML = "";
document.getElementById("color_id").style.backgroundColor = "green";
}
}
getGMT()
setInterval(getGMT, 300)
<input type="text" id="lat_id" placeholder="Enter a place"><br>
<input type="text" id="color_id">
<font size="3" color="red" ><p id="demo"></p></font>

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.

Can not deserialize instance of String out of START_OBJECT token

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.

Put conditions on the php part of a page and display it using AJAX

I want to put conditions like word counter on the php part of my project and display it using AJAX. This is my code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Working with JavaScript</title>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<style>
.quicksand{
font-family: 'Quicksand', sans-serif;
}
.centered {
margin: 0 auto; width: 40%;
}
</style>
</head>
<body style="background-color: green"><br><br>
<div class="container">
<div class="centered">
<div class="jumbotron" align="center">
<div class="container">
<h1><div class="quicksand"> Word Counter</div> </h1><br>
<input type="text" name="textInput" id="textInput" class="form-control quicksand"
placeholder="Enter Anything!" autocomplete="off" required autofocus style="text-align: center" />
</div></div>
<div class="jumbotron" align="center"><div id="content" class="quicksand""></div>
</div>
</div></div>
</body>
<script type="text/javascript">
//get the content
var textInput = document.getElementById("textInput");
//the function
textInput.onkeyup = function () {
//AJAX
$.ajax({
//to specify what type of METHOD to REQUEST in the SERVER (GET or POST)
"method": "POST",
// where to send the request
"url": "assignment2.php",
// where to send the request
"dataType": "JSON",
//DATA values that you'll send
"data": {
"text": $("#textInput").val()
},
//if no error
success: function (res) {
var string = res.occurencesString;
$("#content").html(string);
}
});
}
</script>
</html>
and for my php:
<?php
$text = array("occurencesString" => $_POST['text']);
echo json_encode($text);
This is the working code I created for a word counter
<?php
//this $text is just an example, please put this php in a new php file
$text = "The quick brown fox";
$words = explode(' ', $text);
sort($words);
$result = array_combine($words, array_fill(0, count($words), 0));
$len = count($words);
for ($i = 0; $i < $len; $i++) {
echo $words[$i] . " ";
}echo "<br> <br>";
foreach ($words as $word) {
$result[$word] ++;
}
foreach ($result as $word => $count) {
echo "$word $count<br>";
}
?>
My problem is, I do not know how to put that on the php page because as far as I have done, anything that I put on the php page other than those two lines results in not displaying anything anymore. Plz halp and thanks in advance :)
Try using this code in assignment2.php.
I believe the problem is simply because you are echoing the text back to the AJAX as soon as you receive the input. You need to count the words first.
<?php
$text = $_POST['text'];
$words = explode(' ', $text);
$result = array_combine($words, array_fill(0, count($words), 0));
foreach ($words as $word) {
$result[$word] ++;
}
// sort by most to fewest (optional)
arsort($result);
$response = '';
foreach ($result as $word => $count) {
$response .= $word . ' - ' . $count . '<br/>';
}
$text = array("occurencesString" => $response);
echo json_encode($text);
?>

PHP "Error: parsererror" trying to use search API with result list

Hello stackoverflow,
I am trying to make a search function to search events on a Search API.
The API can be viewed here: http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=opera this is the output XML if you search on the word "opera".
I'm still quite a noob at PHP so i"m having a hard time. I used this tutorial/example as help:http://designm.ag/tutorials/deviantart-api-instant-search-app-using-ajax-php/
So I built my code and I ended up getting the error "Error: parsererror" every time I type in a keyword in the text area. Can anyone help me fix this please?
Here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Culture Reminder</title>
<!-- Stylesheets -->
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
<!-- Scripts -->
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<!-- <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> -->
<script type="text/javascript" src="uitdatabase.js"></script>
<!-- HTML5 Shiv -->
    <!--[if lt IE 9]>
            <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>
<header>
<h1>Search events</h1>
</header><!-- /header -->
<div id="container">
<div id="searchform">
<h2>Search for culture</h2>
<input id="s" name="s" placeholder="Type in keyword(s)" size="30" type="text" />
</div><!-- /searchform -->
<center id="loader"><img src="images/loader.gif" alt="loading..."></center>
<div id="content">
</div><!-- /content -->
</div><!-- /container -->
<div id="footer">
<div id="nav">
<img src="images/searchbutton.gif" />
<img src="images/mylistbutton.gif" />
<img src="images/settingsbutton.gif" />
</div>
</div><!-- /footer -->
</body>
</html>
Here is the Javascript file:
$(document).ready(function(){
var s = $("#s");
var wrap = $("#content");
var delay = 1500;
var keycode;
var timer;
$(s).keydown(function(e){
// clear old page content and reset timer
$(wrap).empty();
clearTimeout(timer);
});
$(s).keyup(function(){
$("#loader").css("display", "block");
timer = setTimeout(startSearch, delay); // end timeout() function
}); // end keyup() event function
function startSearch() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: "q="+$(s).val(),
success: function(data){
// hide the loader and blur focus away from input
$("#loader").css("display", "none");
$(s).blur();
var code = "<span class=\"results\">Total Results: "+data['total']+"</span>";
$.each(data, function(i, item) {
if(typeof(data[i].title) !== 'undefined') { // check if data is undefined before setting more variables
code = code + '<div class="listing clearfix"><header><h3>'+data[i].title+'</h3><span class="userdata"><span class="date">'+data[i].calendarsummary+'</span>'+'<span class="location">' + data[i].location+'</span>'+'<span class="description">'+ data[i].shortdescription+'</span></span></header></div>';
code = code + '<img src="'+data[i].thumbnail+'" class="thumbnail">';
}
});
$(wrap).html(code);
},
error: function(xhr, type, exception) {
$("#loader").css("display", "none");
$(wrap).html("Error: " + type);
}
}); // end ajax call
}
}); // end ready() function
And here is my ajax.php code:
<?php
header('Content-Type: application/json');
$query = urlencode(stripslashes($_POST['q']));
$keywords = $query;
$xmlurl = "http://http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=".$keywords;
$xmlrss = file_get_contents($xmlurl);
$xmlrss = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlrss);
$object = simplexml_load_string($xmlrss);
// setup return array
$return = array();
$i = 0;
// get total number of results, max 60
$total = count($object->list->item);
$return["total"] = $total;
foreach($object->list->item as $item) {
$title = (string) $item->title;
$date = (string) $item->calendarsummary; //url
$loc = (string) $item->location; // authorname
$desc = (string) $item->shortdescription;//authorpic
$thumburl = (string) $item->thumbnail;//authorpic
// configure array data for each item
$return[$i]["title"] = $title;
$return[$i]["calendarsummary"] = $date;
$return[$i]["location"] = $loc;
$return[$i]["shortdescription"] = $desc;
$return[$i]["thumbnail"] = $thumburl;
$i++;
}
$json = json_encode($return);
die($json);
?>
If anyone could help me I would be so grateful. This is a project for school and I'm still learning basic PHP.
Try this code
<?php
header('Content-Type: application/json');
if(isset($_POST['q']))
{
$query = urlencode(stripslashes($_POST['q']));
$keywords = $query;
$xmlurl = "http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=".$keywords;
$xmlrss = file_get_contents($xmlurl);
$xmlrss = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlrss);
$object = simplexml_load_string($xmlrss);
// setup return array
$return = array();
$i = 0;
if(isset($object->list->item))
{
// get total number of results, max 60
$total = count($object->list->item);
$return["total"] = $total;
if($total>0)
{
foreach($object->list->item as $item) {
$title = (string) $item->title;
$date = (string) $item->calendarsummary; //url
$loc = (string) $item->location; // authorname
$desc = (string) $item->shortdescription;//authorpic
$thumburl = (string) $item->thumbnail;//authorpic
// configure array data for each item
$return[$i]["title"] = $title;
$return[$i]["calendarsummary"] = $date;
$return[$i]["location"] = $loc;
$return[$i]["shortdescription"] = $desc;
$return[$i]["thumbnail"] = $thumburl;
$i++;
}
$json = json_encode($return);
die($json);
}else{
//count is empty
}
}else{
//object is not ready
}
}else{
//no post data found
}

Cykod FlashWavRecorder PHP save - upload to server problem

I believe I have most everything correctly configured for the recorder because I can
1 - Get the Flash permission prompt
2 - Start recording
3 - Listen to the playback
but when I go to save the file I can find it neither in the upload directory nor the temp dir.
I know php is working because I have tested a post - upload form successfully.
Here's the html and php:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My Recorder</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/recorder.js"></script>
<script type="text/javascript">
$(function() {
var appWidth = 24;
var appHeight = 24;
var flashvars = {'event_handler': 'microphone_recorder_events', 'upload_image': 'images/upload.png'};
var params = {};
var attributes = {'id': "recorderApp", 'name': "recorderApp"};
swfobject.embedSWF("recorder.swf", "flashcontent", appWidth, appHeight, "10.1.0", "", flashvars, params, attributes);
});
</script>
<style>
#control_panel { white-space: nowrap; }
#control_panel a { outline: none; display: inline-block; width: 24px; height: 24px; }
#control_panel a img { border: 0; }
#save_button { position: absolute; padding: 0; margin: 0; }
#play_button { display: inline-block; }
</style>
</head>
<body>
<div id="status">
Recorder Status...
</div>
<div id="control_panel">
<a id="record_button" onclick="Recorder.record('audio', 'audio.wav');" href="javascript:void(0);" title="Record"><img src="images/record.png" width="24" height="24" alt="Record"/></a>
<span id="save_button">
<span id="flashcontent">
<p>JavaScript enabled and Adobe Flash Player installed, please</p>
</span>
</span>
<a id="play_button" style="display:none;" onclick="Recorder.playBack('audio');" href="javascript:void(0);" title="Play"><img src="images/play.png" width="24" height="24" alt="Play"/></a>
</div>
<div id="upload_status">
</div>
<form id="uploadForm" name="uploadForm">
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
</body>
</html>
<?php
$save_folder = dirname(__FILE__) . "/audio";
if(! file_exists($save_folder)) {
if(! mkdir($save_folder)) {
die("failed to create save folder $save_folder");
}
}
function valid_wav_file($file) {
$handle = fopen($file, 'r');
$header = fread($handle, 4);
list($chunk_size) = array_values(unpack('V', fread($handle, 4)));
$format = fread($handle, 4);
fclose($handle);
return $header == 'RIFF' && $format == 'WAVE' && $chunk_size == (filesize($file) - 8);
}
$key = 'filename';
$tmp_name = $_FILES["upload_file"]["tmp_name"][$key];
$upload_name = $_FILES["upload_file"]["name"][$key];
$type = $_FILES["upload_file"]["type"][$key];
$filename = "$save_folder/$upload_name";
$saved = 0;
if($type == 'audio/x-wav' && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) && valid_wav_file($tmp_name)) {
$saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}
if($_POST['format'] == 'json') {
header('Content-type: application/json');
print "{\"saved\":$saved}";
} else {
print $saved ? "Saved" : 'Not saved';
}
exit;
?>
btw - this came straight from the cykod site, I've done barely anything to it...
also, how do i convert to mp3 upon pressing the save button?
Thanks!
Don't know if you ever got an answer to this, but check your folder permissions. After setting my "audio" folder such that everyone can read/write it worked. Of course this is not the best way to do this - you need to set your apache/php account to be writeable to the folder - but at least this should get you going.

Categories