PHP Ajax function not posting data - php

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/

Related

Passing form info from UI Dialog via AJAX

I have the following code:
HTML
<div id="resume-begin" style="background:#CCCCCC; display:inline-block;">
<img src="/images/plus-plus.png" style="display:inline;" class="trigger"/>
</div>
<div class="input-resume-data" style="display:none;">
<form id="project-form">
<label for="resume-create-name">Resume Project Name:</label>
<input type="text" id="resume-create-it" name="resume-create-it" class="text ui-widget-content ui-corner-all">
</form>
</div>
jQuery
<script>
$(document).ready(function() {
$('#resume-begin').click(function() {
('#resume-begin').hide();
$('.input-resume-data').dialog("open");
});
});
</script>
Once the div resume-begin is clicked, it opens my UI Dialog box, which is as follows:
<script>
$(function() {
$( ".input-resume-data" ).dialog({
title: 'Name your Resume Project',
autoOpen: false,
resizable: false,
height: 450,
width: 380,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
buttons: {
"Submit": function() {
var $this = $(this);
var string = $('#resume-create-it').serialize();
$.ajax({
url: 'functions.php',
type: 'POST',
data: string,
success: function(data){
alert("Project created!");
$this.dialog('close');
}
});
},
Cancel: function() {
$( this ).dialog( "close" );
$( "#resume-begin" ).show( "slow", function() {
}); //end function
} //end cancel button
} //end buttons
}); //end dialog
}); //end jquery function
</script>
What I would like:
Once the user enters the text in the UI-input, and clicks Submit, I want to post the data to the PHP page, where I would save it to the database. Currently, if I enter in data and push submit, the success function works, but the data is not saved in the database.
In my PHP, I try to grab the data like:
//Sanitize the POST values
$resumeProjectname = $_POST['resume-create-it'];
I am unsure if I am passing the data correctly, which is through the variable "string" in jQuery, as well as if I'm retrieving the data correctly in the php file.
Any help would be greatly appreciated. Please let me know if you have any questions!
Thanks.
From my view i found two errors
('#resume-begin').hide();//$ missing
and another
var string = $('#resume-create-it').serialize();
should be
var string = $('#project-form').serialize();
As serialize applies to Form.
https://api.jquery.com/serialize/
To send your data do the following
data: {
resume_name: string
},
dataType: "json"
And then in PHP access it with
$resume_name = $_POST['resume_name'];
And as a final note, I wouldn't call a variable string since string is a keyword in many languages. At first I thought you were trying to tell it that the data you're sending is a string. Also don't call the response from the server data because you use the word data two lines above it. Use something like response.
I should mention
You don't have to use JSON. You can use other data types but that is one of the critical pieces that you are missing. You need to set the dataType so that jQuery knows how to format your response. I personally think that since you are using JavaScript to begin with it makes sense to use JavaScript Object Notation.

Running PHP code with AJAX in real time?

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...?

Multiple Ajax Calls while one Ajax call is still running

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 :]

How to submit the php page from jquery confirmation box?

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');
}
});

How to display PHP message after jQuery loading?

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.

Categories