I am working on a project of web calendar. I want to add my php database file to the java script file. When I click on the save button of calendar, the entries showed in calendar, but I m unable to add PHP file to save button. So when I click on save button, the entry should go to the database(php file).
code goes here:-
buttons:
{
save : function()
{
calEvent.id = id;
id++;
calEvent.start = new Date(startField.val());
calEvent.end = new Date(endField.val());
calEvent.title = titleField.val();
calEvent.body = bodyField.val();
$calendar.weekCalendar("removeUnsavedEvents");
$calendar.weekCalendar("updateEvent", calEvent);
$dialogContent.dialog("close");
},
cancel : function() {
$dialogContent.dialog("close");
}
}
There is no such thing as a "PHP database", and you cannot add PHP to your JavaScript file.
Your save button needs to send data to a PHP via page via HTTP, either by regular post-back or AJAX. The page will reside and execute on your server, while the JavaScript calendar executes in the client's browser. That PHP page can then talk to a database server to store/retrieve data for you.
Your server must:
be set up to execute PHP files correctly
have a running database server (PostgreSQL, MySQL, etc)
have a database and table in which to hold your data
You must understand that a database is at the server end (sometime the web server).
It could by Sybase, MySql, SQLite, ...
Nothing to do with the server.
Javascript on the browser can and sometimes is turned off. It just makes it easier and more interactive to use the web pages.
So why should summat go to a php file? This makes no sense along with php base. Please have a little reflection on the various technologies involved.
Related
I can't find on the web so I'm asking some help over here.
I'd like to create a log file, when someone press on a button it will a text to a log.txt file.
I'm just looking for the the base code based on Jquery ajax and PHP
Thanks
there is no base code for jquery logging to sever
first of, you have to decide how many times you want to call the server,
each log entry will be too much load on server,
append all to js array and post on session ending? when doe's session ends? and what if user closes browser? all the log gone? (see my suggestion bellow)
you'll have to make an endpoint on server to get log entries and append them to file, then you should think of storage, and how to organize log enries from multiple clients
I would recomend using log4javascript library with AjaxAppender, see example here, you can then use setBatchSize to send in batches or setTimed to send with time intervals, see documentation here, also you can setSendAllOnUnload to don't lose messages on browser close (in most cases).
in the server i would use log4php with LoggerAppenderRollingFile see here
I don't have to time to code it for you but here is the basic logic. You can look up how to do each item individually.
You need to add an event listener with jquery for the click event and bind it to the button.
Inside that, have an ajax request to some endpoint or script on your server that will update the log file.
When that script is executed (via the ajax call), you can have PHP open the file and append a line to it that has whatever data you want.
JavaScript:
$('button').on('click', function() {
$.ajax({
// do ajax request here
});
});
PHP:
$file = fopen("log.txt","rw");
$fileContents = fread($file, filesize("log.txt"));
fwrite($file, $fileContents."Someone clicked button\r\n");
fclose($file);
Something like that. Sorry for not giving a full explanation but I hope it helps.
the log file will be in notepad format the values will be like this 11.23445646,56.3456578954
10.23445646,26.3456578954
16.23445646,-46.3456578954
I'm planning to get the data from server to website textbox, of first value which I marked as italic the values will change after few seconds the updated value will come first. I tried some PHP example but not getting it in the below text box the values I need to get.. for example: x=11.23445646, y=56.3456578954, pls guide me
Longtitude <input id="x" type="number" value = "" onkeyup="updateMarker('x')">
Latitude <input id="y" type="number"value = "" onkeyup="updateMarker('y')">
Updated Answer
You can do this now using Web Socketing. Here is a guide and hello-wrold example of a php websocket server:
http://socketo.me/docs/hello-world
And to see how to implement client side javascript of websocket, you can see the bottom of the link put above, which shows you this snippet:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
Old
PHP does not support live connections generally in the way you expect, you have to simulate it via repeated AJAX request. How? For instance on each second, or each two seconds.
You first have to write an ajax in your HTML with jQuery library:
Sending a request each second:
var url = "url_to_you_file";
var textarea_id = "#textarea";
setInterval(function(){
$.ajax({
url : "site.com/get-file-logs.php",
type : "POST",
success : function(data){
$(".textarea").html(data);
}
});
}, 1000);
Then in PHP file you would write this:
$file_path = "path_to_your_file";
$file_content = file_get_contents($file_path);
echo $file_content;
The above example gets the file content and sends it back to your browser. You may want to process it in a certain way; that then changes your approach a little bit. Because you must always stick to JSON format when you try to get data back from server to be manipulated by Javascript.
PHP doesn't really do "live" page updates since normally when a web browser (or other user agent) loads a web page once it's done downloading the page then PHP is already finished and can't touch what's already on the client.
Best way to do this would probably be to use a JavaScript AJAX call to periodically load the updated values from a PHP script and then update the values on the page.
Or if it's a really small page (in byte size) you could just make it automatically reload the whole page (with updated values) if that is not a problem for you.
In any case every time the PHP script is called it would just open the file in read mode and only read the latest values from the beginning of the file and return those. See fread(). Or maybe file_get_contents() or file() would be easier and just read the first line.
AJAX is a bit larger topic and I don't currently have the time to explain the whole process of updating the page using JavaScript. Google is your friend.
for a project at school I am trying to make a website that can show your grades in a prettier way than it's being done now.
I have been able to log in to the site using cURL and now I want to get the grades in a string so I can edit it with PHP.
The only problem is that cURL gets the html source code when it hasn't been edited by the javascript that gets the grades.
So basically I want the code that you get when you open firebug or inspector in a string so I can edit it with php.
Does anyone have an idea on how to do this? I have seen several posts that say that you have to wait till the page has loaded, but I have no clue on how to make my site wait for another third-party site to be loaded.
The code that I am waiting to be executed and of which I want the result is this:
<script type="text/javascript">
var widgetWrapper = $("#objectWrapper325");
if (widgetWrapper[0].timer !== undefined) {
clearTimeout( jQuery('#objectWrapper325')[0].timer );
}
widgetWrapper[0].timer = setTimeout( function() {
if (widgetWrapper[0].xhr !== undefined) {
widgetWrapper[0].xhr.abort();
}
widgetWrapper[0].xhr = jQuery.ajax({
type: 'GET',
url: "",
data: {
"wis_ajax": 1,
"ajax_object": 325,
'llnr': '105629'
},
success: function(d) {
var goodWidth = widgetWrapper.width();
widgetWrapper.html(d);
/* update width, needed for bug with standard template */
$("#objectWrapper325 .result__overview").css('width',goodWidth-$("#objectWrapper325 .result__subjectlabels").width());
}
});
}, 500+(Math.random()*1000));
</script>
First you have to understand a subtle but very important difference between using cURL to get a webpage, and using your browser visiting that same page.
1. Loading a page with a browser
When you enter the address on the location bar, the browser converts the url into an ip address . Then it tries to reach the web server with that address asking for a web page. From now on the browser will only speak HTTP with the web server. HTTP is a protocol made for carrying documents over network. The browser is actually asking for an html document (A bunch of text) from the web server. The web server answers by sending the web page to the browser. If the web page is a static page, the web server is just picking an html file and sending it over network. If it's a dynamic page, the web server use some high level code (like php) to generate to the web page then send it over.
Once the web page has been downloaded, the browser will then parse the page and interprets the html inside which produces the actual web page on the browser. During the parsing process, when the browser finds script tags it will interpret their content as javascript, which is a language used in browser to manipulate the look of the web page and do stuff inside the browser.
Remember, the web server only sent a web page containing html content he has no clue of what's javascript.
So when you load a web page on a browser the javascript is ONLY interpreted once it is downloaded on the browser.
2. What is cURL
If you take a look at curl man page, you'll learn that curl is a tool to transfer data from/to servers which can speak some supported protocols and HTTP is one of them.
When you download a page with curl, it will try to download the page the same way your browser does it but will not parse or interpret anything. cURL does not understand javascript or html, all it knows about is how to speak to web servers.
3. Solution
So what you need in your case is to download the page like cURL does it and also somehow make the javascript to be interpreted as if it was inside a browser.
If you had follwed me up to here then you're ready to take a look at CasperJS.
I've been working on a project for a couple of Minecraft servers that use Bukkit. I'm trying to create a web page that contains a dynamic map of the servers' worlds, as well as a real-time event update system, where a <div> is updated as events happen on the server. To give a brief outline of how my system works, the Minecraft servers communicate events with a Node.js webserver over the same network via UDP packets, and the Node.js webserver uses these packets to build JavaScript objects containing the event info. The objects are then stored, and passed to Jade whenever the page is requested. Jade takes care of the templating.
What I want to do is update this page dynamically, so that the user doesn't have to refresh the entire page to update the list of events. What I'm trying to implement is something like the Facebook ticker, which updates every time a Facebook friend does something like posting a status, commenting on a post, or 'liking' a post.
In reading this question on SO, I've concluded that I need to use long polling in a PHP script, but I'm not sure of how to integrate PHP with a webserver written almost entirely in Node.js. How could I go about doing this?
EDIT:
I've run into a problem in the clientside code.
This is the script block:
script(src='/scripts/jadeTemplate.js')
script(src='/socket.io/socket.io.js')
script(type='text/javascript')
var socket = io.connect();
socket.on('obj', function(obj) {
var newsItem = document.createElement("item");
jade.render(newsItem, 'objTemplate', { object: obj });
$('#newsfeed').prepend(newsItem);
console.log(obj);
alert(obj);
});
And this is objTemplate.jade:
p #{object}
// That's it.
When the alert() and console.log() are placed at the top of the script, it alerts and logs, but at the bottom, they don't execute (hence, I think it's a problem with either the creation of newsItem, the jade.render(), or the prepend.
If I need to provide any more snippets or files let me know. I'm still tinkering, so I might solve it on my own, but unless I update, I still need help. :)
I'd skip PHP and take a look at socket.io. It uses websockets when possible, but it will fall back to long-polling when necessary, and the client side library is very easy to use.
Whenever your node.js server has a new object ready to go, it will push it to all connected browsers. Use ClientJade to render the object using your template (you may have to break out the relevant part of the main template into its own file), then prepend the generated dom element to your feed.
First, if it isn't this way already, you'll need to break out the relevant part of your jade template into its own file. Call it objTemplate.jade. Then use ClientJade to create a compiled template that can be run in the browser: clientjade objTemplate.jade > jadeTemplate.js. Put jadeTemplate.js in your public js directory.
In your node.js app, you'll have something like this (pseudo-codey):
var io = require('socket.io').listen(httpServer);
listenForUDPPackets(function(obj) {
saveObjSomewhere(obj);
io.sockets.emit('obj', obj);
});
Then on the client, something like this:
<script src="/js/jadeTemplate.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('obj', function(obj) {
var newsItem = document.createElement();
jade.render(newsItem, 'objTemplate', obj);
$('#newsFeed').prepend(newsItem);
});
</script>
I have:
PHP Socket Server
PHP Pages to handle communication with server & db
Client .php page, which uses javascript/canvas to display & interact with a game.
What I want is for the user to connect and authenticate using the PHP pages which will initiate a socket connection to the server. Based on the information from that socket some chat info and events might be triggered to load data into client php page.
What is the right way to handle this. In all instances that I've ajax in before, the user triggers the event, not the server and javascript waits around for the php page's response.
What piece of php code from the php socket lets me send messages to the canvas elements?
Here's an example as the above is probably not very illuminating:
IE:
PHP reads off of its socket connection {"name":"msg","from":"user1","time":12345,"msg","hello world"}
At this point what does PHP do?** So that ...
The client has a div with "id='Incoming'"
I want to launch the following javascript:
function handleMessage(msgObj) {
var cText = document.getElementById("Incoming").innerHTML;
cText += "(" + msgObj.time + ")" + msgObj.from + " says: " + msgObj.msg +"<br/>";
document.getElementById("Incoming").innerHTML = cText;
}
I guess I'm trying to figure out how a client's web page is supposed to talk back to the php sockets...
Is this possible or do I need to make a client in flash, java, etc?
You send stuff from client to server when you've got data to send (e.g. user submits a button) typically via an event handler. The websocket also fires event when it receives data from the server (socket.onmessage). Simples.
ws.onmessage=function (evt) { handleMessage(evt.data); };
(or just change your handleMessage function body to use msgObj.data as the text value)
What piece of php code from the php socket lets me send messages to the canvas elements?
What websocket implementation are you using? They all have different APIs (NB a websocket is not the same thing as a network socket)
You should use Comet:
http://en.wikipedia.org/wiki/Comet_(programming)
AJAX is much better and also asynchronous
http://www.ape-project.org/
http://www.stream-hub.com/
...
http://cometdaily.com/maturity.html
or use HTML5 WebSockets