Sending a JavaScript variable to PHP - javascript

So I am trying to store the date inside a database and to do so I need to pass the variable 'date' to the PHP file store.pro.php however, I am not sure how to do this. I have tried Ajax but at the moment it doesn't seem to be working.
Javascipt code:
// variables for fetching current date
n = new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
// variables for displaying current date
let displayDay = 0;
let displayMonth = 0;
// If m or d are only one digit, add a leading 0 to the value
if (d < 10) {
displayDay = '0' + d.toString();
} else {
displayDay = d.toString();
}
if (m < 10) {
displayMonth = '0' + m.toString();
} else {
displayMonth = m.toString();
}
// storing the current date within raceDate
var date = displayDay + '/' + displayMonth + '/' + y;
$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date }
});
PHP code in store.pro.php
if (isset($_POST['x'])) {
$raceDate = $_POST['x'];
echo($raceDate);
} else {
echo "no";
}

How do you know "it doesn't seem to be working" ?
add success method to your ajax, like this:
$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date },
success: function(res) {
res = JSON.parse(res);
console.log(res);
}
});
Then, in store.pro.php put this:
if (isset($_POST['x'])) {
$raceDate = $_POST['x'];
echo json_encode($raceDate);
} else {
echo json_encode("no");
}
exit; // You may need remove this line, after you check, that ajax call is working
and check console in your browser

Related

ng2-select2 cannot select a particular option

I am using https://github.com/NejcZdovc/ng2-select2 angular component to handle a pulldown that gets its data from a remote api. The initial list of data that gets populated works fine and I have no problem selecting any of the options in the pulldown, but if I cause the select2 component to have to get data a second time from the api I am not able to select one of the items in the list of options and the previous selection remains selected. Here is some screen show of what is happening.
initial load
Here I select dev1-access-est-1 and the screen looks like.
So far so good.
Now I try to change selection to dhcp-hkg1-1-6
But when I click on dhcp-hkg1-1-6 the Filter Key value remains dev1-access-est-1.
Here is the template HTML I am using for the select2 component:
<div class="form-group__text ">
<select2 name="cm_select2" id="cm_select2" [value]="filterKey" [options]="select2Options"></select2>
</div>
And here is where I am setting my select2Options:
setSelect2Options () {
this.select2Options = {
'width': '100%',
'minimumInputLength': 3,
'ajax': {
'url': function(params) {
var d = new Date(),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var startDate = [year, month, day].join('-');
var url = "http://dev-03.example.com/api/v1/cm/cm_list/?cm_type=" + $( "#node" ).val() + "&start_date=" + startDate + '&source=mongo';
return url;
},
'dataType': 'json',
'data': function (params) {
var query = { 'starts_with': params.term, 'page': params.page || 1 };
// Query parameters will be ?search=[term]&page=[page]
return query;
},
'processResults': function (data) {
var results = [];
for (var i = 0; i < data.results.length; i++ ) { results.push( { "id": i, "text": data.results[i]} ); }
// Tranforms the top-level key of the response object from 'items' to 'results'
return { 'results': results };
}
}
};
}
Can you please try adding cache: false to the options
'ajax': {
'cache': false,
'url': function(params) {
var d = new Date(),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var startDate = [year, month, day].join('-');
var url = "http://dev-03.example.com/api/v1/cm/cm_list/?cm_type=" + $( "#node" ).val() + "&start_date=" + startDate + '&source=mongo';
return url;
},
I found the problem got worse with each access to the remote API. On the second call to the remote API I could not select two options from the list. I read the issue I pointed out in my comment above and realized that one cannot reuse id's from one call to the backend API to the next so I decided to add the epoch time to each id in my processResults() function like so:
'processResults': function (data) {
var results = [];
const epochTime = (new Date).getTime();
// work around for issue https://github.com/NejcZdovc/ng2-select2/issues/136 (use epoch time to get unique ids.
for (var i = 0; i < data.results.length; i++ ) { results.push( { "id": i + epochTime, "text": data.results[i]} ); }
// Tranforms the top-level key of the response object from 'items' to 'results'
return { 'results': results };
}
If some finds a better solution please post it here.

I am trying to retrive data using as an ajax function which is not working properly

In asp.net webform i am trying to call data using ajax call. I have similar function of other page which works fine but on this page i am getting error.
I am getting pageCountInt as NaN
<div id="loadmore" class="loadmore-w"><p id="loadmore-btn" >Load more</p></div>
Table has about 6 records and it loads the first 2 records and when i cluck on the load more button it doesnt load any more data and show pageCountInt as NaN
var pageIndexInt = 0;
var pageCountInt = 0;
GetInterviewRecords();
$('#loadmore-btn').click(function() {
// console.log("button clicked");
GetInterviewRecords();
});
function GetInterviewRecords() {
//console.log("i am in GetInterviewRecords function");
pageIndexInt++;
console.log("pageIndexInt " + pageIndexInt);
console.log("pageCountInt " + pageCountInt);
if (pageIndexInt == 1 || pageIndexInt <= pageCountInt) {
$("#loading-interview").show();
$.ajax({
type: "POST",
url: "<%= ResolveUrl ("~/en/Default.aspx/GetInterviews ") %>",
data: '{pageIndex: ' + pageIndexInt + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessInterview,
failure: function(response) {
alert(response.d);
},
error: function(response) {
alert(response.d);
}
});
}
}
function OnSuccessInterview(response) {
// console.log("i am in OnSuccessInterview function");
var xmlDocInterview = $.parseXML(response.d);
console.log("Interview XML ----");
//console.dirxml(xmlDocInterview);
//console.dir(xmlDocInterview);
var xmlInterview = $(xmlDocInterview);
pageCountInt = parseInt(xmlInterview.find("pageCount").eq(0).find("pageCount").text());
var interview = xmlInterview.find("Table");
interview.each(function() {
var articleItem = $(this);
var aImagePath = '<%= ResolveUrl ("http://website.com/images/Interview/")%>' + articleItem.find("PageImage").text();
var aTitle = articleItem.find("Heading").text();
var aURL = 'http://website.com/interview/' + aID + "/" + aTitle;
$('<div class="tab-item-wrapper"><img src="' + aImagePath + '" class="tab-i-a-img"><span class="tab-i-a-title">' + aTitle + '</span></div>').appendTo(".wrapper");
});
if (pageIndexInt >= pageCountInt) {
$("#loadmore").hide();
}
}
C# Function
public static DataSet GetInterviewListByLangID(int LangID, int PageIndex, int PageSize)
{
DataSet ds = null; int PageCount = 0;
try
{
SqlParameter[] sqlparam = new SqlParameter[4];
sqlparam[0] = new SqlParameter("#LangID", LangID);
sqlparam[1] = new SqlParameter("#PageIndex", PageIndex);
sqlparam[2] = new SqlParameter("#PageSize", PageSize);
sqlparam[3] = new SqlParameter("#PageCount", PageCount);
sqlparam[3].Direction = ParameterDirection.Output;
ds = SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, "usp_GetInterviewListwise", sqlparam);
DataTable dt = new DataTable("PageCount");
dt.Columns.Add("PageCount");
dt.Rows.Add();
int TotalPageCount = 0;
if (!String.IsNullOrEmpty(sqlparam[3].Value.ToString()))
{
TotalPageCount = (int)sqlparam[3].Value;
}
dt.Rows[0][0] = TotalPageCount;
ds.Tables.Add(dt);
}
catch (Exception ex)
{
//HttpContext.Current.Response.Redirect("Message.aspx?msg=Invalid Request");
}
return ds;
}
[WebMethod]
public static string GetInterviews(int pageIndex)
{
// System.Threading.Thread.Sleep(1000);
return GetInterviewListByLangID(1, pageIndex, 2).GetXml();
}
SQL SERVER SP
ALTER PROCEDURE [dbo].[usp_GetInterviewListwise]
#LangID int
,#PageIndex INT = 1
,#PageSize INT = 6
,#PageCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [PublishDate] DESC
)AS RowNumber
,[InterviewID] AS ID
,[Title] As Heading
,[Description] AS Brief
,REPLACE(CONVERT(CHAR(10), [PublishDate], 103), '/', '-') AS ReleaseDate
,[Image] AS PageImage
,[VideoID] AS VideoID
INTO #Results
FROM Interview WHERE Visible = 1 AND Active = 1 AND LanguageID = #LangID
AND InterviewID NOT IN (SELECT TOP 1 InterviewID FROM Interview WHERE LanguageID=#LangID AND Active=1 AND Visible = 1 Order by PublishDate DESC)
DECLARE #RecordCount INT
SELECT #RecordCount = COUNT(*) FROM #Results
SET #PageCount = CEILING(CAST(#RecordCount AS DECIMAL(10, 2)) / CAST(#PageSize AS DECIMAL(10, 2)))
PRINT #PageCount
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
END
How i can improve this code and convert this into json or fix the same where i work with XML. I am not sure why pageCountInt value is NaN and i am finding it even more hard to debug it also.
I solved the issue as i was using PageCount as pageCount in the following lien of code
pageCountInt = parseInt(xmlInterview.find("PageCount").eq(0).find("PageCount").text());
Just wasted 4 hours figuring out what could be the issue. CaSe SeNsiTiVe OHHHH!!!

jQuery AJAX call freezes all other JS logic

I am trying to get a *.srt file and parse it with this script: Parse a SRT file with jQuery Javascript.
I've got a problem with the AJAX call blocking rest of the JS code. I tried to add syncs, set timeout, I wrapped it into a setTimeout function, tried with another *.srt file, but still it's not working. It doesn't throw error, it alerts end dialog, parsed lines are stored in variable but another scripts are frozen.
var subtitles = [];
$.ajax({
method: "GET",
url: '{% static "file.srt" %}',
async: true,
error: function(data) {
alert("error");
},
success: function(data) {
function strip(s) {
return s.replace(/^\s+|\s+$/g, "");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
srt = strip(srt);
var srt_ = srt.split('\n\n');
var cont = 0;
for (s in srt_) {
st = srt_[s].split('\n');
if (st.length >= 2) {
n = st[0];
i = strip(st[1].split(' --> ')[0]);
o = strip(st[1].split(' --> ')[1]);
t = st[2];
if (st.length > 2) {
for (j = 3; j < st.length; j++)
t += '\n' + st[j];
}
//define variable type as Object
subtitles[cont] = {};
subtitles[cont].number = n;
subtitles[cont].start = i;
subtitles[cont].end = o;
subtitles[cont].text = t;
document.body.innerHTML += " (" + subtitles[cont].start + " - " + subtitles[cont].end + " ) " + subtitles[cont].text + "<br>";
}
cont++;
}
alert("end");
},
timeout: 2000,
});
Please help me.

How to make yahoo finance YQL query more than 1 year stock data?

I'm using a tableau web connector to download stock price. The source code is following:
<html>
<meta http-equiv="Cache-Control" content="no-store" />
<head>
<title>Stock Quote Connector-Tutorial</title>
<script src="https://connectors.tableau.com/libs/tableauwdc-1.1.1.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function() {
function buildUri(tickerSymbol, startDate, endDate) {
var startDateStr = getFormattedDate(startDate);
var endDateStr = getFormattedDate(endDate);
var queryStatement = 'select * from yahoo.finance.historicaldata where symbol = "' +
tickerSymbol +
'" and startDate = "' + startDateStr +
'" and endDate = "' + endDateStr + '"';
var uri = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(queryStatement) +
"&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json";
return uri;
}
function getFormattedDate(date) {
// Return a date in the format YYYY-MM-DD
return date.getUTCFullYear() +
'-' +
makeTwoDigits(date.getUTCMonth() + 1) +
'-' +
makeTwoDigits(date.getUTCDate());
}
function makeTwoDigits(num) {
// Pad a digit to be two digits with leading zero
return num <= 9 ? "0" + num.toString() : num.toString();
}
var myConnector = tableau.makeConnector();
myConnector.getColumnHeaders = function() {
var fieldNames = ['Ticker', 'Day', 'Close'];
var fieldTypes = ['string', 'date', 'float'];
tableau.headersCallback(fieldNames, fieldTypes);
}
myConnector.getTableData = function(lastRecordToken) {
var dataToReturn = [];
var hasMoreData = false;
// Get parameter values and build YQL query
var ticker = tableau.connectionData;
var endDate = new Date();
var startDate = new Date();
startDate.setYear(endDate.getFullYear() - 1);
//startDate.setYear(startDate.getFullYear() - 1);
//startDate.setYear(startDate.getFullYear() - 1);
//startDate.setYear(startDate.getFullYear() - 1);
var connectionUri = buildUri(ticker, startDate, endDate);
var xhr = $.ajax({
url: connectionUri,
dataType: 'json',
success: function (data) {
if (data.query.results) {
var quotes = data.query.results.quote;
var ii;
for (ii = 0; ii < quotes.length; ++ii) {
var entry = {'Ticker': quotes[ii].Symbol,
'Day': quotes[ii].Date,
'Close': quotes[ii].Close};
dataToReturn.push(entry);
}
tableau.dataCallback(dataToReturn, lastRecordToken, false);
}
else {
tableau.abortWithError("No results found for ticker symbol: " + ticker);
}
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.log("Connection error: " + xhr.responseText + "\n" + thrownError);
tableau.abortWithError("Error while trying to connect to the Yahoo stock data source.");
}
});
}
tableau.registerConnector(myConnector);
})();
$(document).ready(function() {
$("#submitButton").click(function() {
var tickerSymbol = $('#ticker').val().trim();
if (tickerSymbol) {
tableau.connectionName = "Stock Data for " + tickerSymbol;
tableau.connectionData = tickerSymbol;
tableau.submit();
}
});
});
</script>
</head>
<body>
<p>Enter a stock ticker symbol: <input type="text" id="ticker" /></p>
<p><button type="button" id="submitButton">Get the Data</button></p>
</body>
</html>
The code is workable when we just want to download 1 year data, but if we change the time longer than 1 year(enddate.year - startdate.year > 1), it is not workable.
After debugging the code, I found the issue comes from YQL query:
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.historicaldata where symbol = "AAPL" and startDate = "2014-08-24" and endDate = "2016-11-23"&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json
when startDate = "2014-08-24" and endDate = "2016-11-23" is longer than 15 month, YQL will return null. I'm trying to fix this issue. If it is python or java, the problem is not hard, first check whether the duration is longer than 1 year, if so, get 1 year result and do the same for rest n-1 year. But this tableau code makes me stuck with it. I have to make the code workable with tableau, which makes me unable to proceed due to lack of knowledge about both js and tableau.
Can any one advise on this issue? My objective is to make the code workable for >10 years for stock symbol like AAPL.
Thanks in advance.
I don't believe YQL supports queries for longer than 15 months or so. Limits like these are fairly common when working with APIs. What you want to do from a web data connector standpoint is to implement paging.
The high level idea is that your getTableData function of your WDC will execute multiple times, and each time, it will gather a single page of data, which is then passed to Tableau. For example, here's how you could get multiple years worth of data in your example:
myConnector.getTableData = function(lastRecordToken) {
var dataToReturn = [];
var hasMoreData = false;
// Get parameter values and build YQL query
var ticker = tableau.connectionData;
var endDate = new Date();
var startDate = new Date();
var maxYear = 5;
var yearOffset = lastRecordToken || 0;
endDate.setYear(endDate.getFullYear() - (yearOffset));
startDate.setYear(endDate.getFullYear() - 1);
var connectionUri = buildUri(ticker, startDate, endDate);
var xhr = $.ajax({
url: connectionUri,
dataType: 'json',
success: function (data) {
if (data.query.results) {
var quotes = data.query.results.quote;
var ii;
for (ii = 0; ii < quotes.length; ++ii) {
var entry = {'Ticker': quotes[ii].Symbol,
'Day': quotes[ii].Date,
'Close': quotes[ii].Close};
dataToReturn.push(entry);
}
var hasMoreData = !(yearOffset == maxYear);
tableau.dataCallback(dataToReturn, yearOffset + 1, hasMoreData)
}
else {
tableau.abortWithError("No results found for ticker symbol: " + ticker);
}
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.log("Connection error: " + xhr.responseText + "\n" + thrownError);
tableau.abortWithError("Error while trying to connect to the Yahoo stock data source.");
}
});
}
tableau.registerConnector(myConnector);
})();
This example uses the two extra parameters of the dataCallback function to implement paging. The documentation for paging in v1 of the web data connector API can be found here: http://onlinehelp.tableau.com/current/api/wdc/en-us/help.htm#WDC/wdc_paging.htm%3FTocPath%3DAdditional%2520Concepts%7C_____2
Additionally, if you are able to use v2 of the WDC API (usable in Tableau 10 and later), I would highly recommend it. The paging model in V2 is more flexible and easier to use.

Js onload and document.getElementById not working for me

Something in my code is not working. I am new to this. I think it is the onload maybe?
I am trying to convert a 24 clock to a 12 hour GMT server time clock and I have got as far as passing my new code to the CSS div I made.
All the CSS is fine and my coding works well with alert but not with onload and document.getElementById.
<script>
var currenttime = '<? print date("F d, Y H:i:s a", time())?>'
var serverdate=new Date(currenttime)
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = serverdate.getHours();
var hours = ((hours24 + 11) % 12) + 2;
formatted = [formatted, [addZero(hours), addZero(serverdate.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");
}
document.getElementById("servertime").innerHTML=formatted
return formatted;
}
})();
window.onload=function(){
formatTime(new Date())
}
</script>
</head>
<body>
<h1><p><span id="servertime"></span></p></h1>
</body>
You could just write this, no need for javascript at all.
<h1><p><span id="servertime"><? print date("F d, Y h:i:s a", time())?></span></p></h1>
In case you are preparing a periodic update with your javascript (here it makes sense), I suggest using a simple jquery script for it:
$(document).ready(function() {
function update() {
$.ajax({
type: 'POST',
url: 'servertime.php',
timeout: 1000,
success: function(data) {
$("#servertime").html(data);
window.setTimeout(update, 1000);
},
});
}
update();
});

Categories