Why am I unable to get sever time? - php

<html>
<head>
<title>Ajax Demonstration</title>
<style>
.displaybox {
width:150px;
background-color:#ffffff;
border:2px solid #000000;
padding:10px;
font:24px normal verdana, helvetica, arial, sans-serif;
}
</style>
<script language="JavaScript" type="text/javascript">
//<%=new java.util.Date()%>
function getXMLHTTPRequest() {
alert("Hello! I am an alert box!");
try {
req = new XMLHttpRequest();
} catch (err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
var http = getXMLHTTPRequest();
function getServerTime() {
var myurl = 'http://localhost/csp 2/telltimeXML.php';
myRand = parseInt(Math.random() * 999999999999999);
// var modurl = myurl+"?rand="+myRand;
http.open("GET", myurl, true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}
function useHttpResponse() {
if (http.readyState == 4) {
if (http.status == 200) {
var timeValue = http.responseXML.getElementsByTagName("timenow")[0];
alert(timeValue);
document.getElementById('showtime').innerHTML = timeValue.childNodes[0].nodeValue;
}
}
}
</script>
</head>
<body style="background-color:#cccccc"
onLoad="getServerTime()">
<center>
<h1>Ajax Demonstration</h1>
<h2>Getting the server time without page refresh</h2>
<form>
<input type="button" value="Get Server Time"
onClick="getServerTime()">
</form>
<div id="showtime" class="displaybox"></div>
</center>
</body>
</html>
Code for the PHP file:
<?php header('Content-Type: text/xml'); echo "<?xml version=\"1.0\" ?><clock1><timenow>" .date('H:i:s')."</timenow></clock1>"; ?>

Could be lots of things, since as others have pointed out we'd like to know what you are seeing. But one guess is that the url you are requesting is not hosted on the same server as the html file. That is, the html page you are one should be on http://localhost/.

Related

AJAX : Pass an image and data through Single AJAX [duplicate]

This question already has answers here:
How to send image to PHP file using Ajax?
(5 answers)
jQuery AJAX file upload PHP
(5 answers)
jQuery / ajax upload image and save to folder
(3 answers)
Upload image using jQuery, AJAX and PHP
(2 answers)
Closed 4 years ago.
I want to pass some text data and file through one ajax code
Here is my code's index.php :-
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Karthikeyan K">
<title>POST</title>
<!-- Bootstrap CSS file -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<style type="text/css">
body {
padding: 45px;
}
footer {
margin: 10px 0;
}
.photo {
margin-bottom: 10px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.mentionsInput.css">
<style type="text/css">
#status-overlay {
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.50);
position: fixed;
top: 0;
left: 0;
z-index: 99999;
overflow: hidden;
}
#highlight-textarea {
background: #fff;
}
.form-control:focus {
box-shadow: 0 0 0 2px #3399ff;
outline: 0;
}
h2 {
font-size: 20px;
}
</style>
<style>
#upload_button {
display: none;
border: 0px;
background: linear-gradient(180deg, #f44, #811);
border-radius: 5px;
color: #fff;
padding: 5px;
}
</style>
</head>
<body>
<div id="status-overlay" style="display: none"></div>
<form method="POST" class="form" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" id="title" class="form-control" placeholder="Post title..."><br>
<div id="highlight-textarea">
<textarea onclick="highlight();" name="postText" class="form-control postText mention" cols="10" rows="8" placeholder="What's going on?" dir="auto"></textarea>
</div><br>
<select class="form-control" name="type" id="type" required>
<option value="">Choose Post Type</option>
<option value="Closet">Closet</option>
<option value="Follower">Follower</option>
<option value="Group">Group</option>
</select><br>
<p><button id="upload_button">Click here to select file</button></p>
<p><input id="upload_input" name="upfile" type="file"/></p>
</div>
<input type="button" value="Post" class="btn btn-primary pull-right postMention">
</form>
<!-- Bootstrap Script file -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src='https://cdn.rawgit.com/jashkenas/underscore/1.8.3/underscore-min.js' type='text/javascript'></script>
<script src='js/lib/jquery.elastic.js' type='text/javascript'></script>
<script type="text/javascript" src="js/jquery.mentionsInput.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('textarea').on('click', function(e) {
e.stopPropagation();
});
$(document).on('click', function (e) {
$("#status-overlay").hide();
$("#highlight-textarea").css('z-index','1');
$("#highlight-textarea").css('position', '');
});
});
function highlight()
{
$("#status-overlay").show();
$("#highlight-textarea").css('z-index','9999999');
$("#highlight-textarea").css('position', 'relative');
}
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
//post text in jquery ajax
var post_data = "text="+encodeURIComponent(post_text);
var val1 = $('#title').val();
var val2 = $('#type').val();
//var val3 = $('#upload_input');
//var post_title = $('#title').val();
var form = new FormData(document.getElementById('.postMention'));
//append files
var file = document.getElementById('upload_input').files[0];
if (file) {
form.append('upload_input', file);
}
$.ajax({
type: "POST",
data: post_data+'&title='+val1+'&type='+val2+'&upload_input='+form,
url: 'ajax/post.php',
success: function(msg) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
}
});
} else {
alert("Post cannot be empty!");
}
});
});
//used for get users from database while typing #..
$('textarea.mention').mentionsInput({
onDataRequest:function (mode, query, callback) {
$.getJSON('ajax/get_users_json.php', function(responseData) {
responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, responseData);
});
}
});
});
</script>
</body>
</html>
<?php } ?>
here's a code of my php file to insert data into database ajax/post.php
. . . .
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
if(isset($_POST) && !empty($_POST['text']) && $_POST['text'] != '')
{
include '../config/config.php';
$user = $uid; //w3lessons demo user
$postid=mt_rand();
$text = strip_tags($_POST['text']); //clean the text
$title= $_POST['title'];
$type= $_POST['type'];
define('FIRST_MATCH_GROUP', 1);
preg_match_all("/#\[(.+)\]/U", $text, $tags); // Value under #[]
$tags = implode(',', $tags[FIRST_MATCH_GROUP]);
$upfile_name = $_FILES['upload_input']['name'];
$upfile_size =$_FILES['upload_input']['size'];
$upfile_tmp =$_FILES['upload_input']['tmp_name'];
$upfile_type=$_FILES['upload_input']['type'];
$upfile_t = explode(".", $_FILES["upload_input"]["name"]);
$upfile_name = mt_rand() . '.' . end($upfile_t);
if($upfile_type == "image/jpg" && $upfile_type == "image/png" && $upfile_type == "image/jpeg" && $upfile_type == "video/mp4"){
echo "<script>window.alert('extension not allowed, please choose a JPG or PNG or MP4 file.');</script>";
}
else {
if($upfile_size > 10485760){
echo "<script>window.alert('File size must be Less 10 MB');</script>";
}
else {
move_uploaded_file($upfile_tmp,"../../uploads/".$upfile_name);
$DB->query("INSERT INTO posts(post_id,title,content,user_id,type,tags,image) VALUES(?,?,?,?,?,?,?)", array($postid,$title,$text,$user,$type,$tags,$upload_input));
?>
<div class="media">
<div class="media-left">
<img src="https://cdn.w3lessons.info/logo.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">w3lessons</h4>
<p><?php echo getMentions($text); ?></p>
</div>
</div>
<hr>
<?php
} } } else {
echo "1"; //Post Cannot be empty!
}
function getMentions($content)
{
global $DB;
$mention_regex = '/#\[([0-9]+)\]/i'; //mention regrex to get all #texts
if (preg_match_all($mention_regex, $content, $matches))
{
foreach ($matches[1] as $match)
{
$match_user =$DB->row("SELECT * FROM register WHERE id=?",array($match));
$match_search = '#[' . $match . ']';
$match_replace = '<a target="_blank" href="' . $match_user['profile_img'] . '">#' . $match_user['first_name'] . '</a>';
if (isset($match_user['id']))
{
$content = str_replace($match_search, $match_replace, $content);
}
}
}
return $content;
}
}?>
When i submit form data was passing at my php page but images index is goes undefined...
change the way you pass data in request
try this
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
var formData = new FormData($('.form')[0]);
formData.append('text',encodeURIComponent(post_text));
$.ajax({
url: 'ajax/post.php',
type: 'POST',
data: formData,
success: function (data) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
},
cache: false,
contentType: false,
processData: false
});
} else {
alert("Post cannot be empty!");
}
});
});
and input name
<input id="upload_input" name="upload_input" type="file"/>

Why The Program Writes To Socket Empty?

I am making a program which records video, and sends its blobs to a socket every 5 secs.It seems working properly but when i look at the files received by the server, i see all the programs written by socket client are empty= 0kb.Can you help me please? My HTML/JS and PHP codes are below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>WebRTC Video Recording using MediaStreamRecorder</title>
<script src="https://cdn.WebRTC-Experiment.com/MediaStreamRecorder.js"></script>
<!-- for Edige/FF/Chrome/Opera/etc. getUserMedia support -->
<script src="https://cdn.WebRTC-Experiment.com/gumadapter.js"></script>
<link rel="stylesheet" href="https://cdn.webrtc-experiment.com/style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="author" type="text/html" href="https://plus.google.com/+MuazKhan">
<meta name="author" content="Muaz Khan">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<style>
input {
border: 1px solid rgb(46, 189, 235);
border-radius: 3px;
font-size: 1em;
outline: none;
padding: .2em .4em;
width: 60px;
text-align: center;
}
select {
vertical-align: middle;
line-height: 1;
padding: 2px 5px;
height: auto;
font-size: inherit;
margin: 0;
}
</style>
</head>
<body>
<article>
<header style="text-align: center;">
<h1>
WebRTC Video Recording using MediaStreamRecorder
</h1>
<p>
HOME
<span> © </span>
WebRTC Experiment .
</p>
</header>
<section class="experiment" style="padding: 5px;">
<label for="time-interval">Time Interval (milliseconds):</label>
<input type="text" id="time-interval" value="5000">
<br>
<br> recorderType:
<select id="video-recorderType" style="font-size:22px;vertical-align: middle;margin-right: 5px;">
<option value="[Best Available Recorder]">[Best Available Recorder]</option>
<option value="MediaRecorder API">MediaRecorder API</option>
<option value="WebP encoding into WebM">WebP encoding into WebM</option>
</select>
<br>
<br>
<button id="start-recording">Start</button>
<button id="stop-recording" disabled>Stop</button>
<button id="pause-recording" disabled>Pause</button>
<button id="resume-recording" disabled>Resume</button>
<button id="save-recording" disabled>Save</button>
<br>
<br>
<label for="video-width">Video Width:</label>
<input type="text" id="video-width" value="320">
<label for="video-height">Video Height:</label>
<input type="text" id="video-height" value="240">
</section>
<section class="experiment">
<div id="videos-container">
</div>
</section>
<script>
function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
}
var mediaConstraints = {
audio: !IsOpera && !IsEdge, // record both audio/video in Firefox/Chrome
video: true
};
document.querySelector('#start-recording').onclick = function() {
this.disabled = true;
captureUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
};
document.querySelector('#stop-recording').onclick = function() {
this.disabled = true;
mediaRecorder.stop();
mediaRecorder.stream.stop();
document.querySelector('#pause-recording').disabled = true;
document.querySelector('#start-recording').disabled = false;
};
document.querySelector('#pause-recording').onclick = function() {
this.disabled = true;
mediaRecorder.pause();
document.querySelector('#resume-recording').disabled = false;
};
document.querySelector('#resume-recording').onclick = function() {
this.disabled = true;
mediaRecorder.resume();
document.querySelector('#pause-recording').disabled = false;
};
document.querySelector('#save-recording').onclick = function() {
this.disabled = true;
mediaRecorder.save();
// alert('Drop WebM file on Chrome or Firefox. Both can play entire file. VLC player or other players may not work.');
};
var mediaRecorder;
function onMediaSuccess(stream) {
var video = document.createElement('video');
var videoWidth = document.getElementById('video-width').value || 320;
var videoHeight = document.getElementById('video-height').value || 240;
video = mergeProps(video, {
controls: true,
muted: true,
width: videoWidth,
height: videoHeight,
src: URL.createObjectURL(stream)
});
video.play();
videosContainer.appendChild(video);
videosContainer.appendChild(document.createElement('hr'));
mediaRecorder = new MediaStreamRecorder(stream);
mediaRecorder.stream = stream;
var recorderType = document.getElementById('video-recorderType').value;
if (recorderType === 'MediaRecorder API') {
mediaRecorder.recorderType = MediaRecorderWrapper;
}
if (recorderType === 'WebP encoding into WebM') {
mediaRecorder.recorderType = WhammyRecorder;
}
// don't force any mimeType; use above "recorderType" instead.
// mediaRecorder.mimeType = 'video/webm'; // video/webm or video/mp4
mediaRecorder.videoWidth = videoWidth;
mediaRecorder.videoHeight = videoHeight;
mediaRecorder.ondataavailable = function(blob) {
var a = document.createElement('a');
a.target = '_blank';
a.innerHTML = 'Open Recorded Video No. ' + (index++) + ' (Size: ' + bytesToSize(blob.size) + ') Time Length: ' + getTimeLength(timeInterval);
a.href = URL.createObjectURL(blob);
videosContainer.appendChild(a);
videosContainer.appendChild(document.createElement('hr'));
// EKLENEN
var myRequest = new XMLHttpRequest();
myRequest.open('POST', 'save.php' , true);
myRequest.send(blob);
};
var timeInterval = document.querySelector('#time-interval').value;
if (timeInterval) timeInterval = parseInt(timeInterval);
else timeInterval = 5 * 1000;
// get blob after specific time interval
mediaRecorder.start(timeInterval);
document.querySelector('#stop-recording').disabled = false;
document.querySelector('#pause-recording').disabled = false;
document.querySelector('#save-recording').disabled = false;
}
function onMediaError(e) {
console.error('media error', e);
}
var videosContainer = document.getElementById('videos-container');
var index = 1;
function bytesToSize(bytes) {
var k = 1000;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
function getTimeLength(milliseconds) {
var data = new Date(milliseconds);
return data.getUTCHours() + " hours, " + data.getUTCMinutes() + " minutes and " + data.getUTCSeconds() + " second(s)";
}
window.onbeforeunload = function() {
document.querySelector('#start-recording').disabled = false;
};
</script>
<pre style="border-left: 2px solid red; margin-left:2em; padding-left: 1em;">
// cdn.webrtc-experiment.com/MediaStreamRecorder.js
var mediaConstraints = {
audio: true,
video: true // if firefox or chrome
};
navigator.getUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
function onMediaSuccess(stream) {
var mediaRecorder = new MediaStreamRecorder(stream);
mediaRecorder.mimeType = 'video/webm';
mediaRecorder.ondataavailable = function (blob) {
// POST/PUT "Blob" using FormData/XHR2
var blobURL = URL.createObjectURL(blob);
document.write('' + blobURL + '');
};
mediaRecorder.start(3000);
}
function onMediaError(e) {
console.error('media error', e);
}
</pre>
MediaStreamRecorder Demos
<script>
window.useThisGithubPath = 'streamproc/MediaStreamRecorder';
</script>
<script src="https://cdn.webrtc-experiment.com/commits.js" async></script>
</article>
<footer>
MIT License
<table>
<tr> <td>
</td>
</tr>
</p>
</footer>
</body>
</html>
And PHP Socket Client below :
<?php
$portnum = 'portnum';
$ipnum = 'Ipnum';
// No Timeout
set_time_limit(0);
if ( ($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == FALSE ) {
$message = "Socket not created";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$context = stream_context_create($opts);
if ( ($file = file_get_contents($_FILES['blob'], false, $context ) ) == FALSE ) {
$message = "File_get_contents not working.";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$ss = fopen ( file, "r");
$streamvid = fread ( $ss );
if ( ( $tt = fsockopen($ipnum, $portnum, $errno, $errstr, 30)) == FALSE ) {
$message = "fsockopen not working";
echo "<script type='text/javascript'>alert('$message');</script>";
}
if ( (fwrite ( $tt , $streamvid ) ) == FALSE ) { // DIŞARI ALINDI
$message = "fwrite failed";
echo "<script type='text/javascript'>alert('$message');</script>";
}
fclose( $tt );
?>
mediaRecorder.ondataavailable = function(blob) {
// upload blob to PHP server
uploadToPHPServer(blob);
};
function uploadToPHPServer(blob) {
var file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', {
type: 'video/webm'
});
// create FormData
var formData = new FormData();
formData.append('video-filename', file.name);
formData.append('video-blob', file);
makeXMLHttpRequest('https://path-to-your-server/save.php', formData, function() {
var downloadURL = 'https://path-to-your-server/uploads/' + file.name;
console.log('File uploaded to this path:', downloadURL);
});
}
function makeXMLHttpRequest(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback();
}
};
request.open('POST', url);
request.send(data);
}
Here is save.php:
<?php
// via: https://github.com/muaz-khan/RecordRTC/blob/master/RecordRTC-to-PHP/save.php
header("Access-Control-Allow-Origin: *");
function selfInvoker()
{
if (!isset($_POST['audio-filename']) && !isset($_POST['video-filename'])) {
echo 'PermissionDeniedError';
return;
}
$fileName = '';
$tempName = '';
if (isset($_POST['audio-filename'])) {
$fileName = $_POST['audio-filename'];
$tempName = $_FILES['audio-blob']['tmp_name'];
} else {
$fileName = $_POST['video-filename'];
$tempName = $_FILES['video-blob']['tmp_name'];
}
if (empty($fileName) || empty($tempName)) {
echo 'PermissionDeniedError';
return;
}
$filePath = 'uploads/' . $fileName;
// make sure that one can upload only allowed audio/video files
$allowed = array(
'webm',
'wav',
'mp4',
'mp3',
'ogg'
);
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
echo 'PermissionDeniedError';
continue;
}
if (!move_uploaded_file($tempName, $filePath)) {
echo ('Problem saving file.');
return;
}
echo ($filePath);
}
selfInvoker();
?>
Regarding PHP upload issues,
https://github.com/muaz-khan/RecordRTC/wiki/PHP-Upload-Issues
PS. Don't forget to create uploads directory here:
https://path-to-your-server/uploads/ ----- inside same directory as "save.php"

Passing JavaScript Variables from JavaScript to PHP using AJAX

I am having some problems with my PHP file. So basically I am working on a project that takes two addresses from the user, then it uses javascript to show their route and once they click submit, I want to pass these two variables to PHP file. I researched a lot and found that I would need AJAX call. The problem I am running into is that AJAX call works perfectly, but when I go to PHP file it throws me an error that variables are not defined. Someone, please explain to me what I am doing wrong here.
JavaScript code:
/* ============================================================================================
Reference: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-directions
==============================================================================================
*/
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 41.881832, lng: -87.623177},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var submit_button = document.getElementById('button-to-submit');
/*var modeSelector = document.getElementById('mode-selector');*/
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
/*this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');*/
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(submit_button);
/*this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);*/
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
/* AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
}; */
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
origin_addr = document.getElementById('origin-input').value;
//console.log(origin_addr);
destination_addr = document.getElementById('destination-input').value;
//console.log(destination_addr);
//var place_id = document.getElementById('origin-input');
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
$("#button-to-submit").click(function() {
$.ajax({
url: "Database/save-points.php",
type: "POST", //send it through get method
data: {
origin_address: origin_addr,
destination_address: destination_addr
},
success: function(response) {
//Do Something
console.log("Succeed");
location.href="Database/save-points.php";
},
error: function(xhr) {
//Do Something to handle error
}
});
});
PHP code:
<?php
$origin_address = $_POST['origin_address'];
$destination_address = $_POST['destination_address'];
echo $origin_address;
echo $destination_address;
?>
/* maps.php */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr" dir="ltr">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js" type="text/javascript"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#origin-input,
#destination-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 200px;
}
#origin-input:focus,
#destination-input:focus {
border-color: #4d90fe;
}
#mode-selector {
color: #fff;
background-color: #4d90fe;
margin-left: 12px;
padding: 5px 11px 0px 11px;
}
#mode-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
</head>
<body>
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
placeholder="Enter a destination location">
<div id="mode-selector" class="controls">
<input type="radio" name="type" id="changemode-walking" checked="checked">
<label for="changemode-walking">Walking</label>
<input type="radio" name="type" id="changemode-transit">
<label for="changemode-transit">Transit</label>
<input type="radio" name="type" id="changemode-driving">
<label for="changemode-driving">Driving</label>
<input type="submit" id="button-to-submit" value="SAVE !" />
</div>
<div id="map"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOU_KEY&libraries=places"></script>
<script type="text/javascript">
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var modeSelector = document.getElementById('mode-selector');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
/************************************/
$(document).ready( function() {
$("#button-to-submit").click(function() {
origin_addr = $("#origin-input").val();
destination_addr = $("#destination-input").val();
$.ajax({
type: "POST",
url: "maps.exe.php",
data: {
origin_address: origin_addr,
destination_address: destination_addr
},
success: function(response){
alert(response);
window.location.href = 'test-resp.php?'+response;
}
});
return false;
});
});
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMap" async defer></script>
</body>
</html>
/* maps.exe.php */
<?php
$origin_address = $_POST['origin_address'];
$destination_address = $_POST['destination_address'];
echo"origin=$origin_address&destination=$destination_address";
?>
/* test-resp.php */
<?php
$origin_address = $_GET['origin'];
$destination_address = $_GET['destination'];
echo"[ origin : $origin_address / destination = $destination_address ]";
?>
I have an example of me passing JS variable to PHP.
JS (url and content are JS variables) :
var data_to_send = {
filepath: ""+url,
filecontent: ""+content
};
jQuery.ajax({
url:"php/dynamic.php",
data: data_to_send,
cache: false,
async: true,
type:'post',
timeout:3000//purely optionnal, check jQuery's Doc to learn more about ajax optionnal parameters/settings
});
In dynamic.php :
<?php
$vars = serialize($_POST); /*easier access*/
$file_path = "../".$vars["filepath"];
$file_content = $var["filecontent"]; /*example of assigning a JS var's value to a PHP var*/
$fh = fopen($file_path, 'w+') or die("could not open file");
fwrite($fh, $file_content."\n");
fclose($fh);
?>
PS: I use jQuery for POST, I dunno the pure javascript way to do the same :/

ajax get and insert with php and mysql

I have a page that has a form on it, when I click a button on the page it sends 3 variables to a layer(page_ref, template_ref, and box_id) via a javascript call.
Then with ajax I get some content from the mysql db with the variables and insert this into a text area on the layer.
The layer has a save button and when I click that I want to save the content of the textarea back to the db.
I can fill the textarea from the db no problem but am having problems pushing is back to the db.
The problem I have is sending the javascript variables to the ajax update page as they need to be passed to php varriables.
heres what I have
on the main page I call a javascript function
edit_box('show',i,'<? echo $page_ref; ?>','<? echo $template_ref; ?>');
in the layer I have this
<style type="text/css">
#popupbox
{
padding:0;
width: 99%;
height: auto;
margin: 0px auto;
position:absolute;
background: #FBFBF0;
border: solid #000000 2px;
z-index: 9000;
font-family: arial;
visibility: hidden;
}
</style>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script>
<script>
//Browser Support Code
function get_edit_content(box_id,page_ref,template_ref)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("edit_content").innerHTML=xmlhttp.responseText;
var area1 = new nicEditor({fullPanel : true}).panelInstance("edit_content",{hasPanel : true});
}
}
var queryString = "?box_id=" + box_id + "&page_ref=" + page_ref + "&template_ref=" + template_ref;
xmlhttp.open("GET","get_content.php" + queryString,true);
xmlhttp.send();
}
$("#sub").click( function()
{
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info)
{
$("#result").html(info);
});
clearInput();
});
$("#myForm").submit( function()
{
return false;
});
function clearInput()
{
$("#myForm :input").each( function()
{
$(this).val('');
});
}
function edit_box(showhide,box_id,page_ref,template_ref)
{
if(showhide == "show")
{
get_edit_content(box_id,page_ref,template_ref);
document.getElementById('popupbox').style.visibility="visible";
}
else if(showhide == "hide")
{
document.getElementById('popupbox').style.visibility="hidden";
}
}
</script>
<div id="popupbox">
<form id="myForm" action="update_textarea.php" method="post">
<input type="hidden" name="page_ref" value="<? echo $page_ref; ?>" />
<input type="hidden" name="template_ref" value="<? echo $template_ref; ?>" />
<input type="hidden" name="box_id" value="<? echo $box_id; ?>" />
<textarea name="edit_content" id="edit_content" style="width: 500px; height:500px;"></textarea>
<center>close</center>
<button id="sub">Save</button>
</form>
</div>
then I have get_contents page
<?php
include("connect.php");
$page_ref = $_GET['page_ref'];
$template_ref = $_GET['template_ref'];
$box_id = $_GET['box_id'];
$sql = "SELECT * FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_id='$box_id' AND box_type='text'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['content']."</p>";
}
?>
and finally the update_textarea page
<?
include("connect.php");
$page_ref = $_POST['page_ref'];
$template_ref = $_POST['template_ref'];
$box_id = $_POST['box_id'];
$edit_content = $_POST['edit_content'];
if(mysql_query("UPADTE site_content SET content='$edit_content' WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_id='$box_id' AND box_type='text'"))
{
echo "Successfully Inserted";
}
else
{
echo "Insertion Failed";
}
?>
I realised that i needed to set the values of the hidden inputs in the ajax call after
document.getElementById("edit_content").innerHTML=xmlhttp.responseText;
by adding
document.getElementById("box_id").value = box_id;
etc

What is wrong in this Ajax/Javascript code?

I'm trying to do a function that will show the clock on clicking a button but i can't get the clock to show up. I'm kinda new on this stuff and would really appreciate some help with this and also an explanation to what I've done wrong.
Thanks in advance!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
function getXMLHTTPRequest() {
try {
req = new XMLHTTPRequest();
} catch(err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
var http = getXMLHTTPRequest();
function getServerTime() {
var myurl = 'telltimeXML.php';
myRand = parseInt(Math.random()*9999999999999);
var modurl = myurl+"?rand="+myRand;
http.open("GET", modurl, true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}
function useHttpResponse() {
if (http.readyState == 4) {
if(http.status == 200) {
var timeValue = http.responseXML
.getElementsByTagName("timenow")[0];
document.getElementById('showtime').innerHTML
=timeValue.childNodes[0].nodeValue;
}
}
else {
document.getElementById('showtime').innerHTML = '<img src="anim.gif">';
}
}
</script>
<title>Ajax</title>
<style>
.displaybox {
width:150px;
background: #ffffff;
border:2px solid #000;
padding:10px;
font:24px normal verdana, helvetica, arial, sans-serif;
margin: 0 auto;
}
</style>
</head>
<body style="background-color:#cccccc; text-align:center">
<h1>Ajax</h1>
<h2>Hamta tiden fran servern utan att uppdatera sidan</h2>
<form>
<input type="button" value="Hamta tiden fran servern" />
</form>
<div id="showtime" class="displaybox"></div>
</body>
</html>
And here is the .PHP code.. (telltimeXML.php)
<?php
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" ?><clock1><timenow>"
.date('H:i:s)."</timenow></clock1>";
?>
You have missed to close the ' in date finction in telltimeXML.php file .Replace this :
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" ?><clock1><timenow>".date('H:i:s)."</timenow></clock1>";
with
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" ?><clock1><timenow>".date('H:i:s')."</timenow></clock1>";
I think you are missing some parentheses at the end of this line:
http.onreadystatechange = useHttpResponse;

Categories