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();
Related
I have a form with inputs and a textarea (ckeditor), after submitting the form with ajax all input fields value are sent to database table except CKEDITOR textarea and I can't figure out why!
I've tried some solutions in some questions here with same problem but with no vein!
HTML PART
<form id="submitForm">
... some inputs ...
<textarea class="form-control" name="details" rows="6" id="product-details"></textarea>
<button class="btn btn-solid btn-rounded" id='publish' type="submit"> SAVE </button>
</form>
JS PART
$(document).ready(function() {
ClassicEditor.create( document.querySelector("#product-details"), {
toolbar: {
items: [
"heading", "|",
"alignment", "|",
"bold", "italic", "strikethrough", "underline", "subscript", "superscript", "|",
"link", "|",
"bulletedList", "numberedList", "todoList",
"-", // break point
"fontfamily", "fontsize", "fontColor", "fontBackgroundColor", "|",
"code", "codeBlock", "|",
"insertTable", "|",
"outdent", "indent", "|",
"uploadImage", "blockQuote", "|",
"undo", "redo"
],
shouldNotGroupWhenFull: false
}
});
$("#submitForm").on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax/create-product.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$("#publish").prop("disabled", true);
},
success: function(response) {
if (response.status == '1') {
Command: toastr["success"](response.message, "")
window.location.href = response.url;
} else {
$("#publish").prop("disabled", false);
Command: toastr["error"](response.message, "")
}
}
});
});
});
It's not working because the value of the editor is not exposed directly to the textarea beneath. I think there is some option for that, but this will work as well: copy the value upon submit to an hidden control.
var instance;
$(document).ready(function() {
ClassicEditor.create(document.querySelector("#product-details")).then(editor => instance = editor);
$("#submitForm").on('submit', function(e) {
e.preventDefault();
document.querySelector("[name=details").value = instance.getData();
$.ajax({
type: 'POST',
url: 'ajax/create-product.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$("#publish").prop("disabled", true);
},
success: function(response) {
if (response.status == '1') {
Command: toastr["success"](response.message, "")
window.location.href = response.url;
}
else {
$("#publish").prop("disabled", false);
Command: toastr["error"](response.message, "")
}
}
});
});
});
textarea {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/34.2.0/classic/ckeditor.js"></script>
<form id="submitForm">
<textarea class="form-control" name="details-editor" rows="6" id="product-details"></textarea>
<p>this textarea should be hidden:</p>
<textarea name="details"></textarea>
<button class="btn btn-solid btn-rounded" id='publish' type="submit"> SAVE </button>
</form>
I have created some ajax that uploads an image and loads it into the page.
It creates an images with an X button on the top corner, I am trying to get it so when this button is clicked I then run another peice of php code with will delete the correct image and reload the images.
I cant get my ajax code to pick up the php code and I am not sure why.
Any pointed would be very helpful.
I have found out that dymanically created elemets will not be picked up so had to change my ajax code to
$("body").on("click", "#deleteform button", function(e){
so I am hitting this point but but it sill is not picking up my php code and I dont know why.
Any pointers would be very helpful
AJAX JS:
$(document).ready(function(){
$("#uploadForm").on('submit',function(e) {
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_add_image.inc.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
});
});
$(document).ready(function(){
$('button.deleteimage').on('click', function(){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer"+image_id).html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="include_advert/advert_js/advert_gun_load_save_images.js"></script>
<div class="bgColor">
<form id="uploadForm" action="include_advert/advert_new_gun_add_image.inc.php" method="post" class="login-form" enctype="multipart/form-data">
<div id="targetLayer" class=col> </div>
<div id="uploadFormLayer">
<input name="file" type="file" class="inputFile" /><br/>
<div class="text-center">
<input type="submit" name="submit" value="UPLOAD" class="btn btn-common log-btn">
</div>
</form>
advert_new_gun_add_image.inc.php:
<?php
$imagecount = 0;
echo ('<div class=row sm>');
foreach ($getadvertimages as $getadvertimages_row) {
echo ( '<div class="image-area" >
<form id="deleteform'.$getadvertimages_row['image_id'].'" method = "POST" action ="include_advert/advert_new_gun_delete_image.php" >
<img src="'. $getadvertimages_row['image_src'] . '" alt="Preview">
<button onclick = "" name="deleteimage" id="deleteimage" value="'. $getadvertimages_row['image_id'] . '" class="remove-image" style="display: inline;" >X</button>
</form>
</div>');
}
echo ('</div>');
advert_new_gun_delete_image.php:
<?php
if (isset($_POST['deleteimage']) ){
echo('hello');
}?>
I am expecting when I click the button on the image it will run the advert_new_gun_delete_image.php file without reloading the complete page
The Above Answer was almost there but I had to change the $('button.delete-button').on('click', function(){ to $("body").on("click", "#deleteimage", function(e){
And I also removed:contentType: false, cache: false,processData:false,
Thanks Ghulam for the push in the right direction
$(document).ready(function(){
$("body").on("click", "#deleteimage", function(e){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id },
success: function(data)
{
$('#imageareadiv').hide();
$("#targetLayer").html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
$(document).ready(function(){
$('button.delete-button').on('click', function(){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer"+image_id).html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
include 'advert_new_gun_save_image_script.inc.php';
include 'advert_new_dropdown_populate/advert_new_gun_image_populate.php';
$imagecount = 0;
echo ('<div class=row sm>');
foreach ($getadvertimages as $getadvertimages_row) {
echo ( '<div class="image-area" >
<form id="deleteform'.$getadvertimages_row['image_id'].'" method = "POST" action ="include_advert/advert_new_gun_delete_image.php" >
<img src="'. $getadvertimages_row['image_src'] . '" alt="Preview">
<button type="button" name="deleteimage" value="" class="remove-image delete-button" style="display: inline;" >X</button>
</form>
</div>');
}
echo ('</div>');
Similarly you can make "targetLayer" dynamic with image_id value just like I did with form's attribute id deleteform.
$(document).delegate('#deleteform button', 'click', function (e) {
instead of
$("body").on("click", "#deleteform button", function(e){
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);
}
});
});
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
}
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
...