I am newbie at PHP. I wanted to build a small project of room booking, and improve it by using AJAX.
http://img851.imageshack.us/img851/6172/88303815.png
I'm trying to display an alert message every time someone is reaching the limit of two hours room time. The registration div is where all the PHP is taking care of the "Get Room" action. My problem is that the room_per_user function does not show the correct amount of rooms per user unless I refresh the page.
How can i correct my code to present the error message?
$("#formReg").ajaxForm({
url: "room.php",
type: "POST",
beforeSubmit: disableButtons,
success: function(data) {
$("#registration").load("room.php #registration", function() {
$(function() {
<?php
if(rooms_per_user($_SESSION['user_id'])>=2)
{
$string = "\$(\"#dialog-message\").find('.error').show();";
echo $string;
}
?>
$( "input:submit, a, button", ".registration" ).button();
$( "a", ".registration" ).click(function() { return false; });
});
});
$("#cancellation").load("room.php #cancellation", function() {
$(function() {
$( "input:submit, a, button", ".cancellation" ).button();
$( "a", ".cancellation" ).click(function() { return false; });
});
});
});
function disableButtons(){
$('form').find('input[type="submit"]').attr('disabled', 'disabled');
}
Thank you very much, and forgive if I did some fatal mistakes ;-)
Sorry, I copied the code wrong in the PHP part (i tried to shorten it up and forgot the PHP tag)
EDIT 2: I tried to use the json encode but i don't know why it doesn't work for me... It get stuck at the submit button disabling phase. When I delete the datatype line it works fine... Help anyone? Thank you very much for your answers!
$("#formReg").ajaxForm({
url: "room.php",
dataType: 'json',
type: "POST",
beforeSubmit: function() {
$('form').find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data) {
alert(data.status);
$("#registration").load("room.php #registration", function() {
$( "input:submit, a, button", ".registration" ).button();
$( "a", ".registration" ).click(function() { return false; });
});
$("#cancellation").load("room.php #cancellation", function() {
$( "input:submit, a, button", ".cancellation" ).button();
$( "a", ".cancellation" ).click(function() { return false; });
});
}
});
David is sort of correct in his response, but I wanted to elaborate on it a little more.
What you have here is a javascript function with variable output based on the current number of rooms a user has.
The script you posted above is loaded when the user visits your page initially. Which means when they initially load the page and have no rooms reserved, the
<?php
if(rooms_per_user($_SESSION['user_id'])>=2)
{
$string = "\$(\"#dialog-message\").find('.error').show();";
echo $string;
}
?>
block of your code is going to not be output to the page. This is why your users are not seeing the alert message when they try to add additional rooms. The code that you're outputting to the page does NOT reload itself with each ajax request, but rather is static content. So as the users register additional rooms beyond 2, the JS code here:
$("#dialog-message").find('.error').show();
is never being output or used.
Typically when you do validation like this, the "correct" way is to do it server side.
So when a user tries to register a room but already has 2 of them booked, the AJAX request fires off to room.php which receives the "data" response back from the server. My suggestion would be to add a dataType to your ajaxForm parameters like this
url: "room.php",
type: "POST",
beforeSubmit: disableButtons,
dataType: 'json',
success: function(data) {
This will tell jQuery to expect a response as JSON from the server. In your script rooms.php you will then need to establish a standard data format to respond with and return it by using
echo json_encode( array( 'status' => 'OK' ) ); //tell the JS code that the status was OK
or in the event of an error:
echo json_encode( array( 'status' => 'ERROR' , 'errtxt' => 'Sorry, but you have already reserved 2 rooms.' ) ); //tell the JS code that the status was OK
So I've boiled down your JS code and removed a lot of jQuery wrappers around functions within functions that you didn't need and here's the end result:
$("#formReg").ajaxForm({
url: "room.php",
type: "POST",
beforeSubmit: function() {
$('form').find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data) {
if( data.status != 'OK' ) {
$("#dialog-message").find('.error').html(data.errtxt).show();
return;
}
$("#registration").load("room.php #registration", function() {
$( "input:submit, a, button", ".registration" ).button();
$( "a", ".registration" ).click( function(e) {
e.preventDefault();
});
});
$("#cancellation").load("room.php #cancellation", function() {
$( "input:submit, a, button", ".cancellation" ).button();
$( "a", ".cancellation" ).click(function() { return false; });
});
}
});
Couple that with the rest of the suggestions for the PHP side, and I think you'll be sittin pretty.
You appear to be mixing JavaScript with PHP:
if(rooms_per_user($_SESSION['user_id'])>=2)
Is rooms_per_user a PHP function or a JavaScript function? $_SESSION is definitely a PHP array. Anything that's in PHP is going to be meaningless to the JaveScript, and vice versa. Most likely this code is causing errors in your browser JavaScript console.
PHP executes on the server-side. When it's done executing, the page is emitted to the browser. Then the JavaScript executes in the browser. The PHP code and the JavaScript code exist in two entirely different contexts and can't be mixed like this.
Given the structure you have in your JavaScript code right now, the easiest way to achieve the desired functionality would probably be to add another call to .ajax() to call a server-side resource, get the value of rooms_per_user, set it to a JavaScript variable, and then use it (all in the success of that .ajax() call).
Basically, your JavaScript code can't talk directly to your PHP code. If there's a value that exists only on the server, you need to make a call to that server to get that value.
Related
I'm trying to use Jquery to call an ajax function, which updates an MySQL database. I have several other Ajax requests in the same file and they work fine. For some reason the getinvoices value is not being passed to the PHP file. I'm calling the function on click of a button, below is the code I'm using.
Javascript
$( "#updatexero" ).button().on( "click", function(event) {
$.ajax({
type:'post',
url: 'invoices.php',
data: { getinvoices: 1 },
success: function(){
$( "#sql-confirm" ).dialog({
modal: true,
buttons: {
OK: function() {
$( this ).dialog( "close" );
}
}
});
}
});
});
PHP - invoices.php
if ( isset($_REQUEST['getinvoices'])) {
//Code to do stuff
}
If I do echo $_POST['getinvoices'];, it says undefined index, as no value has been passed. I can't see why this shouldn't work, what am I doing wrong?
Edit: I have solved the issue now, the problem was another if statement in invoices.php that wasn't getting called, so nothing to do with the Ajax query. The firebug extension proved handy for debugging though.
Your code is correctly written.
I adopted your code "as is" and put it on my own server.
In invoices.php I simply put:
<?php
print_r( $_POST );
?>
This is the result I got when checking in the debug console:
I would advise you to use this debug console to check your AJAX request. It's included in both Chrome and FireFox. In chrome you need to install the extension Firebug Lite however.
You'll see in my picture that getinvoices is both included in the AJAX post and received by the invoices.php script.
The debug console will also alert you if there is a syntax error in your JavaScript code.
However.. you can change the following code:
$( "#updatexero" ).button().on( "click", function(event) {
to
$("#updatexero").click(function(event){
Try this:
$( "#updatexero" ).on( "click", function(event) {
$.ajax({
type:'post',
url: 'invoices.php',
data: { getinvoices: 1 },
success: function(){
$( "#sql-confirm" ).dialog({
modal: true,
buttons: {
OK: function() {
$( this ).dialog( "close" );
}
}
});
}
});
});
You have syntax error in your code .
Remove .button() as it does not match the syntax here.
Try below code :-
$("#updatexero").on("click", function(event) {
//// Your code.
});
For more information check out below link :-
http://api.jquery.com/on/
I have PHP page called (jQuery_puff.php) which only holds a javascript/jQuery in it.
The jquery in that PHP is this:
<?php
echo '<script>
$( "#myButton" ).click(function() {
$( "#myDiv" ).effect( "puff", "slow" );
$( "#myDiv" ).toggle( "puff" );
});
</script>';
?>
I have included this PHP page within another PHP file like so:
<?php include "jQuery_puff.php"; ?>
what the first code inside the jQuery_puff.php does is that it will apply a jquery puff effect to the #myDiv everytime the user clicks on the #myButton.
Everything works as they should. so far so good. but this is only happens for one user (client side).
Now My Question:
Is there any way to run this PHP page in real time for all the users using AJAX?
For example the USER 1 clicks on the #myButton and the USER 2, USER 3 etc will also see the puff effect being applied to the #myDiv ?
I thought about using something like this But this doesn't do anything!!
<script type="text/javascript">
$(document).ready(function() {
$("#myButton").click(function() {
$.ajax({
url: 'myOwn.php',
cache: false,
success: function(data) {
checkForNewData2();
}
});
});
var intervalID2 = setInterval(checkForNewData2, 500);
});
function checkForNewData2() {
$.ajax({
url: 'jQuery_puff.php',
dataType: 'json',
cache: false,
success: function(data) {
$("#data").html(data.data);
}
});
}
</script>
am I in the right direction? or...?
I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.
I got some progressbar Update Issues. What I like to do is, fire a ajax call which takes some time to complete and during the this call I'd like to fire ajax calls, set by an interval, to update my progressbar.
Since I could not find a solution and only found the Browser's restriction, which would match here. It's always max 2 calls active.
Still, my second call stays pending in Google Chrome, untill my first (main) call finished.
EDIT: full jquery script
// update cars cache
$('#cars_cache_update_run').bind('click', function(){
// remove button
$(this).remove();
// hide import widgets
$('#products_import_widget').css('display', 'none');
$('#vehicles_import_widget').css('display', 'none');
$('#orders_import_widget').css('display', 'none');
$('#test_data_widget').css('display', 'none');
// show blind
$('#cars_cache_update_info').css('display', 'none');
$('#cars_cache_update_blind').css('display', 'inline');
var carsUpdateInterval = setInterval(function() {
getImportState('http://localhost/index.php/import/import_state/cache_update', 'cars_import_progressbar');
}, 1000);
// ajax request
$.ajax({
url: "http://localhost/index.php/import/cars_cache",
async : true,
success: function(data){
$('#cars_cache_update_blind').css('display', 'none');
$('#cars_cache_update_success').css('display', 'inline');
clearInterval(carsUpdateInterval);
},
error: function(thrownError){
$('#cars_cache_update_blind').css('display', 'none');
$('#cars_cache_update_error').css('display', 'inline');
$('#cars_cache_update_error_msg').html(thrownError);
}
});
});
function getImportState(url, id)
{
$.ajax({
url: url,
success: function(data){
var json = $.parseJSON(data);
$.each(json, function(i, item) {
var progressbar_value = json[i]['state'];
$( "#"+id ).progressbar({
value: progressbar_value
});
})
}
});
}
Another funny thing, if I call the interval request by $.get I'll get a strange error..
Working with Codeignitor Framework.
GET http://localhost/[object%20Object] 404 (Not Found) jquery.1.7.min.js:4
send jquery.1.7.min.js:4
f.extend.ajax jquery.1.7.min.js:4
f.(anonymous function) jquery.1.7.min.js:4
(anonymous function)
Many Thanks for your help already, been trying for hours now.. Maybe I'm just a noob.. Haha.
rootless
Don't call multiple ajax with intervals. Try something like this:
function updateProgress(){
$.ajax({
url: "http://localhost/index.php/import/import_state/cache_update",
success: function(data){
var json = $.parseJSON(data);
$.each(json, function(i, item) {
var progressbar_value = json[i]['state'];
$( "#cars_import_progressbar" ).progressbar({
value: progressbar_value
});
});
updateProgress(); // after success, call the same function again
}
});
}
updateProgress(); // start updateProgress
Hope it helps :]
I created a conformation box from jquery. I want to submit the page and view PHP echo message when click the confirm button in the confirmation box. Can you help me with code that comes for the confirmation button?
My jQuery/javascript function is here:
$(document).ready(function(){
$('#click').click(function(){
//$(function() {
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
$( "#dialog:ui-dialog" ).dialog( "destroy" );
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Ok": function() {
// I WANT THE CODE FOR HERE TO SUBMIT THE PAGE TO WIEW PHP ECHO MESSAGE
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
});
You can use jQuery Form submit library. This will give you many options.
And according to your requirement you can call
beforeSubmit: 'YOUR FUNCTION To OPEN DIALOG',
If this returns true your form will get post and you will definitely get response.
see example here : http://malsup.com/jquery/form/#ajaxForm
Use the jQuery Post function...
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Here is a version with a callback when the post completed...
$.post("test.php", { name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
}
);
Or if you have an existing form that you want to post use the jQuery submit function...
$("form").submit();
But before you do this you need to make sure that you populated the input fields in the form.
try this code,
var parameter_1 = 'test';
var parameter_2 = 'test';
$.ajax(
{
type: "POST",
url: "/submit_url.php",
data: "parameter_1="+ parameter_1 +"& parameter_2 ="+ parameter_2,
success: function(html)
{
alert('Submitted');
}
});