getting php session from javascript variable - javascript

I am using a JQuery date and time picker in my php website. I want to save the javascript variable as a php session, I have looked at previous answers on this site and tried suggestions but it doesnt seem to be working for me. Can anyone tell me what Im missing?
This is my jquery date and time picker, getting the selected date and time, and the posting ajax:
<input type="text" name="date2" value="">
<script type="text/javascript">
$(function(){
$('*[name=date2]').appendDtpicker({"inline": true,
"allowWdays": [1, 2, 3, 4, 5], // 0: Sun, 1: Mon, 2: Tue, 3: Wed, 4: Thr, 5: Fri, 6: Sat
"futureOnly": true,
"autodateOnStart": false
});
$('#btn_input').on('click', function(){
var input = $('*[name=date2]').handleDtpicker('getDate');
console.log(input);
jQuery.ajax({
url: 'backend.php',
type: 'POST',
data: {
'input': input,
},
dataType : 'json',
success: function(data, textStatus, xhr) {
console.log(data); // do with data e.g success message
},
error: function(xhr, textStatus, errorThrown) {
console.log(textStatus.reponseText);
}
});
});
});
</script>
<input type="submit" class="btn" id="btn_input" value="Confirm">
And this is the backend.php i am sending it to:
<?php
session_start();
$_SESSION['input'] = $_POST['input'];
echo ($_SESSION['input']);
?>
Any help is much appreciated!

New answer:
HTML
<!DOCTYPE html>
<html>
<head>
<!-- include jquery here -->
<script type="text/javascript" src="jquery.simple-dtpicker.js"></script>
<link type="text/css" href="jquery.simple-dtpicker.css" rel="stylesheet"/>
</head>
<body>
<input type="text" class="myDatepicker"/>
</body>
</html>
JS
$(function(){
$('.myDatepicker').appendDtpicker({ //please note that it requires an element that fits this selector
'inline' : true,
'allowWdays' : [1, 2, 3, 4, 5],
'futureOnly' : true,
'autodateOnStart' : false
'onHide': function(handler){
$.ajax({
type: 'POST',
url: 'backend.php',
data: 'input='+ handler.getDate(), //the selected value is being sent to your php, where the session variable is set accordingly
success: function(response){
console.log(response); //in case you have any output (e.g. error messages) in backend.php we will output them to the console for debugging purposes.
}
});
}
});
});
PHP (backend.php)
<?php
session_start();
$_SESSION['input'] = $_POST['input'];
echo $_SESSION['input'];
?>
Complete script would typically look like:
index.php / index.html
<!DOCTYPE html>
<html>
<head>
<!-- include jquery here -->
</head>
<body>
<input type="text" class="myDatepicker"/>
</body>
</html>
<script type="text/javascript">
$(function(){
$('.myDatepicker').appendDtpicker({ //please note that it requires an element that fits this selector
'inline' : true,
'allowWdays' : [1, 2, 3, 4, 5],
'futureOnly' : true,
'autodateOnStart' : false
'onHide': function(handler){
$.ajax({
type: 'POST',
url: 'backend.php',
data: 'input='+ handler.getDate(), //the selected value is being sent to your php, where the session variable is set accordingly
success: function(response){
console.log(response); //in case you have any output (e.g. error messages) in backend.php we will output them to the console for debugging purposes.
}
});
}
});
});
</script>
Please note that the path to backend.php suggests that index.php/index.html and backend.php are located in the same folder.
ORIGINAL ANSWER: Originally I thought we were talking about jQuery-ui datepicker. I'll leave this response in case anyone needs it.
This is one way of doing it...
$('.myElement').datepicker({
minDate: 0, //dates from today and onwards
onSelect: function(date){ //"date" will have the selected value of the datepicker
$.ajax({
type: 'POST',
url: 'backend.php',
data: 'input='+ date, //the selected value is being sent to your php, where the session variable is set accordingly
success: function(response){
console.log(response); //in case you have any output (e.g. error messages) in backend.php we will output them to the console for debugging purposes.
}
});
});

Should you using jquery cookies too(Jquery Cookies).. So, after you call ajax and success, you will get return session from passing your backend.php, and then that result you store to jquery cookies. After that, you can using cookies for next progress..

Try:
<script>
jQuery(function($) {
$(document).on('click', '#btn_input', function(){ // edit here
var input = $('*[name=date2]').handleDtpicker('getDate');
console.log(input);
jQuery.ajax({
url: 'backend.php',
type: 'POST',
data: {
'input': input,
},
dataType : 'json',
success: function(data, textStatus, xhr) {
console.log(data); // do with data e.g success message
},
error: function(xhr, textStatus, errorThrown) {
console.log(textStatus.reponseText);
}
});
});
});
</script>
Does this work? If not, what's value of input in your console?

Related

How to get post value through ajax in view in Codeigniter

I tried to receive Ajax response but the response is null.
My HTML Looks like this
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<select class="form-control" class="form-control" id="choose_country">
<option value="">Select a prefered language</option>
<option value="en">EN</option>
<option value="fr">FR</option>
<option value="de">DE</option>
<option value="nl">NL</option>
</select>
</form>
<div id="table_load"></div> <!-- loads search table -->
My Javascript looks like this
<script>
$('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');
$("#choose_country").change(function(){
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url(); ?>admin/manage_article/search",
type: "post",
data: {choose_country: choose_country},
dataType: 'json',
async: false,
success: function (response) {
if(response.success == true){
alert('success');
$('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');
}else{
alert('fail');
}
},
});
});
</script>
My controller looks like this
public function search(){
$choose_language = $this->input->post('choose_country');
$this->load->view('admin/manage_article/search');
}
}
I want to pass the value of select box to the controller and return back the selected value in the page $this->load->view('admin/manage_article/search');
I have tried the above code but the response alerts "fail".
I am new to ajax so pardon me if there are any mistakes in coding.
Try this, in your controller
public function search() {
$choose_language = $this->input->post('choose_country');
$result = ($choose_language) ? true : false;
$this->output->set_content_type('application/json')->set_output(json_encode(array('choose_country' => $choose_language, 'result' => $result)));
}
your jquery will be as below
<script type="text/javascript">
$(document).ready(function() {
$("#choose_country").change(function() {
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url(); ?>admin/manage_article/search",
type: "post",
data: {
choose_country: choose_country
},
dataType: 'json',
async: false,
success: function(response) {
if (response.result) {
alert('success');
$('#table_load').html(response.choose_country);
} else {
alert('fail');
}
},
});
});
});
</script>
I dont know why you are using the ajax, you might have business logic in controller, which you have not shown. If not then you can simply load the value of choose_country in table_load, as below.
<script type="text/javascript">
$(document).ready(function() {
$("#choose_country").change(function() {
var choose_country = $("#choose_country").val();
$('#table_load').text(choose_country);
});
});
</script>
There is no reason to make two calls to the server - once for the ajax call and then again to load html.
To return and load html into the browser via AJAX do this in your javascript.
$("#choose_country").change(function () {
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url('admin/manage_article/search'); ?>",
type: "post",
data: {choose_country: choose_country},
dataType: 'html',
// Forcing synchronous strongly discouraged,
// as it can cause the browser to become unresponsive.
//async: false,
success: function (response) {
$('#table_load').html(response);
},
error: function(xhr, textStatus, errorThrown){
console.log(textStatus, errorThrown);
}
});
});
Your controller will work the way you show it in the question except I don't see where the posted var is used, so you may not receive the language specific html what you want (If that is what you're trying to do).
If you really feel the need to have the return contain a property called result that you can check using if (response.result) {... then you will need a variation on parth's answer to your question. You can add the html to the returned json with this in your controller.
public function search()
{
//What do you do with this?
//You don't show how this is used so I'm mostly going to ignore it.
$choose_language = $this->input->post('choose_country');
$result = !empty($choose_language) ? true : false;
///get the view file as a string of html markup
$html = $this->load->view('admin/manage_article/search', NULL, TRUE);
$out = array('result' => $result, 'html' => $html);
$this->output
->set_content_type('application/json')
->set_status_header('200')
->set_output(json_encode($out));
}
Then your success function would be like this
success: function(response) {
if (response.result === true) {
alert('success');
$('#table_load').html(response.html);
} else {
alert('fail');

AJAX not sending data

I am using the following code to get data from an input field and send it to PHP by POST but its not working
<script type="text/javascript">
$(document).ready(function () {
$("#id_1").change(function () {
var rat1 = $(this).val();
$.ajax({
url: "upload.php",
type: "post",
data: rat1,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
this is the input form
<input type="number" name="your_awesome_parameter" id="id_1" class="rating" data-clearable="remove"
data-icon-lib="fa" data-active-icon="fa-heart" data-inactive-icon="fa-heart-o"
data-clearable-icon="fa-trash-o"/>
You need to provide a name for the parameter. It should be:
data: { param_name: rat1 }
Then in upload.php you access it with $_POST['param_name']
Just in case, did you imported Jquery into your project?
I tested your code and I with the minor change that Barmar specified and it is working for me.
Try to use this code in your php file and see if you get any response in the developer tools console.
$data = $_POST["param_name"];
echo json_encode([$data]);
Try in this way men
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ejemplo_ajax_proceso.php',
type: 'post',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (response) {
$("#resultado").html(response);
}
});
}
change on input type number is not working in older versions of browsers, I think not sure. But try this below solution as you are using input type number.
$("#id_1").on("mouseup keyup",function () {
//your logic here
});
and passing data as already mentioned by others:
data: { param_name: rat1 }

Ajax not sending info to php

I'm trying to get some information from my php code when clicking on a button, but it doesn't connect to php.
front page is displayed in index.php
index.php:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="functions.js"></script>
<title>Account Panel</title>
</head>
<div "getInfos">
<h2>In this section you can get your inforrmation</h2>
<button id="getNameBtn">Get Your Name!</button>
<span id="getNameSpan"> something must come here</span>
</div>
</body>
</html>
javascript codes and ajax are in
functions.js:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
and php in serverside is some simple thing like this:
handler.php:
<?php
echo('Ajax successful!');
?>
You have not close the document ready function:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
data:JSON.stringify({taskid = 1}),
shoulde be
data:JSON.stringify({taskid: 1}),
First of all, you should better use a newer jquery version.
There is at least one error in your Code:
data:JSON.stringify({taskid = 1})
The json should read
{taskid : 1}
Use a colon, not an equal sign. Not sure that it is true for your jQuery version, but usually data can be attached as json object already, so the whole line should work so:
data: {taskid : 1},
And the data is then visible as POST data in the PHP page. Note that the live() function is deprecated since 1.7. You can use
$("#getNameBtn").click(function(){...});
instead. Moreover, I don't think you need the headers in your request.
First important change you need to do, use $.on instead of $.live, since the latter is deprecated. Another thing you should check, if the handler.php file is at the same level as your JS/HTML file. It could be that the file is not reachable from your code. Here is what you can try:
$(document).ready(function(){
$("#getNameBtn").on('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data: { call: 'myAjax', taskid : 1 },
headers: {
'content-type': 'application/json'
},
success: function(response) {
$('#getNameSpan').html(response);
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
And in the PHP file, you can check for the call key:
<?php
if(isset($_POST) && $_POST['call'] == 'myAjax') {
echo $_POST['taskid'];
exit;
}
?>
That exit is really important.
In your PHP file that returns JSON you should also set the header to JSON.
header("Content-Type: application/json"); //Above all HTML and returns
And the true answer to your problem has already been answered.

Trying to pass js variables to php with ajax

As the title says, I'm trying to pass a couple js variables to a php file. Here is my code so far.
JS:
$.ajax({
method: "POST",
url: "sendDataToDB.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
sendDataToDB.PHP:
<?php
$temp = $_POST["mainVideoData"];
echo $temp;
?>
I saw this code on different websites, but for some reason it's not working for me. It says that 'mainVideoData' is undefined which basically means that it doesn't exist.
Does anyone know what I did wrong?
Thanks!
EDIT:
I've read some suggestions, and decided to make a whole new file with just the code someone gave me that worked for him. Here is my whole php file and whole js file.
php.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery-2.1.3.js" type="text/javascript"></script>
<script src="getApiData.js" type="text/javascript"></script>
<meta charset="utf-8"/>
<link rel="stylesheet" href=""/>
</head>
<body>
</body>
</html>
<?php
if(isset($_POST['mainVideoData'])){
$temp = $_POST["mainVideoData"];
echo $temp;
}
?>
And here is my whole js file:
$(document).ready ( function(){
var mainVideoTitle = "Hello";
$.ajax({
method: "POST",
url: "php.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
});
It only gives me an alert saying 'data sent', but it doesn't echo 'hello'.
Does anyone know what's wrong?
EDIT 2:
So I've added some code in my php file that should put my $temp in a database. Sadly that doesn't work. When I replace $temp by a normal value like 'hello' it places it in my database. When I use $temp it gives me this error:
Error: INSERT INTO youtubevideos (category)
VALUES (Wiz Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack)You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack)' at line 2
As you can see, it does give me the right value, and it also places that right value in VALUES. But for some reason it still gives me this error. Any reason why?
jQuery library is definitely included
check the path of your php file is valid
check mainVideoTitle defined or not
After just try this.
script:
$(document).ready ( function(){
var mainVideoTitle = "Hello";
$.ajax({
method: "POST",
url: "sendDataToDB.PHP",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
});
sendDataToDB.PHP:
<?php
if(isset($_POST['mainVideoData'])){
$temp = $_POST["mainVideoData"];
echo $temp;
}
?>
I hope this is help to achieve your result!!!
Try this it will work.Data will be captured in success.
$.ajax({
method: "POST",
url: "sendDataToDB.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
console.log(data);
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});

Calling JSon file with ajax(Uncaught ReferenceError: request is not defined)

Brand new to using JSon/ajax. Trying to replicate this jQuery UI Autocomplete using a static json file as source just as an example. I'm not positive I'm referencing this correctly if someone could let know whats wrong. Getting a (Uncaught ReferenceError: request is not defined)
<form id="searchform" method="get" role="search">
<input id="searchfield" />
<input type="submit" name="go" value="go!" />
</form>
<script src='js/jquery-1.11.0.min.js'></script>
<script src="js/autocomplete/jquery-ui-1.10.3.custom.js" type="text/javascript" charset="utf-8"></script>
<script>
$(function() {
$.ajax({
url: "json/Providers.json",
dataType: "json",
data: {term: request.term},
success: function(data) {
var cat_data = $.map(data, function(item) {
return {
ProviderID: item.ProviderID,
Name: item.Name,
};
});
$("#searchfield").catcomplete({
delay: 0,
source: cat_data,
minlength:0
});
}
});
});
</script>
json format
{"Providers":[{"ProviderID":"3","NAME":"name1"},
{"ProviderID":"4","NAME":"name2"},
{"ProviderID":"5","NAME":"name3"}]}
This particular data: {term: request.term}, is the problem
You need to define any javascript variable before accessing them.
var request;
In your case data is not required. Just remove data: {term: request.term} since you are loading the static .json file
Since you're a reading json file, it is clear there is no need to pass any parameter. So remove data: {term: request.term}

Categories