How to get user data from Javascript user back to Django - javascript

I'm using Django and Bootstrap to create a simple website.
In my .html file, I'm using Bootstrap to display a datepicker.
<div id="datepicker" ></div>
Also in the .html, I have some quick and dirty javascript code that gets updated when my datepicker gets clicked on.
<script>
function setup(){
<SOME OTHER JS>
$('#datepicker').on("changeDate", function() {
$('#my_hidden_input').val(
$('#datepicker').datepicker('getFormattedDate')
);
});
$(document).ready(setup);
</script>
I want to pass back this new date to my Django page. Basically I want to refresh the page with data pertaining to this new date, and my Django code knows how to handle the new date.
How should I do that? Should I redirect back to my current page, but add something to the URL so that Django's regex will pick it up? Or should I make it an Http GET with the new date?

<script>
function pass_this_to_backend(date){
$.ajax({
type: "POST",
url: "/get_date/",
data: { 'date':date },
dataType: "json",
success: function(response) { alert(response); },
error: function( rrror) { alert(error); }
});
}
function setup(){
<SOME OTHER JS>
$('#datepicker').on("changeDate", function() {
$('#my_hidden_input').val(
$('#datepicker').datepicker('getFormattedDate')
);
pass_this_to_backend(date);
});
$(document).ready(setup);
</script>

You can use Ajax to get data from server without page refresh:
jQuery.ajax({
type: 'POST',
url: 'web/path/to/php/file.php',
data: {
post_date: $('#datepicker').val() //this is the data to post to server
},
success: function(res) {
//code executed after server response. res - server response
$('#datepicker').append(res); //modifying your html
}
});
And in file.php for example:
echo $_POST['post_date']; //accessing your date on server side and return it
If you do need to refresh the page, you can send your data in url:
$('#datepicker').on("changeDate", function() {
var val = $('#my_hidden_input').val(
$('#datepicker').datepicker('getFormattedDate')
);
val = encodeURIComponent(val); //encode data for url passing
window.location.href = '?date = ' + val; //goto url with appended parameter
});
To get data you use:
$date = urldecode($_GET['date']);

Related

JS / JSON: Cannot redirect to next page after insert data (AJAX JSON)

Based on my question, I have successfully added input data to the database using ajax. However, it cannot redirect to the next page, "viewDetails.html" after inserting the data. Can anyone know how to fix it?
<script>
$('#userForm').submit(function(e){
$.ajax({
type: "GET",
url: "https://yes.hus.com/yesss/husss.asmx/TGA_AppAttendanceInsert?",
data:$('#userForm').serialize(),
beforeSend: function(){
console.log("Pending to send");
},
success: function(response){
console.log("Pending to send" + response);
window.location.href = "viewDetails.html";
return true;
},
});
});
</script>
Add e.preventDefault() after submit function line.
Like
<script>
$('#userForm').submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "https://yes.hus.com/yesss/husss.asmx/TGA_AppAttendanceInsert?",
data:$('#userForm').serialize(),
beforeSend: function(){
console.log("Pending to send");
},
success: function(response){
console.log("Pending to send" + response);
window.location.href = "viewDetails.html";
return true;
},
});
});
</script>
When you use element.submit function, javascript will automatically send request to server side. So usually you don't need an ajax function inside it. Except you need to do something after request.
With e.preventDefault(), submit default function will stop and go to your ajax function.
Also you don't need a question marks on url. Ajax will generate it automatically.

Security issues while sending variable from Javascript to PHP

I'm developing JavaScript game. I need to insert some records (such as score, time, level, etc.) to database.
To do It I can use JavaScript in following:
function jsFunction() {
var jsScore = 1000;
window.location.href = "file.php?score=" + jsScore;
}
And in PHP file I could use $_GET['score'];
But looks like this way is not secure, user could change score at address bar directly in browser. Am I wrong?
How could I do It in more secure way?
Maybe sending the data via AJAX post would be more appropriate. Technically the user could still edit it using the dev console but it much less visible.
<script>
function jsFunction() {
var jsScore = 1000;
$.post( "file.php", { score: jsScore})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
</script>
You can make use of the jquery library and send the ajax request to the php page. like below.
function jsFunction() {
var jsScore = 1000;
$.ajax({
method: "POST",
url: "file.php",
data: { score: jsScore }
}).done(function(response){
//you can perform some activity after score saved etc..
}).fail(function(response){
//you can perform some activity if score do not saved etc..
})
}
then you can access the score using $_POST['score']; in php.
Try sending data in post using ajax. This will not show data in url and is also secure as the data passes in post.Here is the code
var score = '1000';
var time = '10';
$.ajax({
url: 'file.php',
type: "POST",
data: {score: score, time: time,},
success: function(posData) {
// success code here
},
});
In file.php you can get all parameters in
print_R($_POST);

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

AJAX will post to originating page but not another

I have a script that submits multiple forms using AJAX. It will post the data successfully if the url used is the originating page, but it will not post the data to another page (the page I use for processing).
Can anyone tell me why this is happening?
/* AJAX for edit */
var submitForms = [
document.forms["editRow"],
document.forms["editRow2"],
document.forms["editRow3"],
document.forms["editRow4"],
document.forms["editRow5"],
document.forms["editRow6"],
document.forms["editRow7"],
document.forms["editRow8"]
]
$('.submitEdit').on('click', function() {
var editRow = $(submitForms).serializeArray();
$.ajax({
type: 'POST',
url: "IRCprocessinventory.php",
data: editRow,
cache: false,
success: function(result){
$('body').html(result);
} //end result
}); // end ajax
}); // end click

Ajax Success data returns complete HTML page

I'm using iFrame class JSP page with Date picker field on it. On selecting a date from the picker, I'm sending the date to the Struts Action using jQuery AJAX call like below:
$( "#datepickerStart" ).datepicker({
onSelect: function(dateText, instance) {//date select from picker to trigger
$.ajax({
type: "Post",// post method
url: 'checkAvailability.do?operation=getlist&datepickerStart='+ ("#datepickerStart").val(), // passing URL with date value to STRUTS Action
data: "date="+date,
//dataType: "application/json",
success: function(data) {
alert(data); //getting with the complete HTML page
}
});
}
});
And from DB I'm fetching the results in LIST and converting to JSON object like below:
Gson gson = new Gson();// Using google GSON to convert to JSON
String json = new Gson().toJson(lRList);
response.setContentType("application/json");// setting content type
response.setCharacterEncoding("UTF-8"); //setting character encoder
response.getWriter().write(json);// writing to response the JSON object
System.out.println("JSON Object::"+json);
And in standard output gives me the result like this:
JSON Object::[{"bookDate":"2014-07-11","fromTime":"2:00PM","totime":"3:30PM","userID":"XXX","isSuccess":false},
{"bookDate":"2014-07-11","fromTime":"10:30AM","totime":"11:00AM","userID":"XXX","isSuccess":false}]
But the alert in Ajax success gives the complete HTML page :(. I need this data and want to populate the values in the same JSP by showing in a div table. So can anyone help me on this to resolve it and let me know where I'm doing the mistake...
i think you should use get instead of post in the ajax call
$( "#datepickerStart" ).datepicker({
onSelect: function(dateText, instance) {//date select from picker to trigger
$.ajax({
type: "get",
url: 'checkAvailability.do?operation=getlist&datepickerStart='+ ("#datepickerStart").val(), // passing URL with date value to STRUTS Action
data: "date="+date,
//dataType: "application/json",
success: function(data) {
alert(data); //getting with the complete HTML page
}
});
}
});
setup AJAX error to get the error like:
$.ajaxSetup({
error: function(jqXHR, e) {
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText);
console.log('Error msg: '+msg);
}
});
and then set datatype as json in your AJAX call as your getting response in Json format like:
$("#datepickerStart").datepicker({
onSelect: function(dateText, instance) {
$.ajax({
type: "post",
url: 'checkAvailability.do?operation=getlist&datepickerStart='+$("#datepickerStart").val(),
data: "date="+date,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
}
});
}
});
also you were forgot to put $ starting of ("#datepickerStart").val()
for further reference checkout my app

Categories

Resources