How to submit the php page from jquery confirmation box? - php

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

Related

PHP Ajax function not posting data

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/

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.

How to submit a form using jquery dialog button?

Hello guys just want to ask about how can i process a form submission using the jquery dialog button. In my code I have a button that when you click. It will pop up a form in a dialog box. Below is the jquery buttons for OK and CANCEL. My problem is I can't submit my form the only option that I have is to create a submit button inside my form. But i want to use the jquery button instead. Im using CodeIgniter I hope you can help me.
My view (showAllSuppliers.php)
/* FOR ADD PAGE */
$(".hero-unit input[name=add_supplier]").on('click',function(){
$('#popup').load("<?php echo site_url("supplier_controller/addNewSupplier/"); ?>").dialog({
title: "Add New Supplier",
autoOpen: true,
width: 800,
modal:true,
position: "center",
buttons: {
OK: function(){
$("#addSupplier").submit(); //HOW CAN I SUBMIT MY FORM USING THIS?
},
CANCEL: function() {
$(this).dialog( "close" );
}
}
});
});
my form (addNewSupplier.php)
<?php
$attr = array('id'=>'addSupplier');
echo form_open('supplier_controller/insertNewSupplier');
..
..
..
... MY TEXTBOX FIELDS HERE
..
..
//echo "<input type='submit' value='ADD' />"; ANOTHER OPTION FOR SUBMISSION
echo form_close();
?>
my controller function(supplier_controller.php)
public function insertNewSupplier(){
$this->supplier_model->insertNewSupplierDetail();
redirect('supplier_controller/index','refresh');
}
Try by just changing this line and your usual js:
$attr = array('id'=>'addSupplier');
echo form_open('supplier_controller/insertNewSupplier', $attr);
If still does not submits the form then try to submit by ajax call.
$(".hero-unit input[name=add_supplier]").on('click',function(){
$('#popup').load("<?php echo site_url("supplier_controller/addNewSupplier/"); ?>").dialog({
title: "Add New Supplier",
autoOpen: true,
width: 800,
modal:true,
position: "center",
buttons: {
OK: function(){
$.ajax({
url : '<?=base_url()?>supplier_controller/insertNewSupplier',
type : 'POST',
data : $("#addSupplier").serializeArray(),
success : function(resp){
alert("Submitted !!!");
$(this).dialog( "close" );
},
error : function(resp){
//alert(JSON.stringify(resp));
}
});
},
CANCEL: function() {
$(this).dialog( "close" );
}
}
});
});
You need ajax call
$('#submit').click(function (){
var first_name = $('#first_name').val();
$.ajax({
url : '/supplier_controller/insertNewSupplier,
type : 'post',
data : first_name,
success : function(){
//do something;
console.log(first_name);
}
})
return false;
});
That's gonna work if you ad id to submit button and to your input. But you can also call them via html tags. It's just an idea or example for you.
If you want to use classic form submission instead of ajax call, write these code lines for the buttons parameter:
buttons: {
OK: function(){
$(this).dialog().find('form').submit();
},
CANCEL: function() {
$(this).dialog( "close" );
}
}

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.

How to request page content by clicking a div with jQuery mobile?

I am trying to fetch data form a callback page (php) and load it into a html div with jQuery mobile. This should happen if a user clicks on another div.
What I actually got is
$.('#home-button').bind('vclick', function( e ) {
$.get('homeCallback.php',function(data){
$('#displayContent').append(data).trigger('create');
},'html');
});
Where #home-button is the div that should trigger the event and #displayContent the div where the content should be put in.
The request should be able to pass some parameters, too. Like homeCallback.php?param=1 but it could also use the post method.
The callback does not have to be html only, it could also be possible that the callback php script provides JSON data or anything.
I am not a JS crack so I have problems solving this issue. Thanks for your help!
Edit:
So I found a solution on my own:
$(document).ready(function() {
$.ajaxSetup ({
cache: false
});
var ajaxLoader = '<img src="images/ajax-loader.gif" alt="loading.." />';
var loadUrl = "homeCallback.php";
$('#home-button1').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option1',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
$('#home-button2').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option2',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
});
And this is what homeCallback.php simply does..
<?php
if( isset($_GET["option1"] ))
echo "option1";
if( isset($_GET["option2"] ))
echo "option2";
So far.
$.('#home-button').bind('click', function() {
$.ajax({
url: "homeCallback.php",
type: "POST",
data: ({param: 1, param2: 2}),
success: function(html){
$("#displayContent").html(html);
}
});
});

Categories