How to submit form using ajax inside wordpress plugin - ajax

I am creating small plugin where i want to submit form data using ajax but it giving response zero.
Here is my call i have added all code in a single file for the time being
file name :index.php
<?php wp_enqueue_script("jquery");?>
<?php
function myaddgallery(){
global $wpdb;
echo "abac";
}
add_action('wp_ajax_myaddgallery' , 'myaddgallery');
add_action('wp_ajax_nopriv_myaddgallery' , 'myaddgallery');
?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#shaGalleryForm').submit(function(e){
// prevent normal submit behaviour
e.preventDefault();
var name = jQuery("#shaGalleryName").val();
alert(name);
//var postData = jQuery("#shaGalleryForm").serialize();
//console.log(postData);
var name = "shalu";
jQuery.ajax({
type: "POST",
url: "http://localhost/plugindevelop/wp-admin/admin-ajax.php",
data : {action: "myaddgallery", name : name},
success: function(response){
//console.log(postData);
console.log("added success");
alert(response);
},
error: function(data){
console.log("fail");
}
});
});
}) ;
</script>
<div class='wrap'>
<h2>Add Gallery</h2>
<p>This is where from you can create new gallery</p>
<form name="shaGalleryForm" id="shaGalleryForm" method="post">
<table class="form-table">
<tr>
<th>Gallery Name</th>
<td>
<input type="text" id="shaGalleryName" name="shaGalleryName">
<p class="description">Add gallery name also please avoid special character</p>
</td>
</tr>
</table>
<p class="submit">
<input type="submit" value="Save" id="shaSaveGallery" name="shaSaveGallery" class="button button-primary">
</p>
</form>
</div>

Try to add die() after you echo the data
function myaddgallery(){
global $wpdb;
echo "abac";
die();
}

Related

Script to delete Ajax record does not work correctly

I have an Ajax script that should delete entries. It basically works, but when you click the delete button, only the first one is deleted from the list of all records. Although, after reloading the page, the record that disappeared appears and the one I wanted to delete is deleted. How can this be fixed?
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (){
$("#textpostdata").remove();
},
});
});
});
And html
<div id="textpost">
#foreach($post->comments as $com)
<div id="textpostdata" data-id="{{$com->comment_id}}">
<p><b>{{$com->author_name}}</b> · <i>{{$com->created_at->diffForHumans()}}</i></p>
<p>{{$com->comment}}</p>
#if(Auth::check())
#if(Auth::user()->id == $com->author_id)
<form action="{{route('delMusicComment', ['comment_id' => $com->comment_id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $com->comment_id }}">Удалить</button>
</form>
#endif
#endif
<hr>
</div>
#endforeach
</div>
you used the same id for multiple elements
the id should be unique, if you use same id for other elements, the html just set that id to first element.
you can use className instead ID like this:
HTML:
<button type="submit" class="btn btn-sm btn-outline-danger py-0 mt-4 delete" data-id="{{ $com->comment_id }}">Удалить</button>
jquery:
$("body").on("click",".delete",function(e){
//other lines of your jquery is ok, because you used $(this) in this line: var id = $(this).data('id');
Jquery - remove the entry after ajax:success
var this_element = $(this); //get the active element, because you can not use $(this) in ajax:sucess!
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (){
this_element.closest("div").remove(); //remove selected button's whole div!
},
});
NOTE:
when you use className to access the element, you can find the element that event affected on with $(this)
for test use this code: console.log($(this));
Your html is not valid because if there is many comments you have many div with id #textpostdata. You can suffix it with the id of your comment
<div id="textpost">
#foreach($post->comments as $com)
<div id="textpostdata-{{$com->comment_id}}" data-id="{{$com->comment_id}}">
<p><b>{{$com->author_name}}</b> · <i>{{$com->created_at->diffForHumans()}}</i></p>
<p>{{$com->comment}}</p>
#if(Auth::check())
#if(Auth::user()->id == $com->author_id)
<form action="{{route('delMusicComment', ['comment_id' => $com->comment_id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $com->comment_id }}">Удалить</button>
</form>
#endif
#endif
<hr>
</div>
#endforeach
</div>
Furthermore your query selector should be modified and your delete method should return the deleted element
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (data){
$("#textpostdata" + data.comment_id).remove();
},
});

How to save the content of a textarea using Ckeditor and CodeIgniter?

I'm using Codeigniter with Ckeditor. My problem is that when I submit the content, the data from the textarea is not stored in the database. But when I tried it again it finally did. So the situation is like I have to double click submit button to save it.
I stored the downloaded Ckeditor on a folder named ./Assests/Ckeditor(Sorry for the wrong spelling.I'll fix this later.)
Here's my form in my view folder:
ask_view.php:
<form id="form" enctype="multipart/data" method="post" onsubmit="createTextSnippet();">
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name ="title" class="form-control" id="title" placeholder="Title" required >
</div>
<input type="hidden" name="hidden_snippet" id="hidden_snippet" value="" />
<div class="form-group">
<label for="exampleInputEmail1">Editor</label>
<textarea name ="text" class="form-control" id="text" rows="3" placeholder="Textarea" required></textarea>
</div>
<input type="submit" class="btn " name="submit" value ="Submit" style="width: 100%;background: #f4a950;color:#161b21;">
</form>
<script src="<?php echo base_url('assests/js/editor.js')?>"></script>
<script type="text/javascript">
CKEDITOR.replace('text' ,{
filebrowserBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserUploadUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserImageBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=1&editor=ckeditor&fldr=')?>'
}
);
</script>
<script type="text/javascript">
//code used to save content in textarea as plain text
function createTextSnippet() {
var html=CKEDITOR.instances.text.getSnapshot();
var dom=document.createElement("DIV");
dom.innerHTML=html;
var plain_text=(dom.textContent || dom.innerText);
var snippet=plain_text.substr(0,500);
document.getElementById("hidden_snippet").value=snippet;
//return true, ok to submit the form
return true;
}
</script>
<script type="text/javascript">
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/knowmore2/index.php/ask_controller/book_add',
data: $('form').serialize(),
success: function (data) {
console.log(JSON.parse(data));
}
});
});
</script>
Ask_model.php:
public function book_add($data)
{
$query=$this->db->insert('article', $data);
return $query;
}
Ask_controller.php:
public function book_add(){
$data = $_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$result=$this->ask_model->book_add($details);
echo json_encode($details);
}
The content with html tags should be save in a column named content in the database, but it didn't save in the first click. It only saves on the second one,but the other data are saved in the first like the title, etc. So I get 2 rows of data, one without the content and the other with one.
Database:

ajax form in CodeIgniter - sending generated form

I want to open a modal and get the content (the formular) form the controller. These steps work fine.
Now I have the formular inside the modal. How I can submit these formular and process it with the same controller function?
At the Moment I do the Ajax-Call in this way
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and received
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#disconnect_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
This is the form which will be generate from the controller by the call above
echo' <div class="modal-body">
<div id="modul_disc_infos">
<span class="module-headlines-title">'._l("modul_name").': <span id="disc_modulname">'._l('module_'.$result->folder.'_titel').'</span></span>
<span class="module-headlines-subtitle">'._l("modul_disconnect_deadline").': <span id="disc_enddate">'.$enddate.'</span></span>
</div>
<div id="modul_disc_check">
<div class="alert alert-danger" role="alert">'._l("modul_disconnect_disclaimer").'</div>
<hr>
<input type="checkbox" name="check_disclaimer" value="1"> '._l("modul_disconnect_disclaimer_check").'
<input type="hidden" name="modid" value="'.$this->input->post('modid').'">
<input type="hidden" name="formstep" value="1">
'.$errormsg.'
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">'._l('close').'</button>
<button type="button" class="btn btn-danger" id="submit_disconnect" >'._l('modul_disconnect_now').'</button>
</div>';
By the way - is there a better way to parse the values of the formular instead one by one like in my code "var modid = $(this).attr('modid');"?
I've solved that in this way that i do 2 different ajax call, starts with a click or submit on the form or a specific button. One call generate the form, one call handle the form. For me it works and its a little bit flexibel to use the same functions for different jobs.
//Formular for disconnection
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$('#ajax_modal_title').html('<?php echo _l('modul_disconnect'); ?>');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and recieved
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#ajax_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
//Handle the disconnection
$("#ajax_form").on("submit", function (event) {
event.preventDefault();
subform=$('input[name="subform"]').val();
$.ajax({
url: "<?php echo base_url() ?>admin/module/"+subform+"_form",
type: "POST",
data: $('#ajax_form').serialize(),
success: function(result){
$('.modal-ajax-content').html(result);
},
error: function(error){
// Show error message
alert('error');
}
});
});

insert Using ajax But page refreshing on submit why?

Controller code I have :
<?php
class Ajax_cntrl extends CI_controller{
public function index(){
$this->load->view('ajax_view');
$insert = array(
'name' => $this->input->post('name'),//<-- also not able to get this id from ajax post request
'pass' => $this->input->post('pass'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'address' => $this->input->post('address'),
);
$this->db->insert('form',$insert);//<--insert item into cart
$query;// to insert into database
//redirect('shop');
}
}
?>
view code I have ::
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<form action="" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Pass</td>
<td><input type="password" name="pass" id="pass"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" id="mobile"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" id="address"></td>
</tr>
<tr>
<td><input type="submit" name="submit" id="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var form_data = { //repair
id: id,
name: $('#name_' + id).val(),
pass: $('#pass' + id).val(),
email: $('#email' + id).val(),
mobile: $('#email' + id).val(),
address: $('#email' + id).val()
};
$.ajax({
type:'post',
url:"<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data, // $(this).serialize(); you can use this too
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
</script>
problem is that when i am submitting the form it refreshing the browser ajax not working where is the fault m not able to understand please help me related in this why ajax call is not working there and is that a gud way to implement ajax with codeigniter ?? if yes then y its not working
Use below code, this will fix your issue.
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var form_data = {//repair
name: $('#name').val(),
pass: $('#pass').val(),
email: $('#email').val(),
mobile: $('#mobile').val(),
address: $('#address').val()
};
$.ajax({
type: 'post',
url: "<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data,
dataType: 'json',
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
});
</script>
Let me know if it not works for you.

Ajax call back: Return variable as input value

After ajax call back I need to echo out a variable as value of hidden field.
HTML
<form ajax1>
<input name="Place" value="Milan">
<input name=submit onclick="return submitForm1()">
</form>
<form ajax2>
<input type="hidden" value="$place">
<input name="filter">
<input name=submit onclick="return submitForm2()">
</form>
<div id="result"></div>
Ajax Call
function submitForm1() {
var form1 = document.myform1;
var dataString1 = $(form2).serialize();
$.ajax({
type:'GET',
url:'query.php',
cache: false,
data: dataString1,
success: function(data){
$('#results').html(data);
}
});
return false;
}
PHP
<?
$place= $_GET['Place']
//do stuffs
?>
It works perfectly, but now I need to add a function to echo out $place in value=" " of form ajax2
Any help appreciated

Resources