I'm trying to insert a row into my repair_history table from a form inside a dialog box using ajax.
Here is the function that opens the dialog box with the form:
<script>
$(function() {
$( "#repair-dialog" ).dialog({
autoOpen: false,
height: 300,
width: 450,
modal: true,
buttons: {
"Save": function() {
insert(
$( "#repair-dialog-date" ).val(),
$( "#repair-dialog-id" ).val(),
$( "#repair-dialog-comment" ).val(),
$( "#repair-dialog-save_type" ).val()
);
$( this ).dialog( "close" );
setTimeout(function(){location.reload(true);},500);
},
"Cancel": function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
$( "#record_repair" ).click(function() { $( "#repair-dialog" ).dialog( "open" ); });
});
function insert(date,id,comment,save_type) {
mydata = {
"date" : date ,
"id" : id ,
"comment" : comment ,
"camera_id" : "<?php= $products['camera_id']?>" };
$.ajax({
type: "POST",
url: "localhost/cibs/index.php/api/record_save/"+save_type,
data: {data:JSON.stringify(mydata)},
dataType: "json",
cache : false
});
}
and here is the function inside the api.php controller that tries to insert:
function record_save()
{
$this->load->database();
$mydata = $this->input->post('data');
$date = $mydata['date'];
$comment = $mydata['comment'];
$id = $mydata['id'];
$camera_id = $mydata['camera_id'];
$table = "repair_history";
$data = array("camera_id" => $camera_id, "repair_id" => $id, "date" => $date, "comment" => $comment);
$this->db->insert($table,$data);
}
and heres the dialog box:
<div id="repair-dialog" title="Add New Repair" style="font-size: 15px;">
<form id="repair">
<input style="height:0px; top:-1000px; position:absolute" type="text" value="">
Repair id: <input type="text" id="repair-dialog-id" /><br>
Repair date: <input type="text" id="repair-dialog-date" /><br>
Comment: <input type="text" id="repair-dialog-comment" /><br>
<input type="hidden" value="repair" id="repair-dialog-save_type">
</form>
</div>
Any replies really appreciated! Thanks! :)
You don't need stringify your object:
$.ajax({
type: "POST",
url: "http://localhost/cibs/index.php/api/record_save/"+save_type,
data: mydata,
dataType: "json",
cache : false
});
And in php:
function record_save()
{
$this->load->database();
$table = "repair_history";
$data = array(
"camera_id" => $this->input->post('camera_id'),
"repair_id" => $this->input->post('id'),
"date" => $this->input->post('date'),
"comment" => $this->input->post('comment')
);
$this->db->insert($table,$data);
}
I'm not sure how your function $this->input->post('data') works, but you are posting the data as a json string, so you should make sure that you json_decode that data first.
Replace
$mydata = $this->input->post('data');
By
$mydata = json_decode($this->input->post('data'), true);
Related
I am using the WordPrewss $wpdb class to insert data into the database. The ajax part works fine but it's not addin the data into the database.
<script>
$("#notes_maker").submit(function(){
event.preventDefault();
var formURL = "<?php echo admin_url('admin-ajax.php')?>";
var notes_editor = $("#notes_area").val();
//var note_timestamp = $(".note_timestamp").text();
$.ajax({
url: formURL,
data: {
'type': 'POST',
'action': 'notes',
'notes_editor1': notes_editor,
'dataType': 'text',
//'note_timestamp': note_timestamp,
},
success: function(data) {
alert("it works");
}
})
});
</script>
<form id="notes_maker" class="notes_section">
<div class="note_timestamp">1.40</div>
<div data-section="notes" class="js-tabs o-wrapper" id="notes">
<textarea name="notes_area1" id="notes_area">
this is some text
</textarea>
<input type="submit" name="submit" value="Save Note"/>
<input type="button" name="cancel_note" value="Cancel"/>
</div>
</form>
functions.php file
function my_ajax_notes() {
if(isset($_REQUEST)) {
$car = $_REQUEST['notes_editor1'];
echo $car;
global $wpdb;
$wpdb->insert(
$wpdb->prefix.`activity_notes`,
[
'text' => $car
]
);
}
}
add_action('wp_ajax_notes', 'my_ajax_notes');
//add_action('wp_ajax_nopriv_notes', 'my_ajax_notes');
As per my understanding of your question I have reproduced your issue and made some changes to the code. Here it is:
HTML:
<form id="notes_maker" class="notes_section" type="POST">
<div class="note_timestamp">1.40</div>
<div data-section="notes" class="js-tabs o-wrapper" id="notes">
<textarea name="notes_area1" id="notes_area">this is some text</textarea>
<input type="submit" name="submit" value="Save Note" id="submit" />
<input type="button" name="cancel_note" value="Cancel" />
</div>
script:
(function($) {
$(document).ready(function() {
$("#notes_maker").submit(function(){
event.preventDefault();
var formURL = "<?php echo admin_url('admin-ajax.php')?>";
var notes_editor = $("#notes_area").val();
$.ajax({
url: formURL,
type: 'POST',
dataType: 'text',
data: {
'action': 'notes',
'notes_editor1': notes_editor,
},
success: function(data) {
alert("it works");
}
})
});
});
})(jQuery);
Then I added the blog_activity_notes table to my database. Here blog is my prefix.
functions.php
function my_ajax_notes() {
if ( isset( $_REQUEST ) ) {
$car = $_REQUEST['notes_editor1'];
echo $car;
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'activity_notes',
array(
'text' => $car,
)
);
}
}
add_action( 'wp_ajax_notes', 'my_ajax_notes' );
Please check once your table name whether the prefix is added or not. If not then you have to add a prefix to your table name.
It is working fine in my local and data has been inserted.
You need to change ajax function
$.ajax({
url: formURL,
'type': 'POST', // put this out here
'dataType': 'text', // put this out here
data: {
'action': 'notes',
'notes_editor1': notes_editor,
},
success: function(data) {
alert("it works");
}
});
and also make sure if the endpoint allows the dataType you are sending
and may want to read about network inspection where you can see what is going on with your requests
https://developer.chrome.com/docs/devtools/network/#load
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 am using a ui-dialog and want to pass a php variable to a url if the Delete button is clicked. I have looked at a large number of other answers to similar questions but nothing seems to quite fit what I am trying to do.
The code below works correctly for the link shown, but doesn't work when I try to pass the php variable to the url.
This code works fine
$( function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
"Delete": function() {
window.open('https://example.com/page.php?id=');
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
I have tried using this but it doesn't work
window.open('https://example.com/page.php?id=<?php echo $id?>')
Try add ";" at the end.
<?php echo $id;?>
Assuming your above code is in .php file, try below code:
<script>
$( function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
"Delete": function() {
window.open("https://example.com/page.php?id=<?php echo $id; ?>");
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
You can assign pageid in input hidden fields like below.
After you need to get this fields value using val() function.
<input type="hidden" value="<?php $id; ?>" id="pageId" />
$( function() {
var PageId = $('#pageId').val();
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
"Delete": function() {
window.open('https://example.com/page.php?id='+PageId);
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
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();
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
...