Values being sent over AJAX but not found in PHP file - javascript

I have a input field which when selected opens a date range calendar.
I am trying to send the date values over AJAX to a PHP file to echo when the apply button is pressed. The AJAX post request does send, however when I try to test for detection in my PHP file nothing is returned.
I have searched online and have found nothing to indicate why. Here is my code
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/latest/css/bootstrap.css" />
<!-- Include Date Range Picker -->
<script type="text/javascript" src="daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="daterangepicker.css" /> </head>
<body>
<input type="text" name="datefilter" value="" id="dates" />
<script type="text/javascript">
$(function () {
$('input[name="datefilter"]').daterangepicker({
"showDropdowns": true
, "minDate": "01/01/2014"
});
$('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) {
$(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) {
$(this).val('');
});
$(".applyBtn").attr('id', 'testing');
$('#testing').click(function (e) {
$.ajax({
type: "POST",
url: 'test.php',
data: {
dates: $('#dates').val()
},
success: function (data) {
alert("success")
}
});
});
});
</script>
</body>
</html>
test.php
<?php
if (isset($_POST['dates'])) {
$range = $_POST['dates'];
echo $range;
} else {
echo "false";
}
?>
EDIT//
response body

The code works fine, the server response is in the "Response" tab:
instead of showing "success" in the alert, you could do this:
success: function (data) {
alert(data)
}
EDIT
Output in test.php:
put datefilter in a form
<form id="frm-test" action="test.php" method="post">
<input type="text" name="datefilter" value="" id="dates" />
</form>
dates -> datefilter in test.php
<?php
if (isset($_POST['datefilter'])) {
$range = $_POST['datefilter'];
echo $range;
} else {
echo "false";
}

Related

How to run ajax and post to PHP

I am trying to run an ajax script from javascript inside a PHP file :
$(document).on('click', '.goto_date', function(){
var datechosen= $('#pickdate').val();
alert(datechosen);
$.ajax({
url:"vdater.php",
method:"POST",
dataType:"json",
data:{'datechosen':datechosen},
success:function(data){
alert('success');
}
});
});
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div align="center">
<input type="button" name="gotodate" value="Go to date" id="gotodate" class="btn btn-danger btn-xs goto_date" />
<input type="date" name='pickdate' id='pickdate' />
</div>
</body>
</html>
But when I run the code nothing happens apart from the alert box referring that the ajax script is reachable in the code..
The PHP file may contain the following code:
echo $_POST['datechosen'];
Surprisingly, It worked by removing the line:
dataType:"json",
Try this one. It must be worked!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Ajax Response</title>
</head>
<body>
<div align="center">
<input type="button" name="gotodate" value="Go to date" id="gotodate" class="btn btn-danger btn-xs goto_date" />
<input type="date" name='pickdate' id='pickdate' />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
let dateBtn = document.querySelector('#gotodate');
let getDate = document.querySelector('#pickdate');
dateBtn.addEventListener('click',(event)=>{
event.preventDefault();
if(getDate.value.trim() !== ""){
console.log(getDate.value.trim());
dateBtn.style.borderColor = "transparent"
jQuery.ajax({
type: "POST",
url: "vdater.php",
data:{
datechosen: getDate.value.trim()
},
success: ((response,status, object) => {
response = JSON.parse(response);
if(response.status){
alert(`Date Chosen: ${response.PickedDate}`);
}
})
});
}else{
dateBtn.style.border = "1px solid #fb5757";
}
});
</script>
</body>
</html>
<?php
if(isset($_POST['datechosen'])){
$date = $_POST['datechosen'];
echo json_encode(["PickedDate"=> $date,"status"=>true]);
}

How to show the session id of php with JavaScript?

I am making a web page where in my index.php file I run a JS function every so often and this function brings data from a php file called closeuser.php, in this case it is the session id.
Example: if I print the session id directly from the index file, it shows me the session id on the screen or with include and the file name if it shows me what the closeuser.php file has, as shown in the following code.
index.php file:
<?php
//session_start();
require_once 'Connections/swag.php';
$ses = session_id();
echo $ses;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">
<link rel="shortcut icon" href="imgs/icon/favicon.ico">
<title>index</title>
<link href="font-awesome/css/all.min.css" rel="stylesheet">
</head>
<body>
<?php include("closeuser.php"); ?>
<script src="js/jquery-3.5.1.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="js/utiles.js"></script>
</body>
</html>
Closeuser.php file:
<?php
echo "a2";
$a = session_id();
echo $a;
?>
It prints me correctly, but if I do it with a js function, as in the following code, it doesn't show me anything, it shows me an empty string in the console, then I don't know why it's the problem:
$(function() {
cron(); // Lanzo cron la primera vez
function cron() {
$.ajax({
method: "POST",
url: "closeuser.php",
})
.done(function(msg) {
console.log(msg)
});
}
setInterval(function() {
cron();
}, 10000); // cada 10 segundos
});
Any idea why you send me the empty string? if I print another string in the closeuser.php file, for example echo "a1"; yes it shows me but the session id doesn't.
you need to add
#session_start();
in "closeuser.php"

Passing variable from ajax to php and it is not being passed

I want to pass a variable value to php on same page using onClick
I have been searching google for days and trying all the examples and can't get anything to work
<!doctype html>
<?php
if(isset($_POST['name']))
{
echo $YourName= $_POST['name'];
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
</head>
<body>
<script type="text/javascript">
function msg(){
var name = "JR";
$.ajax({
type: 'POST',
data: {name : name},
cache: false,
async:false,
success: function(data){
$('#results').html(data);
}
})
}
msg();
</script>
<button type="button" onClick="msg();">Click Me!</button>
</body>
</html>
should pass value to the php part of the page
Add the url in ajax of same page.
If it's in same page, after getting the response use die. otherwise you will get complete HTML code in response. and it should be on top of page.
example.php file will be like.
<?php
if(isset($_POST['name']))
{
echo $YourName= $_POST['name'];
die;
}
?>
<!-- now start html code -->
<!doctype html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function msg(){
var name = "JR";
$.ajax({
type: 'POST',
url:'example.php', //Add the url of same page
data: {name : name},
cache: false,
async:false,
success: function(data){
$('#results').html(data);
}
})
}
</script>
<div id="results"></div>
<button type="button" onClick="msg();">Click Me!</button>
</body>
</html>

How to validate textbox using bootstrap banner

I am relatively new to javascript and Im trying to create a banner that will display if textbox is empty. But it doesn't show. How can I make an alert using bootstrap banners?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
function validateForm() {
var uname = document.getElementById("uname").value;
if (uname == ""){
bootstrap_alert.warning = function(message) {
$('#alert_placeholder').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><span>'+message+'</span></div>')
}
$('#clickme').on('click', function() {
bootstrap_alert.warning('Please enter your name');
});
return false;
}
}
</script>
</head>
<body>
Name: <input type: "text" name="uname" id="uname" />
<input type = "button" id = "clickme" value="Submit"/>
<div id = "alert_placeholder"></div>
</body>
</html>
Well there are several things that you should consider while writing JS code:
Always include $(document).ready(function(){}); if you want your Jquery
code to wait for html body to load. and once it is loaded you want to
use your JS code.
Another thing that you have created a validateform() which is never calling from your code and your main code exists within that function.
I've modified your code to work perfectly
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script>
$( document ).ready(function() {
$('#clickme').on('click', function() {
bootstrap_alert('Please enter your name');
});
bootstrap_alert = function(message) {
var uname=$("#uname").val();
if (uname.length==0){
$('#alert_placeholder').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><span>'+message+'</span></div>')
}
else{
$('#alert_placeholder').html('');
}
}
});
</script>
</head>
<body>
Name: <input type="text" name="uname" id="uname" />
<input type = "button" id = "clickme" value="Submit"/>
<div id = "alert_placeholder"></div>
</body>
</html>
Let me know.. if you need any help in this regard.. I would be gald to help you. Thanks

ajax request not taking place when form is submitted

I'm trying to use Ajax for a form but it seems not to be working. I'm not sure if it's because the file is php but being shown as a javascript file, or something along those lines but I would like to get this fixed. Thanks in advance.
login/index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo SERVER_NAME; ?> | <?php echo $this->title ?></title>
<link rel="stylesheet" media="screen" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="<?php echo URL; ?>/public/css/bootstrap.min.css"></link>
<link rel="stylesheet" href="<?php echo URL; ?>/public/css/css.login.php" />
<script type="text/javascript" src="<?php echo URL; ?>/public/js/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo URL; ?>/public/js/bootstrap.min.js"></script>
</head>
<body>
<div id="login" class="container">
<div class="module">
<div class="module-header">
<h4>Login</h4>
</div>
<div class="module-body module-padding">
<form class="form" method="post" action="<?php echo URL;?>/actions/login.php">
<input type="text" name="login-username" placeholder="Username">
<br />
<input type="password" name="login-password" placeholder="Password">
<br />
<input type="submit" name="submit" placeholder="Login" class="pull-right">
</form>
</div>
</div>
<div class="msg">
</div>
</div>
<script type="text/javascript" src="<?php echo URL; ?>/public/js/user-login.php"></script>
</body>
</html>
user-login.php (acts as js)
<?php
header('Content-Type: application/javascript');
require "../../Application/Configuration/config.php";
?>
$(window).load(function() {
$('.form').submit(function(event) {
var formData = {
'login-username': $('input[name=login-username]').val(),
'login-password': $('input[name=login-password]').val()
};
$.ajax({
type: "POST",
url: "<?php echo URL; ?>/actions/login.php",
data: formData,
success: function (json_data) {
var data_array = $.parseJSON(json_data);
if (data_array['error'] == false) {
$('.msg').css('display', 'block');
$('.msg').addClass('msg-success');
$('.msg p').html(data_array['text']);
$('.msg').fadeOut(4000);
var delay = 4000;
setTimeout(function() {
window.location.replace("../index.php");
}, delay);
} else {
$('.msg').css('display', 'block');
$('.msg').addClass('msg-failure');
$('.msg p').html(data_array['text']);
$('.msg').fadeOut(4000);
}
},
fail: function () {
alert("failed to send");
}
});
});
});

Categories