Passing variables to a PHP file through jQuery - php

Really not familiar with jQuery. Is there anyway I can pass form data to a PHP file using jQuery?
FORM:
<div id="dialog-form" title="Fill in your details!">
<form>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name"/>
<label for="email">Email</label>
<input type="text" name="email" id="email" value=""/>
<label for="phone">Phone</label>
<input type="phone" name="phone" id="phone" value=""/>
</fieldset>
</form>
It's a pop-up dialog with jQuery and gets submitted with:
$("#dialog-form").dialog({
autoOpen: false,
height: 450,
width: 350,
modal: true,
buttons: {
"Sumbit": function() {
//VALIDATES FORM INFO, IF CORRECT
if (Valid) {
$.ajax({
url: 'process-form.php',
success: function (response) {
//response is value returned from php
$("#dialog-success").dialog({
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
}
});
$(this).dialog("close");
}
}
}
});
What I want to do is to send the form data that the user enters into process-form.php, where it will be processed and sent as an email (which I can do). Just not to sure on the jQuery side of things. Is it even possible?

You can use the .serialize() function
$('yourform').serialize();
Docs for .serialize() here
You would use it like this :
$.ajax({
url: 'process-form.php',
data: $('form').serialize(), // **** added this line ****
success: function (response) { //response is value returned from php
$("#dialog-success").dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
}
});

Yes, you can use the jQuery .post() method, which is detailed here
$.post( "process-form.php", $( "#dialog-form" ).serialize( ) );

Given your current code the easiest way is to serialize the form into the data property:
[...]
url: 'process-form.php',
data: $('#dialog-form').serialize()

You're on the right lines with $.ajax, but you need to actually pass the data with the submission, which you haven't done so far. You're best off setting the 'type' as well.
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 450,
width: 350,
modal: true,
buttons: {
"Sumbit": function() {
//VALIDATES FORM INFO, IF CORRECT
if (Valid ) {
$.ajax({
url: 'process-form.php',
type: "post",
data: {
name: $('[name=name]').val(),
email: $('[name=email]').val(),
phone: $('[name=phone]').val(),
},
success: function (response) { //response is value returned from php
$( "#dialog-success" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
}
});
$( this ).dialog( "close" );
}
These variables should now be available in your PHP script as $_POST['name'], $_POST['email'] and $_POST['phone']

Whats the point for form if you're sending with ajax?
On the problem now, get the inputs by:
var fields = [];
$("#dialog-form form fieldset > input").each(function() {
fields.push( $(this)[0].value );
});
...
$.ajax({
url: 'process-form.php',
data:fields
...

Related

php-jquery autocomplete the textbox from database

I want to auto load the text box with some database values. I tried with following code but not getting the values for autocomplete. I used firebug to debug the script but neither it is showing error nor I am getting results.
Here is the code-
<script src="js/jquery1.10.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script>
$('#userlist').autocomplete({
source: function( request, response ) {
//alert('hi')
$.ajax({
url : 'ajax.php',//?action=getUsers',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'users'
},
success: function( data ) {
//alert('in');
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
</script>
<form action="search_result.php" name="searchform" method="post">
<input id="userlist" type="text" class="form-control txt-auto"/>
</form>
You have to wait for $('#userlist') to be created :
$(document).ready(function(){
$('#userlist').autocomplete({
// code ...
});
});

Jquery Submit Ajax

I can't seem to make this to work. I'm trying to submit form using jquery dialog and I want to receive in php so I can use $_POST.
Any idea?
HTML:
<div id="table_rows_form">
<form id="fieldsform" action="system/create">
<label for="fields">How many fields are needed?</label>
<input type="text" id="fields" name="fields" />
<button type="submit">Submit</button>
</form>
</div>
Javascript:
$(document).ready(function() {
$('#table_rows').on('click', function() {
$('#table_rows_form').dialog({
open: function() {
$(this).find('[type=submit]').hide();
},
draggable: true,
modal: true,
resizable: false,
closeOnEscape: false,
width: 'auto',
minHeight: 235,
title: 'Number of Fields',
dialogClass: 'no-close',
buttons: {
"Send": function() {
$('#fieldsform').submit(function(event) {
var formData = {
'fields': $('input[name=fields]').val()
};
$.ajax({
type: 'POST',
url: $('#fieldsform').attr('action'),
data: formData,
dataType: 'json',
encode: true
});
});
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
return false;
});
});
PHP:
print_r($_POST);
The dialog opens correctly but when pressing send button doesn't do anything and doesn't gives any error at the console. Any idea about the error? I'm a newbie with jquery.
You're just adding a submit handler with your code $('#fieldsform').submit( ... ) so it doesn't trigger anything.
Rather, you should do that on document ready, and in the click handler for "Send" button, call $('#fieldsform').submit();

Email custom data through JQuery / Ajax in Wordpress

I am trying to send some custom post data from a page that displays specific posts in a jquery pop-up email.
At the moment, I have a completed HTML form , and JQuery modal box setup.
Here is this js code for this:
jQuery(document).ready(function($){
var email = $( "#email" ),
message = $( "#message" ),
allFields = $( [] ).add( email ).add( message ),
tips = $( ".validateTips" );
$( ".email-course" )
.button()
.click(function() {
$( "#dialog-form" ).dialog( "open" );
});
$( "#dialog-form" ).dialog({
autoOpen: false,
modal: true,
width: 550,
height:260,
resizable: false,
show: 'fade',
title: 'Email course',
buttons: {
"Send": function() {
//Need help here
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
});
And the HTML form:
<div id="dialog-form" title="Email this course">
<form>
<fieldset>
<label for="email">To:</label>
<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
<label for="email">From:</label>
<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
<label for="message">Message (optional)</label>
<input type="text" name="message" id="message" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
and the button:
<div class="right"><button class="email-course">Email this course</button></div>
My question is how to read the data from the form and also I will have to pull some post data with ids from the page that loads them all and send it by Wordpress's wp_email I assume? I will have to merge the "message (optional)" with that specific post ID's data as well. Any other information I need please let me know. Thanks in advance.
Background:
jQuery has a .serialize() method that:
Encode a set of form elements as a string for submission.
With the use of this method you can serialize all the fields values without having to collect them individually.
For example, you can do:
$('form').serialize()
and you will get a string with all the collected form fields & values, then you can pass this string to the server in a data: {} object inside a $.ajax request.
.serialize() documentation at jqAPI
Filling the Send callback:
"Send": function() {
//Need help here
$.ajax({
data : $('#dialog-form form').serialize(),
error : function (jqXHR, textStatus:string, errorThrown:string) {
if (errorThrown) {
// Show message.
}
},
success : function (response_from_server:ResponseFromServer, statusText:string, xhr) {
// Do post-processing here.
},
type : 'POST',
url : ajaxurl
});
},
Here:
ajaxurl: A javascrip global variable set by WordPress to be used in AJAX queries pointing to '/wp-admin/admin-ajax.php'
$('#dialog-form form').serialize() : This method is the one that will serialize all the Successfull HTML controls present in the form and will append them as data in the AJAX query.
Here only is missing the nonce checking to validate the AJAX request, I didn't put it there to make the code simple.
Then on the WordPress PHP backend you have to capture that serialize that data in order to process it as you like.
Hope it helps.

need to call ajax function from inside jquery modal dialog box

I have a dialog box that loads from an ajax call.. It works good. I want to have a link inside my dialog box that updates a DB and loads the results via ajax to the parent page, without my dialog closing. Is this even possible? Here is what I have so far.
This is what my parent page called deals_calendar.php looks like. The ajax call works fine and opens a dialog box that is loaded with content from get_deals.php.
<script type="text/javascript">
$("#calendar td").on('click', function() {
var data = $(this).data();
$.ajax({
type:"GET",
url: "get_deals.php",
data: { monthID: data.month, dayID: data.day, yearID: data.year },
success: function(data){
var title = $( "#dialog" ).dialog( "option", "title", "Deals" );
$('#dialog').dialog({
open: function (event, ui){
$('a').blur();
$(this).scrollTop(0);
}
});
$("#dialog").html(data).dialog("open");
}
});
$("#dialog").dialog(
{
bgiframe: true,
autoOpen: false,
height: 450,
width:900,
modal: false,
closeOnEscape: true
}
);
});
</script>
<div id="dialog" title="Dialog Title"> </div>
<div id="return"></div>
Then in my get_deals.php script I have this
<script type="text/javascript">
$('#click').live('click', function(){
$.ajax({
type:"POST",
url: "deals_add_to_queue.php",
data: { monthID: data.month, dayID: data.day, yearID: data.year },
success: function(data){
alert("Please work!");
("#return").html(data);
}
});
});
</script>
<a id="click" href="#">click me</a>
I can't get this ajax call to fire and update the content on deals_calendar.php. Any help would be great. thanks
If the event is not being fired, you need to use event delegation.
$('body').on('click', '#click' function(){
$.ajax({
type:"POST",
url: "deals_add_to_queue.php",
data: { monthID: data.month, dayID: data.day, yearID: data.year },
success: function(data){
alert("Please work!");
("#return").html(data);
}
});
});

jQueryUI Dialog with ajax-injected html selector

All code below is a stand-alone working example (greatly simplified) of what I am trying to do. If anyone copy/pastes the below code blocks into 3 separate files, the code is fully self-contained-- just remember to reference/include test5.js and the jquery libraries in script tags at top of document.
SUMMARY: HTML div injected via Ajax not opening in the jQuery UI dialog widget.
Objective: On document load, jquery-ajax injects an html form (ultimately, it will retrieve appropriate form values from DB which is the reason for ajax). A div with id="clickme" is injected with the html. Clicking the div should open the dialog.
Problem: The jQueryUI .dialog does not appear. I put an alert box inside the click event, and that fires. But the dialog remains elusive.
Therefore, problem appears to be the fact that the HTML is injected. What am I missing?
HTML: index.php
<div id="putit_here">
</div>
JAVASCRIPT/JQUERY: test5.js
$(function() {
var pih = $('#putit_here');
$.ajax({
type: "POST",
url: "ajax/ax_test5.php",
data: 'contact_id=1',
success:function(data){
pih.html(data);
var etc1 = $( "#editThisContact_1" );
/* *****************************************************************
Moving Dialog up >here< was correct answer.
********************************************************************
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
****************************************************************** */
}
}); //End ajax
/* **** This is where I had it previously ***** */
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
$(document).on('click', '#clickme', function(event) {
alert('HereIAm...');
$( "#editThisContact_1" ).dialog( "open" );
}); //End #clickme.click
}); //End document.ready
AJAX - ax_test5.php
$rrow = array();
$rrow['contact_id'] = 1;
$rrow['first_name'] = 'Peter';
$rrow['last_name'] = 'Rabbit';
$rrow['email1'] = 'peter.rabbit#thewarren.nimh.com';
$rrow['cell_phone'] = '+1.250.555.1212';
$r = '
<div id="editThisContact_'.$rrow['contact_id'].'" style="display:none">
<p class="instructions">Edit contact information for <span class="editname"></span>.</p>
<form name="editForm" onsubmit="return false;">
<fieldset>
<span style="position:relative;left:-95px;">First Name:</span><span style="position:relative;left:10px;">Last Name:</span><br />
<input type="text" id="fn_'.$rrow['contact_id'].'" value="'.$rrow['first_name'].'" name="fn_'.$rrow['contact_id'].'">
<input type="text" id="ln_'.$rrow['contact_id'].'" value="'.$rrow['last_name'].'" name="ln_'.$rrow['contact_id'].'"><br /><br />
<span style="position:relative;left:-120px;">Email:</span><span style="position:relative;left:30px;">Cell Phone:</span><br />
<input type="text" id="em_'.$rrow['contact_id'].'" value="'.$rrow['email1'].'" name="em_'.$rrow['contact_id'].'">
<input type="text" id="cp_'.$rrow['contact_id'].'" value="'.$rrow['cell_phone'].'" name="cp_'.$rrow['contact_id'].'">
</fieldset>
</form>
</div>
';
echo $r;
EDIT:
Updated question to move dialog definition inside AJAX success callback. Did not completely solve problem, though. The dialog now appears if I change the autoOpen flag to true, but that is not how the script must work. The dialog still does not open upon clicking the (injected) #clickme div.
EDIT 2:
My bad. At first I thought it didn't work, but then found that my live test and posted SO question varied in one line: how the .dialog("open") was being called. In live code, it was still using the var: etc1.dialog("open") -- but in post above the selector was fully referenced: $('#editThisContact_1').dialog("open"). The posted syntax was correct. Thanks gents, and also itachi who got me to check chrome console.
You are trying to initialize a dialog on an element before the element exists. You need to initialize the dialog on "#editThisContact_1" after your ajax call comes back successfully.
Like this:
....
success:function(data){
pih.html(data);
//now your DIV is actually there so init the dialog
var etc1 = $( "#editThisContact_1" );
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
}

Categories