I am trying to write a page where there are 2 sets of forms submitted, one to search IMDB, and then the 2nd to submit the request from the returned results.
I have the pages working just fine with just regular old php. I am wanting to convert it over to ajax/jquery to make it have a better ux, when there are large searches and database calls. I am having issues with getting the 2nd Submit button to work. I have searched for quite a while and noticed some comments about not using event.preventDefault() because any button called there after would not work and to use return false; instead. I have tried multiple combinations, even tried having it load a 2nd set of code during the posting.done of the 1st one, all to no avail.
I am trying to really understand what is going on here and what the proper solution would be.
All of this sits inside a div #dynamic
The script:
// Attach a submit handler to the form
$( "#imdb_search" ).submit(function( event ) {
// Stop form from submitting normally
//event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
form_request = $form.find( "input[name='request']" ).val(),
form_user = $form.find( "input[name='user']" ).val(),
form_username = $form.find( "input[name='username']" ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post(url, {
request: form_request,
user: form_user,
username: form_username
});
// Put the results in a div
posting.done(function(data) {
// var content = $( data ).find( "#returned_result" );
$("#dynamic").empty().append(data);
});
return false;
});
So I have tried this as well from one of the comments to no avail:
$( "#imdb_search" ).submit(function(){
var $frm = $(this);
$.ajax({
url: $frm.attr( "action" ),
dataType: 'html',
type: 'POST',
data: $frm.serialize(),
success: function(r) {
$("#dynamic").empty().html(r);
},
error: function(){
//TODO: add error code
}
});
return false;
});
I have this script at the bottom of each of the new php pages that is loaded from the success return. Is that the correct place to have it for DOM? Both forms have the same id but submit different "inputs".
As I can get from your code you also overwrite html form when you get first result, if it is the case then you should use jquery "on" function
$(document).on("#imdb_search", "submit", function(){
var $frm = $(this);
$.ajax({
url: 'your_post_url',
dataType: 'html',
type: 'POST',
data: $frm.serialize(),
success: function(r) {
$("#dynamic").html(data);
},
error: function(){
//TODO: add error code
}
});
return false;
});
and be sure that you don't overwrite this code with other.
Related
I created a form. I added many validations as requirement like required all fields. Check duplicate fields. Now I want if form submitted successfully without error reset my form if it has any error like duplicate email then show error Duplicate data found and don't reset form. I completed my code but tucked in a place I m returning false then it's not showing an error which I mentioned din called PHP file. So, how can I do it without using JSON?
$("#create_stock_out").click(function(){
var form= new FormData();
var subject = $("#subject").val();
var slip_no = $("#slip_no").val();
var warehouse = $("#warehouse").val();
var vendor = $("#vendor").val();
var issued_by = $("#issued_by").val();
var received_by = $("#received_by").val();
var project = $("#project").val();
form.append('subject',subject);
form.append('slip_no',slip_no);
form.append('warehouse',warehouse);
form.append('vendor',vendor);
form.append('issued_by',issued_by);
form.append('received_by',received_by);
form.append('project', project);
form.append('method', "stock_out");
$.ajax({
url: 'Function/Function.php',
type: 'post',
data: form,
contentType: false,
cache: false,
processData:false,
success:function(data){
//alert(data);
$('#stock_out_result').html(""+data+"");
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 5000);
}
});
});
I create a Form after user click on a div, and I submit on same page using Ajax without reloading page.
I see that the form is submitted successfully with data when I check the network tab in dev tools but when I print $_POST or check if isset($_POST["data"]), I get $_POST is empty and the if condition is false, is there any way to get the data in PHP ($_POST) without refreshing the page.
I get no errors in console or php
When using:
form.submit();
The form is submitted and I get $_POST but the page reload, this is why I need to use Ajax
My code on Js page :
function post(path, parameters) {
var form = $('<form id="form"></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", JSON.stringify(value));
form.append(field);
form.append(data);
});
$(document.body).append(form);
$.ajax({
type: "POST",
url: path,
data: $("#form").serialize(),
success: function(data) {
$('.before').hide();
$('.next').show();
}
});
return false;
}
$('.card-container').on('click',function(e){
e.preventDefault();
var page = window.location.href;
var object = {
'array': [
['string1', 'string2'],
['string3', 'string4']
]
};
post(page, object);
});
My code on PHP page :
var_dump($_POST);
if (isset($_POST['array'])) {
$array = json_decode($_POST['array'], true);
print_r("ok");
}
The full code is too long to include it here.
I am working on wordpress site, i created custom form, in which i am getting voucher code and after validating this code , submitting this form to another url , defined in form action, here is jquery for this work,
<script type="text/javascript">
$( document ).ready(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
$( "#submit_btn_redeem" ).click(function(event) {
event.preventDefault();
var form = $("#form-voucher");
var voucher_code = $("#voucher_code").val();
var btn = $(this);
if(voucher_code!=""){
$("#voucher_code").removeClass("error-fld");
btn.prop('disabled', true);
btn.attr("disabled","disabled");
$(".loading").show();
var action_data = {
'action': 'check_voucher_code',
'voucher_code': voucher_code
};
$.ajax({
type: 'POST',
url: ajaxurl,
data: action_data,
dataType: 'json',
success: function (response) {
$(".loading").hide();
btn.prop('disabled',false);
btn.removeAttr("disabled");
if(response.status==1){
$(".response").html(response.message);
$(".response").show().delay(2000).hide(0);
alert($("#voucher_code").val());
//return false;
setTimeout(function(){
document.getElementById("form-voucher").submit();
}, 1000);
}else{
$("#voucher_code").addClass("error-fld");
$(".response").html(response.message);
$(".response").show().delay(3000).hide(0);
}
}
});
}else{
$("#voucher_code").addClass("error-fld");
}
});
});
</script>
Problem is when it submit on given url , it is first redirect to 301 with POST method, then again generate GET request with no parameter and sumitted to that url, I have dumped $_REQUEST on action url, not getting any data here, i have also check .htaccess and redirect plugin, there is no such url exists for redirection, the question is submitting form with post method redirect, while with GET method its work fine, any body can help
You need to defined the action function in your function.php file in your theme, which will look something like this
add_action( 'wp_ajax_nopriv_check_voucher_code', 'functiontohook' );
add_action( 'wp_ajax_check_voucher_code', 'functiontohook' );
After that you need to specify the action in you ajax request which you have done. In functiontohook you can get your all json data and do anything that you want to do. Let me know if anything is not clear. I hope this will help you out.
I'm learning AJAX by reading some online tutorials, so please understand I am very new to AJAX and programming in general. I have managed to do the following with 3 selectboxes:
populates selectbox 2 based on selection from selectbox 1
populates selectbox 3 based on selection from selectbox 2
Everything is working perfectly
Here is my code:
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
Here is an Example
What I want to do
I would like to send the value of the 3 selectboxes to 3 php variables without the form reloading.
My Problem
When the user clicks submit:
The form reloads (which I dont want)
The selectbox values does not get send to my php variables
my code to get the values after submit is clicked is as follows:
if(isset($_POST['submit'])){
$a = $_POST['sport'];
$b = $_POST['tournament'];
:
}
However my code is flawed as I mentioned above.
If any one can help me to explain how to send my form data to the 3 php variables without the form reloading it will be greatly appreciated
If you don't want to submit your form when you click the button, you need to set that input as button and not submit. You can, also, attach the submit event handler to the form and prevent it to submit:
$("form").on("submit", function(e){
e.preventDefault(); //This is one option
return false; //This is another option (and return true if you want to submit it).
});
So, being said this, you could probably do something like:
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'yoururl',
data: formData,
type: 'post', //Based on what you have in your backend side
success: function(data) {
//Whatever you want to do once the server returns a success response
}
});
});
In your backend:
if (isset($_POST["sport"])) {
//Do something with sport
}
if (isset($_POST["tournament"])) {
//Do something with torunament
}
echo "Successfull response!"; //You have to "write" something in your response and that is what the frontend is going to receive.
Hope this helps!
Try using the javascript function preventDefault().
See this SO question.
Use a <button>Submit</button> element instead of <input type="submit"/> since the submit automatically submits the form.
Edit: And you would have to use on.('click') instead of looking for submit event in your jQuery.
I have two files filter.php and products.php included to index.php and I am using .post submit form without refreshing. I send data to products.php and return it back also i refresh my filter and there is my problem. When i try to var dump post data in filter.php it is empty
Here is my script
function ajaxFilter()
{
var str = jQuery( "form[name=\"filters\"]" ).serialize();
jQuery.post( "/", str )
.done(function( data ) {
var productList = jQuery(data).find(".list_product").html();
var filter = jQuery(data).find(".filters").html();
jQuery(".list_product").html(productList);
jQuery(".filters").html(filter);
});
}
Any ideas how to get POST?
I though about putting my post via script to hidden inputs and return them also as html
If it is bad idea or just wrong start.
try this:
var Data = $("form[name=\"filters\"]").serializeArray();
var URL = "products.php"; // whatever filepath where you send data
jQuery.ajax({
type: "POST",
url: URL,
processData: true,
data: Data,
dataType: "html",
success: function (productList) {
// filter your result whatever you return from products.php
jQuery(".list_product").html(productList);
},
error: function (x, y, z) {
var a = x.responseText;
jQuery(".list_product").html(a);
}
});
Use the full URL.
Provide the return values of .error() if you still have problems.