How to send a form without refreshing the page - javascript

I make a form in Wordpress Template that makes certain calculation and displays the result in a modal Bootstrap.
HTML:
//FORM
<form method="post" id="myForm">
<span>Name</span><br><input type="text" name="name" id="name" required>
<span>Email</span><br>
<input type="email" name="email" id="email" required>
<span>Altura</span><br>
<input type="number" name="altura" id="altura" required>
<span>Peso</span><br>
<input type="number" name="peso" id="peso" required>
<br><br>
<button type="submit" id="enviar" onclick="calcularIMC();">Enviar</button>
//MODAL
<div class="modal fade" id="ajax-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div id="corpo_modal">
<p> ALL FIELDS </p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JAVASCRIPT:
function calcularIMC(){
var nome = document.getElementById("nome").value;
var email = document.getElementById("email").value;
var estilo = document.getElementById("estilo").value;
var experiencia = document.getElementById("experiencia").value;
var altura = document.getElementById("altura").value;
var peso = document.getElementById("peso").value;
var resultado = 5;
var corpo = document.getElementById("corpo_modal");
var imc = 0;
if(altura >0 && peso >0){
imc = peso / (altura * altura);
}
if(estilo == "Surf"){
if((imc<=25) && (resultado == 5)){
corpo.innerHTML = '<img src="1.png" style="width: 150px; height:150px">';
}
else{
corpo.innerHTML = '<img src="2.png" style="width: 150px; height:150px">';
}
}
else if(estilo == "SUP"){
if((experiencia >= 3) && (imc <=29)){
corpo.innerHTML = '<img src="3.png" style="width: 150px; height:150px">';
} else{
corpo.innerHTML = '<img src="4.png" style="width: 150px; height:150px">';
}
}
}
The problem is that when I send the form, it updates the page and does not display the modal.
After some research, I found that to solve this problem I will need to use Ajax - jQuery.ajax.
I found this code:
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
When I create a form in a SEPARATE page without putting in wordpress template, it works. But when I put the code in wordpress template it updates the page after 3 seconds.
I also discovered that I can use a native function ajax in jquery, the function $.ajax(); and inside of oneself I use tags like url, type, data and so on. I'm a beginner in Ajax and I'm lost on how to do this.
Why the function e.preventDefaul(); not works when I put in wordpress template?? It's possible make it work in wordpress template?
or
How I can use the $.ajax() to solve this problem??
I want send the form without refresh the page!

Take a look in your javsacript console for errors f12 in your web browser
You'll likely see undefined variable "$" or similar error message.
To avoid conflict with other javascript libraries WordPress invokes jQuery noConflict by default.
The easiest solution is to wrap your code inside an iife passing in the jQuery object and redefining it as $
(function($){
console.log($);
//your code
})(jQuery)
Further information
Wordpress has a special url for handling ajax requests and expects an action field for which function at the backend should be called:
(function($){
$(function() {
$('form#myForm').on('submit', function(e) {
var data = $(this).serialize();
data += '&action=my_action'
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (response) {
console.log(response)
}).error(function() {
console.log('XHR error')
});
e.preventDefault();
});
});
})(jQuery)
You would then add a handler function into your functions.php file:
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die(); // this is required to terminate immediately and return a proper response
}
Further reading
https://codex.wordpress.org/AJAX_in_Plugins
How do I return the response from an asynchronous call?

When posting data in wordpress you should handle the request in the functions.php file in your wordpress theme.
And you shouldn't use the dollar sign when working with wordpress replace it with jQuery which would make the code you posted like this:
jQuery(function() {
jQuery('form#myForm').on('submit', function(e) {
$.post('', jQuery(this).serialize(), function (data) {
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
Functions.php
add_action( 'wp_ajax_[action]', 'my_function' );
function my_function() {
var_dump($_POST);
}
The [action] placeholder needs to be replaced with the action matched from your ajax call, say for example 'my_action'
var data = {
action: 'my_action',
form: jQuery(this).serialize()
}
jQuery(function() {
jQuery('form#myForm').on('submit', function(e) {
$.post('', data, function(data) {
}).error(function() {
});
e.preventDefault();
});
});

Zkk,
You actually don't need to submit anything...
2 quick solutions here:
Change your input type to button; or
Add the following to your javascript tag
:
var meuFormulario = document.getElementById("myForm");
meuFormulatio.onsubmit = function(event){
event.preventDefault();
}
This will cancel your submit action and only run your javascript function to calculate the Índice de Massa Corporea (IMC) you need ;)

Related

how do i fix 400 (Bad Request) error about admin-ajax.php

I want to deliver html value through JS to PHP handling, but I still got error, 400 (Bad Request) .
This is HTML:
</div>
<form class="row g-3" id="my_form">
<div class="col-md-12">
<label for="url" class="form-label">Input URL</label>
<input type="text" class="form-control my_info" id="url" required>
<div class="col-12">
<button class="btn btn-primary submit" type="button">Submit form</button>
</div>
</form>
</div>
This is JavaScript:
function getBaseUrl() {
var re = new RegExp(/^.*\//);
var my_local_url = re.exec(window.location.href)[0];
return my_local_url;
}
console.log(getBaseUrl())
jQuery(document).ready(function($) {
console.log('test');
// We'll pass this variable to the PHP function example_ajax_request
var my_data = {
'action':'crawler_info',
'my_info' : document.getElementById('url').value
};
$('.submit').click(function (){
// This does the ajax request
$.ajax({
url: getBaseUrl() + 'admin-ajax.php',
data: my_data,,
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
})
});
This is PHP:
function get_info() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$infos = $_REQUEST['my_info'];
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $infos;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
print_r($_REQUEST);
}
// Always die in functions echoing ajax content or it will display 0 or another word
die();
}
add_action( 'wp_ajax_crawler_info', 'get_info' );
add_action( 'wp_ajax_nopriv_crawler_info', 'get_info' );
I have try many way to fix it, but it still display this error again.
Does anybody know how to solve my problem,Thanks
I have fixed my problem, some code put in wrong place I found

Passing variables from Javascript to PHP using AJAX and Jquery

I am trying to write a simple web page to send data from an html page to a php script and receive some data back from the php. I am attempting to do this with ajax, but the php script never even runs.
This is the HTML.
<script>
$(document).ready(function(){
$('.button').click(function(){
alert("hi");
var clickBtnValue = "hi";
var ajaxurl = 'add.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
This is the PHP.
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.js"></script>
This is included as well. I really can't figure out why it doesn't run the PHP script. Am I attempting to use out of date commands?
EDIT : Added the button HTML code
<div class="ui one column stackable center aligned page grid">
<div class="column twelve wide">
<form>
<button id = "submit_query" type = "button" class="ui green button">Submit</button>
</form>
</div>
</div>
the reason php script is not executing is, it fails to satisfy switch statement
because you are passing value "hi" instead of "insert" or "select"
var clickBtnValue = "insert";//here value is hi instead of insert or select
var ajaxurl = 'add.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
Your Html form
<div class="ui one column stackable center aligned page grid">
<div class="column twelve wide">
<form>
<input type="hidden" name="action" value "insert"> <!-- either insert or select -->
<button id = "submit_query" type = "button" class="ui green button">Submit</button>
</form>
</div>
</div>
In your Js edit it accordingly
$("form").submit(function(event){
// stop the form from submitting
event.preventDefault();
var $form = $(this);
// Get input from all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
$.post('/add.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
});
With this you can pass the data to the add.php
Next you can fetch it using
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
}
function insert() {
echo "The insert function is called.";
}

Insert multiple label fields using for loop in a form

I'm using jquery ajax in codeigniter framework to load a pop up modal on button click. I pass ajax request to a function in controller and receive some data which should be shown in my pop up modal. Number of labels of the modal is depend on the size of the array received by the ajax request.
I have no idea how to do this. But I tried of passing the size of the received array to a hidden type input field in form created on the pop up modal.
Following is my javascript.
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click','#btn_more', function() {
empId = $('#employeeId').html();
fiter_employees(empId);
});
function fiter_employees(empId){
var empSet ={
empId: empId,
method: 'ajax'
};
var empSentUrl = 'http://localhost/eventmanagementsystem/index.php/employee/get_emp_positions';
$.ajax({
type: 'POST',
dataType: 'json',
url: empSentUrl,
data: empSet,
success: function(data){
$('#modal_pkg1').html(data.empPosition.length)
$('#employeePositions').modal();
}
});
}
});
In my pop up model I used the following codes which is not succeeded.
<div id="employeePositions" class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Employee Name :</h4><br/>
<form>
<?php
for ($i=0; $i < ?>
<input type="hidden" id="modal_pkg1" value="modal_pkg1" />
<?php
; $i++) { ?>
<h4 class="modal-title" id="event_name"></h4>
<?php
} ?>
</form>
Can someone tell me the correct me of doing this please...
Your PHP code has executed the moment you load the page, so when you change the modal_pkg1 value, nothing will happen.
Also, the foor loop itself will not work on load, as it's expecting a number that is not there.
I suggest you do it fully in JS, remove all php code from your script; something like below :
in your Ajax success function :
.success(function(data){
var htmlStr = ''
for(var i=0;i<data.empPosition.length;i++){
htmlStr+='<whatever html element you want to display>'
}
$('form').html(htmlStr) // add the generated html string to the <form> element
$('#employeePositions').modal();
}

PHP Ajax Call Navigating to Action Page on Form Submit

I have this ajax call in my php code that still navigates to action page. I want the ajax call to stay on the same page and only update part of the page. What I'm doing wrong here:
<form method="post" id="holderSave" action="student_add_scene.php">
<h3> Save to Holder</h3><br/>
<div id="cutfrom">
<input placeholder="Cut from" name="from" id="from">
<button href="#" onclick="captureElapsed('elapseFrom', 'from');
return false;">capture</button>
</div>
<div id="cutto">
<input placeholder="Cut to" name="to" id="to" >
<button href="#" onclick="captureElapsed('elapseTo', 'to');
return false">capture</button>
</div>
<div id="savecapt">
<input placeholder="add label" id="label" name="label"/>
<input type='submit' value='Save' class='button'>
</div>
</form>
<script>
$('#holderSave').on("submit", (function (e) { // catch the form's submit event
e.preventDefault();
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
var posting = $.post( url, { from: $('#from').val(), label:$('#label').val(), to: $('#to').val()});
posting.done(function(response)){
$('#holderSave').html(response); // update the DIV
alert(response);
}
});
return false;
}));
</script>
This is a syntax error:
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
You seem to be trying to treat the object literal you pass to ajax as a function body. It isn't, so you can't just write statements in it.
Since you make the ajax request with $.post later, $.ajax is entirely pointless. Remove that line and it should work.
Fixed code. Aside from the pointless half-a-call to .ajax, you had a bunch of syntax errors which I've fixed while reformatting it.
Use your browser's developer tools console. Use http://jshint.com/
// Remove pointless ( from before the second argument of the call to on().
$('#holderSave').on("submit", function(e) {
e.preventDefault();
// Remove half a call to .ajax
var $form = $(this),
url = $form.attr('action');
var posting = $.post(url, {
from: $('#from').val(),
label: $('#label').val(),
to: $('#to').val()
});
posting.done(function(response) {
$('#holderSave').html(response);
alert(response);
// Remove line with extra } here
});
return false;
// Remove extra ) here
});
Change submit into button with id
<input type='button' id="save" value='Save' class='button'>
Trigger click event for button, serialize the form data and post the data via ajax
$(document).ready(function() {
$('#save').click(function(){ // catch the form's submit event
var form = $('#holderSave');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form .serialize(),
success: function( response ) {
console.log( response );
}
} );
});
});

passing values from javascript to php

HTML CODE
<form action="phpfile.php" method="post">
<input type="button" id="id1">
<input type="button" id="id2">
<input type="submit">
</form>
<div id="result"></div>
JAVASCRIPT CODE
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
});
Can you give me some tips on how I can send the qty1, qty2 and totalqty to my php file, after I click the submit button. Before I send it to the php file, I need to check first if the button is already clicked. If not, no qty will be send to the phpfile. I need to send the exact number of qty based on how many times you clicked the button.
The easiest solution would be to add qty as <input type="hidden" id="qty1" name="qty1" /> to your form. They will be invisible as your variables, and will be sent to the server as form fields. To access their values from Javascript, use $("#qty1").value()
You're looking for something called AJAX.
This is easy to implement using the jQuery library, but it's also available using regular JavaScript.
If you choose to use the jQuery implementation then your can look at the documentation.
Here's a basic example:
$.ajax({
type : 'post',
url : 'target.php',
dataType : 'json',
data : {
'foo' : 10
}
}).done(function()
{
$(this).addClass("done");
});
You then use the back-end to handle the response, let's for example assume that you send an object of parameters whera one key is named foo and the value is 10, then you could fetch it like this (if the code is PHP):
$foo = isset($_POST['foo']) ? $_POST['foo'] : "";
Using the ternary operator
try using jquery $.ajax or $.post function:
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
get_values(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
get_values(qty2);
});
function get_values(qty_val) {
$.post(
'get_values.php', // url of your php who will receive the values
{ post_variable_name: qty_val }, // your post variables here
function(data) {
// call back function
$("#result").html(data); // see what does your get_value.php echoes via html
console.log(data); // see it via console in inspect element
}
);
}
and in your php that will recieve the values, just retrieve using $_POST:
<?php
$qty_val = '';
if(isset($_POST['post_variable_name'])) {
$qty_val = $_POST['post_variable_name'];
echo $qty_val;
}
?>
HTML
<form>
<input name="id1" type="button" id="id1" />
<input name="id2" type="button" id="id2" />
<input type="submit" />
</form>
<div id="status"></div>
JS
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
});
$( "form" ).submit(function( event ) {
// prevent the default event
event.preventDefault();
// check first if the totalqty. You can add more checks here
if ( totalqty === 0 ) {
// usually show some kind of error message here
alert('No quantity selected!');
// this prevents the form from submitting
return false;
} else {
$.ajax({
type: 'post',
url: 'phpfile.php',
dataType: 'json',
data: {
quantity1: qty1,
quantity2: qty2,
totalQuantity: totalqty
}
}).done(function(data) {
console.log(data);
alert( "success" );
$('#status').html("Successfully saved!");
}).fail(function() {
console.log(data);
alert( "error" );
$('#status').html("Successfully saved!");
});
}
});
PHP
$qty1 = isset($_POST['quantity1']) ? $_POST['quantity1'] : "";
$qty2 = isset($_POST['quantity2']) ? $_POST['quantity2'] : "";
$total = isset($_POST['totalQuantity']) ? $_POST['totalQuantity'] : "";
Sorry, i can't test it, but it should work
For more detailed you could have a look to the jQuery Learning Center - Ajax where you can find useful examples to work with ajax and forms.

Categories

Resources