how to clear ajax response before create modal open - php

This is the form modal code ...
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Add Ajax</button>
Here I can able to add/edit my form. But, the problem is when I click the Add Ajax to create a new form after the click edit button it contains the last edited modal data. I can't reset the data ... modal is only empty after page refresh
script tag
$(".edit-ajax").click(function() {
let id =$(this).data('id');
$("#myModal").find('[name="id"]').val(id);
$.ajax({
url: frontend_form_object.ajaxurl,
type:'POST',
async:false, // Code paused. (Other code waiting for this to finish.)
data: {
action: 'edit_ajax_test',
id : id,
},
})
.done(function(response) {
console.log(response.success);
$("[name=first_name]").val(response.data.edit_ajax.caller_name);
$("[name=last_name]").val(response.data.edit_ajax.caller_state);
//toastr.success('Successfully saved', 'Success', {timeOut: 5000});
$('#myModal').modal('hide');
})
});

Try this:
$(".edit-ajax").click(function() {
$("#myModal").find("#yourformId")[0].reset();
//rest of your code
}

Related

Ajax No Refresh when Deleting Data in a Table - Laravel

My problem is I can click the button but it is needed to refresh to delete it . it there something that is making my ajax code a problem why it is refreshing? I want a button when click delete it will automatically delete without refreshing.
my Button
<button type="button" data-client_id="{{ $client->id }}" class="btn-archive btn btn-info">Active</button>
<button type="button" data-client_id="{{ $client->id }}" class="btn-delete fa fa-trash btn btn-danger"></button>
my AJAX
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).on('click','.btn-archive',function(){
var clientID=$(this).attr('data-client_id');
var url='/admin/clients/archTrash/'+clientID;
callAjax(url);
});
$(document).on('click','.btn-delete',function(){
var clientID=$(this).attr('data-client_id');
var url='/admin/clients/archTrashPermanent/'+clientID;
callAjax(url);
});
function callAjax(url){
$.ajax({
url:url,
dataType:'json',
type:'GET',
success:function(response){
console.log(response);
},
error:function(err){
console.log(err);
}
});
}
</script>
Table Structure
`
class Client extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
// Table Name
protected $table = 'clients';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;`
This is what I am doing:
When creating the table, I attach a unique id (user-id in this case) to every row that can be deleted. This is how I do it in blade:
#foreach ($visitors as $visitor)
<tr class="data-user-id-{{$visitor->id}}">
<td class="text-left">
{{$visitor->name}}
</td>
<td class="text-left" data-original-value="11">
{{$visitor->email}}
</td>
<td class="text-left">
<a href="#" data-user-id="{{$visitor->id}}" class="btn btn-small btn-info btn-visitor-enable-disable">
Enable
</a>
</td>
<td class="text-left">
<a href="#" data-user-id="{{$visitor->id}}" class="btn btn-small btn-danger btn-visitor-delete">
X
</a>
</td>
</tr>
#endforeach
Then, in the success method of my .ajax call, I just select that row using the unique id of the row that was deleted and remove the row. This is how I do it.
$(".btn-visitor-delete").on('click',function(e) {
e.preventDefault();
const userId = $(this).attr('data-user-id');
var confirmation = confirm("Are you sure you want to delete this user?");
if (confirmation) {
$.ajax({
type:'GET',
url:'/dashboard/allwhitelistedusers/delete/' + userId,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
// data:{user_id: userId},
success:function(data){
//Refresh the grid
$(".data-user-id-"+userId).remove();
alert(data.success);
},
error: function(e){
alert(e.error);
}
});
}
else{
//alert ('no');
return false;
}
});
if u want to delete a record in larval without refreshing the page using ajax so use the below code. I am using this code and its working fine
sending id to ajax in this button class which u can relate to yours id <button class="deleteRecord btn btn-danger" data-id="{{ $party->id }}" >Delete Record</button>
ajax codeis like this with sweet alert
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
var parent = $(this).parent();
swal({
title: "Wait..!",
text: "Are You sure, You want to delete Party?",
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
$.ajax({
url: "delete_party/"+id,
type: 'DELETE',
data: {
"id": id,
"_token": token,
},
success: function (){
parent.slideUp(300, function () {
parent.closest("tr").remove();
});
},
error: function() {
alert('error');
},
});
} else {
swal("Your Party is safe");
}
});
});
``
You are only doing half the work: Data is sent to the server and it seems everything is working as expected on that site. But then you want to "delete a client" (I assume you expect a table row to disappear) without reloading the page. You need to code this inside the success handler:
success: function(response) {
$('#client-data').remove();
console.log(response);
}
Note this example code will always remove the same element with the ID client-data. You'll probably need to use something like $(this).parent().remove(); as there seem to be multiple delete buttons on your page.

AJAX Page with Boostrap Modal Form - Submit don't work

i searched a lot about this problem, but I didn't find a solution, yet.
At first a short description about my setup to make my problem clearer.
Settings.php Page with a Menu, where you can select different settings categories
By clicking on one menu point the corresponding loads by ajax and is displayed.
$('#content').load("http://"+ document.domain + "/domainhere/settings/menupoint1.php");
On the menupont1.php page I got a list with mysql data.
I implemented a "edit" button for each row - while clicking on the edit button, a boostrap modal appears with a form and the corresponding data filled in and ready to edit.
When i now click on "Save changes", the POST-Request is always empty.
To realize the form submit, I already tried several codes:
e.g.:
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
or
$(function(){
$('#editform').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#editform').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
At the moment:
while($xy= $xysql->fetch_assoc()) {
<div class="modal fade" id="edit-<?php echo $xy["id"] ?>" [..]>
<button id="submit>" class="btn btn-default">Save</button>
</div>
<script>
$(function() {
$('button#submit').click(function(){
$.ajax({
type: 'POST',
url: './test2.php',
data: $('form#modal-form').serialize(),
success: function(msg){
$('#test').html(msg)
$('#form-content').modal('hide');
},
error: function(){
alert('failure');
}
});
});
});
</script>
Maybe someone here could help me out with this problem?
thank you very much :)
I've set up a minimal example of how this would work:
example html of two modals, which are produced in a loop in your case.
I've now done it without a unique id, but with selecting via class.
<div class="modal">
<!-- // this classname is new and important -->
<form class="editform">
<input name="test" value="value1">
<button class="btn btn-default">Save</button>
</form>
</div>
<div class="modal">
<form class="editform">
<input name="test" value="value2">
<button class="btn btn-default">Save</button>
</form>
</div>
Your javascript would be something like this:
$(function() {
var formsAll = $('.editform');
// changed this to onSubmit, because it's easier to implement the preventDefault!
formsAll.on('submit',function(e){
e.preventDefault();
var formData = $(this).serialize();
console.log(formData);
// add your ajax call here.
// note, that we already have the formData, it would be "data: formData," in ajax.
});
});
Note, that I don't have your real html structure, so details might vary. But you get the idea.
also available here:
https://jsfiddle.net/a0qhgmsb/16/

Submiting a form created inside an AJAX response

I have 3 steps to do:
Send some datas via AJAX to a PHP page
Retrieve results and show to user a button with popover which contains a form to save name of user search
Send this form in other PHP page via other AJAX
Points 1 and 2 work fine.
I put popover function in 'complete' section of ajax because popover is created only after results are retrieved.
For point 3, i am unable to catch last form with on.submit. When i click on submit button, it sends form (reload my page).
Here is my code:
HTML part:
<body>
<div class="row" id="results"></div>
</body>
JS part:
/* popover form for save search */
var search_box = '<div id="popover-content" class="hide">'+
'<form id="searchForm" class="form-inline" role="form">'+
'<div class="form-group has-warning">'+
'<input placeholder="Name" class="form-control" maxlength="50" type="text"> '+
'<button type="submit" class="btn btn-warning"><i class="fa fa-check"></i></button>'+
'</div>'+
'</form>'+
'</div>';
/* function to retrieve results and show button with popover */
function searchresults() {
if(select_data !== ''){
$.ajax({
type: "POST",
dataType: 'json',
url: "search.php",
data: { q: select_data },
cache: false,
success: function(data) {
if($.isPlainObject(data) && data.state === 200){
// here is code to retrieve results...
// show button with popover and form
saveButton ='<button type="button" class="btn btn-outline btn-warning btn-lg" data-toggle="popover" data-placement="auto top" data-title="Enter name for your search"><i class="fa fa-star"></i> Save selection</button>'+search_box;
$("div#results").html(saveButton);
}
},
complete: function (jqXHR, status) {
$("[data-toggle=popover]").popover({
html: true,
content: function() {
return $('#popover-content').html();
}
});
/* ******** PART DOES NOT WORK ******** */
$("#searchForm").on('submit', function(e) {
e.preventDefault();
alert('passed');
/* code ajax here */
return false;
});
}
});
}return false;
}
How to correct this?
Try to add $(document) .... Let me know if it works I didnt test
$(document).on('submit', 'form#yourFormID', function(e) {
e.preventDefault();
alert('passed');
/* code ajax here */
return false;
});

submithandler of Jquery validation plugin not working for ajax submit bootstrap 3

I am new to web development, especially jquery and bootstrap. I am trying to use jquery validation plugin to validate my forms. Everything works fine in normal form submits, whereas if I am trying to submit the form through ajax, it doesn't seem to work at all. All validations are simply ignored.
HTML
<form class="ajaxForm">
<input type="text" class="form-control" name="user_firstname" required data-rule-required="true" data-msg-required="Please enter your First name" data-rule-names="true" data-msg-names="Please enter alphabets only"/>
<button type="button" class="btn btn-default btn-xs cancel">Cancel</button>
<button type="submit" class="btn btn-primary btn-xs submit">Save Changes</button>
</form>
JS
$('body').on('click', '.submit', function() {
try {
var form, data, url, type, elem_id, a_mode, e_mode, pieces;
form = $(this).closest('form.ajaxFrom');
data = form.serialize();
form.validate({
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'post.php',
data: data,
beforeSend: function() {
},
success: function(html) {
alert('success');
}
});
}
});
}
catch (e) {
alert(e);
}
});
}
I don't want to use form.submit() because it refreshes the page and kinda spoils the whole point of me using ajax here. I do not want to refresh or redirect the page.

voting system with ajax and php

Thanks for reading.
I'm trying to improve so I'm doing an example project to improve. I made a simple. voting system. I have number of contents which displayed by php each of them have up or down vote button. by the way I use twitter bootstrap.
this is the html code:
<html>
<button type="submit" class="btn btn-mini upvote" id="'.$data['ContentID'].'">
<i class="icon-arrow-up"></i>
</button>
<span id="voteresponse">'.$data['VoteSum'].'</span>
<button type="submit" class="btn btn-mini downvote" id="'.$data['ContentID'].'">
<i class="icon-arrow-down"></i>
</button>
</html>
the problem is when I lick up button which is class="upvote" all other buttons does same thing. because the data populated by php there are many of them.
this is my javascript.
<script>
jQuery(document).ready(function($){
$('.upvote').click( function(event) {
event.preventDefault();
$("#voteresponse").html('');
var voteID = $(".upvote").first().attr("id");
$.ajax({
url: "/ajax.php?Page=votetitle",
type: "post",
dataType: "json",
data: {id : voteID},
success: function(data, textStatus){
if(data.success == 'true'){
$('#voteresponse').html(data.message);
return true;
}else{
$('#voteresponse').popover({
title: 'Hata!',
content: data.message
});
}
},
error:function(){
$('#voteresponse').popover({
title: 'error!',
content: 'Server error'
});
}
});
});
});
</script>
and the php code is just usual database request.
<?php
if ( $_SESSION['UserID'] <1 )
die( print_r(json_encode(array('success'=>'false', 'message'=>'error for user!'))) );
print_r(json_encode(array('success'=>'true', 'message'=>$_POST['id'])))
?>
you can see the action here. if you click one of them all other up arrows do same thing. also is this approach right?
thanks. best regards
Only the first one "responds" when you click any of them... This is likely because of var voteID = $(".upvote").first().attr("id"); The voteID should be something like $(this).attr('id'); instead.
Note that you need to recognize which button was clicked, you can use for example $(this).parent()... That will give you to the upper DOM level of the clicked button (div media isotope-item) and from there you can modify only the content of that div.
try changing
var voteID = $(".upvote").first().attr("id");
to this
var voteID = $(this).first().attr("id");
or
var voteID = $(this).attr("id");

Categories