Ajax not calling PHP - javascript

I have a problem with ajax calling a PHP code without change current page. In the php_error.log there is no reference to the PHP file. I have no errors on screen or anything to guide me to resolve the problem.
This is my javascript function
<script type="text/javascript">
function getMail(){
var name = $('#username').val();
var dominio = $('#dominio').val();
if(name.trim() == '' ){
alert('Ingrese su nombre de usuario.');
$('#username').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'paginas/recover.php',
//data:'username='+name+'&dominio='+dominio,
beforeSend: function () {
$('.nextBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
$('#username').val('');
$('.nextBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
},
});
}
};
</script>
This is the function calling button from the HTML
<button id="nextBtn" type="button" class="btn btn-primary nextBtn btn-lg pull-right" onclick="getMail()" disabled>Continuar</button>
And this is the PHP code
<?php
//include ('../paginas/header.php');
include ('../paginas/funciones.php');
//$dominio = $_GET['dominio'];
//$usr = $_GET['username'];
//getToken($usr,$dominio);
$to_mail = 'mail#gmail.com';//getMail($usr, $dominio);
$to_name = 'Usuario Prueba';
$message = 'Prueba';
$subject = 'Prueba';
sendMail($to_mail,$to_name,$subject,$message);
?>
If I access the PHP file alone, the mail was sent, but when I use the javascript function, nothing happened. The function was invoked because if I don't complete the username in the form the alert was executed.
Thanks

//data:'username='+name+'&dominio='+dominio,
change above line to this make it uncomment and pass data as blank
data:'',

Related

How to pass a php variable in window.open function

I have PHP loop ( WHILE{} ) that loops an array from MySQL and creates a page with the data line by line. I need to add to each line a button that will trigger a new page but I need to carry the value of the id of the line to that new pop-up page. This is the code I have, but i can't figure out how to pass my id to the pop up:
I know I can't add my PHP variable to the URL in the JS function, because it sits outside the loop. Can I use the JS function to add it ? Here is some simplified code:
PHP Code
<?php
while ($all = mysql_fetch_array($get_all)){
$id= $all['id'];
echo '<button type='button' class='btn btn-danger' onclick='openWin()'> Click here</button> ';
}
?>
Javascript
<script>
var myWindow;
function openWin() {
myWindow = window.open("http://www.website.com/pop.php", "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>
I need to get $id to the new page. As stated I was hoping to add it to the URL as a $_GET variable, but I don't seem to know how to add it since the url sits in the JS function outside the while loop.
Sorry for the poor indenting
just pass a parameter
while ($all = mysql_fetch_array($get_all)){
$id= $all['id'];
echo '<button type="button" class="btn btn-danger" onclick="openWin(\''.$id.'\')"> Click
here</button> ';
}
<script>
var myWindow;
function openWin(id) {
myWindow = window.open("http://www.website.com/pop.php?p_id="+id, "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>
hope it will work for you.
while ($all = mysql_fetch_array($get_all)){
...
$id= $all['id'];
echo "<button type='button' class='btn btn-danger' onclick='openWin($id)'> Click here</button>";
...
}
<script>
var myWindow;
function openWin(id) {
myWindow = window.open("http://www.website.com/pop.php?id="+id, "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>
Add the id as an attribute of your HTML <button> element and pass that to the openWin function, eg
while ($all = mysql_fetch_array($get_all)) : ?>
<button type="button" class="btn btn-danger" onclick="openWin(this.dataset.id)"
data-id="<?= htmlspecialchars($all['id']) ?>">
Click here
</button>
<?php endwhile ?>
and in your JS
function openWin(id) {
myWindow = window.open(
`http://www.website.com/pop.php?id=${encodeURIComponent(id)}`,
'myWindow',
'width=600,height=800'
)
}
I've used an HTML attribute to store the value (as opposed to just injecting it into the onclick expression) to avoid the issue of having to simultaneously HTML and JS encode the value.
I've also used data-id instead of just id because a 3-digit number makes a bad HTML element ID, prone to easy conflicts.
2 steps to follow
Pass your php variable $id to javascript function using function-call-by-value reference,
then use that argument in GET request for url to be opened in new window
$id= $all['id'];
echo "<button type='button' class='btn btn-danger' onclick='openWin(".$id.")'> Click here</button> ";
}
?>
<script>
var myWindow;
function openWin(id) {
myWindow = window.open("http://www.website.com/pop.php?id="+id, "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>
Use cookies or HTML5 localStorage if its purely on the client-side.
Simple jQuery (Pass as a query string in the URL)
<script>
var myWindow;
function openWin(id) {
myWindow = window.open("http://www.website.com/pop.php?p_id="+id, "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>
Example 2 Simple jQuery (Pass as a query string in the URL via function)
function set_url_data(go_to_url, data) {
new_url = go_to_url + '?data=' + data;
window.location.href = new_url;
}
LocalStorage
//Set data
localStorage.setItem('bookedStatus' + customerId, true);
//Get data
localStorage.getItem('bookedStatus');
Ajax
<script>
$.ajax({
type: "POST",
url: package.php,
data: $("#myform").serialize(),
success: function(data)
{
$('#Result').html(data);
}
});
</script>

How to send a form without refreshing the page

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 ;)

Yii2: call javascript function with a button

I want to call a javascript function from a button in php
this is the php code:
//the view
<?php
$form = yii\widgets\ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>
<?=
$form->field($msubs, 'id_subespecifica', ['options' => ['class' => 'col-md-12']])
->widget(Select2::classname(),[
'data' => ArrayHelper::map($vectorConsul,'sesp', 'sesp'),
'options' => ['id' => 'prueba'],
])
->label(false);
?>
<button class="btn btn-primary" onclick="myFunction()">Add New</button>
<?php
yii\widgets\ActiveForm::end();
?>
And this is the Javascript code:
//Javascript
function myFunction() {
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:{pruebaId:$('#prueba').val()}
// alert(pruebaId);
});
In the javascript function, i need to send the $('#prueba').val() to a php function in the controller:
//Controller
public function actionGetLinea($pruebaId)
{
$model = new PartidaAsociada();
log($pruebaId);
}
But i am getting some errors, i think the button is reloading the whole form and don't recognize the previous data y sent to the form.
Note: The 'alert()' in the javascript function is on commentary because it wont let me use, the form stay loading when i put the alert. thanks beforehand.
I think part of the problem is you aren't preventing the default action of a button click.
We can clean things up a bit too. Hit control+shift+i and choose the console tab to see console.log output.
HTML:
<button class="btn btn-primary _addNew">Add New</button>
Javascript:
$('._addNew').on('click', function(event){
event.preventDefault();
var data = {};
data.pruebaId = $('#prueba').val();
var success = function(data){
console.log("Success!", data);
}
var error = function(data){
console.log("Error!", data);
}
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:data
}, success, error);
});

FIXED jQuery Validate + php check user exits

I am trying to add to a form, which is validated with jQuery validate, and a PHP script where I check if the user (usuario) exits. Each user has a different folder. To check if the user exits, I check if the folder exists then if exists, tell there is an error and I don't want to stop the form from being submitted. If not, I create the sub-folder with the username and create the folder.
Currently, I use the AJAX solution, but the PHP is not executed, and it won't print any echo on it.
I have been reading more about AJAX and about the remote attribute in jQuery validate but neither way I can get my functionality to work out.
With Ajax (or what I have understood as ajax)
submitHandler: function(form) {
var username = $(this).val();
$.post('check_user.php', {'usuario':username}, function(data) {
$("#user-result").html(data);
form.submit();
});
}
With remote
"usuario":{
required: true,
rangelength: [3, 10],
remote: {
url: "check-user.php",
type: "get",
data:{
usuarios: function(){
return $('#usuario').val();
}
}
}
}
My PHP
<?php
$user = $_REQUEST['usuario'];
$dir = "usuarios/$user";
if (!file_exists($dir)) {
echo 'true';
} else {
if(!mkdir($dir, 0777, true)) {
echo 'Fallo al crear las carpetas...'
}
$doc = new_xmldoc('1.0');
$root = $doc->add_root('historial');
$fp = #fopen('historial.xml','w');
if(!$fp) {
echo 'Fallo al crear historial.xml'
}
fwrite($fp,$doc->dumpmem());
fclose($fp);
echo 'true';
}
?>
Piece of my form (HTML)
<form id="register" action="index.php" method="post" onsubmit="return validateForm();">
<div class="elRegister"><label>Usuario:</label>
<input name="usuario" id="usuario" type="text" size="16"></div>
UPDATE:
Closing correctly the brackets i continue having problems.The rules goes fine but after filling correctly my form, when i press submit button it makes nothing. If something in my form is wrong it will display the error corrrectly.
My script will have the following structure:
<script type="text/javascript">
(function($, W, D) {
var validaForm = {};
validaForm.UTIL =
{
setupFormValidation: function()
{
//Reglas de validacion
$("#register").validate({
debug:true,
rules: {
},
messages: {
},
submitHandler: function(form) {
var username = $(this).val();
$.post('check_user.php', {'usuario':username}, function(data) {
$("#user-result").html(data);
form.submit();
});
}
});
}
}
$(D).ready(function($) {
validaForm.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
Thanks for everything and if you need more things of my code, simply ask.
FIXED
Finally i hve been able to fix this problem. I found the solution in here: YouTube
The solution was to use both, ajax and remote rule. With remote rule i check if the user exists and with the ajax i override the form submit and write another one instead which look like:
$("#register").submit(function() {
var valido = $("#register").valid();
if(valido){
var $inputs = $('#register :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
alert("Formulario valido");
$.get("crear_usuario.php",values);
}
else{
alert("Formulario no valido");
}
});
Thank you for your answers!
You are not properly closing submitHandler. Here is the fixed code.
submitHandler: function(form) {
var username = $(this).val();
$.post('check_user.php', {'usuario':username}, function(data) {
$("#user-result").html(data);
form.submit();
});
}

Posting Javascript variable to PHP document

I want to get the value of data-id in my tag and transfer it to a PHP variable.
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
I already got the value of data-id using the javascript below and placed it into a variable, however its not posting on the page.
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid});
});
I tried doing this...
print_r($_POST);
but the array being displayed is empty What am I doing wrong here? Kinda new at this.
If you're trying to post on the same page (which is a bad idea anyway), you should have always have an exit/die; on that PHP catch block, and a success function callback on the $.post.
Example:
Simulated JS:
<?php $adminid = 1; ?>
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid}, function(response){
console.log(response);
});
});
</script>
Here on the PHP (same page):
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
}
Or
if(isset($_POST['admin_to_pass'])) {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
// you must have this or you'll catch the whole document
}
And since in your current code you don't have one, you need the success callback function to process the response which came from the server:
$.post("index.php", {admin_to_pass: adminid}, function(response){
^^^^
console.log(response); // your response from the server is inside (you can name it any name you want)
});

Categories

Resources