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;
});
Related
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
}
I apologize for the ease of this question for you.
But I looked at your beautiful site for an answer to my problem, but I was not lucky.
I'm trying to build my own,form-wizard for student registration, in easy steps as a graduate project for university.
I use PHP, JQuery and AJAX to send data .
My problem:
I have a single form and to button ,
The first three input are searched in the database via the submit button and it is worked good ,
then automatically form-wizard moves to the next fieldset and then displays the inpust field to
student to enter his information .
finally thir is button to save data to database
by AJAX and this button is my problem .
the php say undefined index .
this is code for html wizard-form
$('form').on('submit', function(e) {
var $formInput = $(this).find('.fi');
$formInput.each(function(i) {
if (!$(this).val()) {
e.preventDefault();
$(this).addClass('input-error');
return false;
} else {
if ($formInput.length === i + 1) {
var id_high_school = $('[name="id_high_school"]').val();
var SEC_SCHOOL_YEAR = $('[name="SEC_SCHOOL_YEAR"]').val().toString();
var sum_high_school = $('[name="sum_high_school"]').val();
alert(SEC_SCHOOL_YEAR);
$.ajax({
url: "select_for_modal_serch.php",
method: "post",
data: {
id_high_school: id_high_school,
SEC_SCHOOL_YEAR: SEC_SCHOOL_YEAR,
sum_high_school: sum_high_school
}
}).done(function(datas) {
$('#studint_detail').html(datas);
$('#dataModal').modal("show");
}).fail(function() {
alert('fail..');
});
}
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form name="mainForm" action=" <?php echo $_SERVER['PHP_SELF'] . '#form1' ?> " id="form1" method="POST" enctype="multipart/form-data">
<!-- condetion for regster -->
<fieldset>
<iframe src="license.html"></iframe>
<input class="form-check-input" id="check_qury" type="checkbox" value="yes">
<div class="wizard-buttons">
<button type="button" class="btn btn-next">التالي</button>
</div>
</fieldset>
<fieldset>
<!-- 3 <input type = text > to search for data from mysql -->
<!--her is the submit button and is get data by ajax -->
<input type="submit" class="form-control btn btn-primary view-data" id="submit_high_school" value="بحث" name="submit_high_school" />
<!-- by ajax is work and then is go to the next filedset -->
</fieldset>
<fieldset>
<!-- mor data <input type = text > to search for data from mysql -->
<button type="button" id="sava_data_to_tables" name="sava_data_to_tables" class="btn btn-next">
<!-- this is the button of my problem cant send this form data to mysql -->
</fieldset>
I doing this code to solve the problem but nothing work :
$('#sava_data_to_tables').on('click', function (event) {
var form_data = $(this).parents('form').serialize();
var colage = $('[name="colage"]').val();
var spichelest = $('[name="spichelest"]').val();
// and rest of input type
$.ajax({
url: "insert_into_info_contact.php",
method: "POST",
data: form_data,
success: function (data) {
alert(data);
}, cache: false,
contentType: false,
processData: false
});
});
and my PHP :
<?php
// isset($_POST['sava_data_to_tables'])
//$_SERVER['REQUEST_METHOD']==='POST'
// !empty($_POST)
if ($_SERVER['REQUEST_METHOD']==='post')
{ echo "you submit data"
;}
else {
echo "its not work" ; }
?>
I found some help from a friend ..
He just change this :
var form_data = $(this).closest('form').serialize();
to this :
var form_data = new FormData($(this).closest('#form1').get(0));
He solved my problem.
I honestly did not understand what the problem was, but he told me I had sent a different kind of data >> Thanks every One . :)
I have a payment page that has a multi-step form. In the "step 1" the user inserts his information like nama, surname, etc, then billing information.
So, in the "step 1" I have fields like name, surname, etc. I want in each step collect all information with jQuery so that is possible to send an ajax request to the server to validate the information when the "go to step 2" button is clicked.
My doubt is about how to properly store this step1 data inserted by the user to be possible to send it to the server. For example in the step 1 Im getting the values like:
var name = $('#name').val();
Then how to send the data to the server using an ajax post request?
step 1 html
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" action="">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
For the ajax part when "Go to step 2" is clicked I created a route 'storeUserInfo', but do you know how to send the data to the PaymentController?
$("a[id='goToStep2']").on('click', function(){
$.ajax({
url: '{{ route('products.storeUerInfo',null) }}',
type: 'POST',
success:function(result){
),
error: function(error) {
console.log(error.status)
}
});
});
This is a complete solution for form with file element
HTML
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" action="" id="page-form">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
JS
$(function () {
'use strict'
var page_form_id = "page-form";
$('#a[id='goToStep2']').on('click', function () {
$('#' + page_form_id + ' .error').html("");
$('#' + page_form_id + ' .form-group').removeClass("has-error");
var custom_form = $("#" + page_form_id);
var custom_params = custom_form.serializeArray();
var custom_files = $("#file")[0].files;
var custom_formData = new FormData();
for (var i = 0; i < custom_files.length; i++) {
custom_formData.append("file", custom_files[i]);
}
$(custom_params).each(function (custom_index, custom_element) {
custom_formData.append(custom_element.name, custom_element.value);
});
$.ajax({
method: "POST",
url: '{{ route('products.storeUerInfo',null) }}',
contentType: false,
processData: false,
data: custom_formData,
success: function (data, textStatus, jqXHR) {
setTimeout(function () {
window.location.reload();
}, 3000);
},
error: function (data) {
var errors = data.responseJSON;
$.each(errors['message'], function (index, value) {
$('#' + add_form_id + ' .eMsg_' + index).html(value[0]);
$('#' + add_form_id + ' .eMsg_' + index).parent().parent().addClass("has-error");
});
}
});
});
});
If you use form to send something. Better Use submit form method on JQuery. And give return false on the end of the function.
To check is it working, you can use inspect element on your browser on the console tab. If you see something error status it's maybe your code has something wrong.
In other way you can go to the url manually, without hitting by ajax. So you must make sure it works, before you want to use ajax.
Instead of gathering all of the data into variables separately, use the form online to submit inside your ajax call. First, call preventDefault() on the Event, and then you can use this line in your ajax call:
data:$('#myForm').serialize(),
PS, you add the event object as a parameter in your click listener. Then you can call event.preventDefault();.
$("a[id='goToStep2']").on('click', function(){ var name = $('#name').val();
$.ajax({ url: '{{ route('products.storeUserInfo',null) }}/' + category_id, type: 'POST',
data:{ "name": name},success:function(result){ ), error: function(error) { console.log(error.status) } }); });
I want to display text message for success in popup div without refreshing the page
My popup form like this
<div class="modal-content">
<div id="message">Your message has been sent.<br /><br /></div>
<form action="<?php echo $_SERVER['REQUEST_URI'];?>" id="CallBackForm" name="CallBackForm" method="post">
<div class="form-group">
<input id="custmobileNo" name="custmobileNo" type="text" required="required">
<input type="submit" value="call" id="callback" name="callback" class="btn btn-info">
</div>
</form>
</div>
When I click on this link pop up will call
<a href="#" data-toggle="modal" data-target="#call-back">
<input type="submit" value="Call" class="btn-d btn-doctor" >
</a>
CSS:
<style type="text/css">
#message {
display:none;
font-size:15px;
font-weight:bold;
color:#333333;
}
</style>
Ajax Call:
<script>
$("#callback").click(function () {
var custmobileNo = $("#custmobileNo").val();
$.ajax({
url: "<?php echo base_url('Call'); ?>",
type: 'post',
data: {custmobileNo: custmobileNo},
beforeSend: function () {
if (custmobileNo != "") {
$("#message").fadeIn(); //show confirmation message
$("#CallBackForm")[0].reset(); //reset fields
}
}
});
});
</script>
I wrote beforeSend function() with some data either it was standard code or not I don't know. It was calling message fine but it was not closing I want it will close with in some seconds and click on again that button success message validation was showing I want clear that text also.
Try something like this maybe :
$.ajax({
url: "<?php echo base_url('Call'); ?>",
type: 'post',
data: {custmobileNo: custmobileNo},
beforeSend: function () {
if (custmobileNo != "") {
$("#message").fadeIn(); //show confirmation message
$("#CallBackForm")[0].reset(); //reset fields
}
},
success: function() {
setTimeout(function() { //hide message after a certain time
$("#message").fadeout();
}, 5000); // choose after how many time message should hide, here 5s
}
});
But if your Ajax call fail you won't go in the success part so becareful !
You can do the same with complete : function() {...} instead of success : function() {...}, here is some information about Ajax event : https://api.jquery.com/Ajax_Events/
Is it what you are looking for?
Purpose is to have a small icon on my admin page.
Clicking this icon will fire a modal window with an instance of ckeditor textarea.
The user edit the text, saves it and modal closes.
My problem is that if i click again on the icon, the new editor instance is empty.
Below you can see the relevant codes
HTML Part:
<a id="editShortText" title="Short Description" href="#saveShortTextFrm"><img src="clickme.gif">
<div style="display:none">
<form action="" method="post" id="saveShortTextFrm" name="saveShortTextFrm" class="frm">
<textarea class="jquery_texteditor" name="short_text_english" id="short_text_english" style="width:700px; height:400px;"><? echo $value_from_db;?></textarea>
<div align="center" style="margin:20px;"><input name="submit1" type="submit" value="Save" /></div>
</form>
</div>
JS Script:
$("#editShortText").fancybox({
'scrolling': 'no',
'titleShow': false,
'onStart': function() {
$('.jquery_texteditor').ckeditor(config);
},
'onComplete': function() {
$('.jquery_texteditor').ckeditor(config);
},
'onClosed': function() {
$('.jquery_texteditor').ckeditor(config);
}
});
$("#saveShortTextFrm").live("submit", function() {
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "_save_text.php",
data : $(this).serializeArray(),
success: function(data) {
if (data!='')
{
$("#shortTtextImageHolder").html('<img src="images/button_accept.gif" border="0">');
if(CKEDITOR.instances["jquery_texteditor"])
{
delete CKEDITOR.instances["jquery_texteditor"];
$('.jquery_texteditor').ckeditor(config);
$("#short_text_english").val(data);
CKEDITOR.instances.short_text_english.setData(data);
}
}
else
{
$("#shortTtextImageHolder").html('<span class="error">S.O.S.</span>');
}
$.fancybox.close();
}
});
return false;
});
All work well for the first click - when I click my link/image for the first time.
If i click again (after saving modal data or just closing modal window), the new modal fires up but text area is empty of data.
Any ideas on how to fix this?
When you close the modal try to use
CKEDITOR.instances.short_text_english.destroy(true);
or
if (CKEDITOR.instances.short_text_english) {
CKEDITOR.instances.short_text_english.setData("");
CKEDITOR.instances.short_text_english.destroy(true);
}