I'm new to JS. I have a script which should count clicks and store clicks number value in cookie. The problem is I can't correctly save and call clicks number(generated by parseInt) value from cookies.
Here is the code http://jsfiddle.net/csTpG/99/ (using jquery.cookie plugin)
$('#counter').click(function() {
var productID = $(this).attr('name');
var $this = $(this);
$.get('/', {
item_id: productID
}, function(response) {
if (response) {
if (response == 'empty')
$this.text('Count');
else
$this.text('Count (' + parseInt(response) + ')');
$.cookie('clicked-counter', 'true');
}
});
return false;
});
if ($.cookie('clicked-counter') == 'true') {
var cookie = $.cookie('clicked-counter');
$('#counter a').text('Count (' + cookie + ')');
};
#counter{background-color:white}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="counter">Counter</button>
Yup parseInt() shows NaN.
I updated your script to make it work (i included jQuery.cookie plugin for example) , look here http://jsfiddle.net/nicolapeluchetti/csTpG/100/ but there are still some issues. You get NaN when you do a parseInt because you are trying to parse an html page that returns from your ajax call. What are you trying to do?
Related
Hi I am working in grails ..
<g:link name="searchLink" controller="MRController"
action="ExcelExport">TEST GRAILS</g:link>
<script>
$(function() {
$('a[name="searchLink"]').bind('click', function() {
$(this).attr('href', $(this).attr('href') + '?startdate=' + start().StartDate +'&enddate=' + start().Enddate);
})
})
function start(){
var StartDate = $("#startDate").val();
var Enddate= $("#endDate").val();
return {StartDate:StartDate,Enddate:Enddate}
}
</script>
I have trying to get the following url
http://localhost:8077/Myproject/MRController/ExcelExport
?startdate=2017-05-21&enddate=2017-05-23
But when i click the link again i get the following url instead i want the link with new startdate and enddate value
http://localhost:8077/Myproject/MRController/ExcelExport?
startdate=2017-05-21&enddate=2017-05-23?startdate=2017-05-21&enddate=2017-05-23
Edited
I have tried with the following script to clear the parameters in the first call but i don't know how to make the script run one after another means first the url call work then the parameters will clear through the function
<script>
function refineUrl()
{
//get full url
var url = window.location.href;
//get url after/
var value = url.substring(url.lastIndexOf('/') + 1);
//get the part after before ?
value = value.split("?")[0];
return value;
}
</script>
Don't change the original href attribute in your JS-code:
$('a[name="searchLink"]').bind('click', function() {
document.location = $(this).attr('href') + '?startdate=' + start().StartDate +'&enddate=' + start().Enddate;
})
I've read and re-read every first-page Google result on JQuery/AJAX callbacks using every permutation of terms I can think of, and no re-write I've tried for the code below is successful.
I simply need to construct a callback for this function—which is part of a larger self-calling JQuery function—so that the 'message' variable holds the results of the integrity_check.php routine before proceding to the evaluation routine of 'message' at the end.
(Yes, this is yet another attempt to make JQuery synchronous, and I understand that callbacks are the answer, but I can't find it.) May success and happiness befall you if you can help me with this:
// If the integrity check passed, message will be empty.
// If the integrity check fails, message will hold text for an alert box.
var message;
$.get('integrity_check.php', { add_new_variable: $('#new_variable').val() }, function(data) {
if (data != 0) {
message = data;
}
});
[...some other code follows that may or may not set 'message' variable to a text message for alert box, so the following code must stand independently:]
if (message != '') {
alert(message);
} else {
[...proceed with using new_variable in HTML...]
}
UPDATE
The suggestion by Guest271314 pointed in the right direction, although I had to make modifications to make it work; see CAPS commentary in code solution that follows:
var request = $.get('integrity_check.php', { add_new_variable: $('#new_variable').val() }, function(data) {
if (data != 0) {
message = data;
}
return message;
});
// HERE I HAD TO SAVE THIS VALUE TO A NEW VARIABLE;
// $('#new_variable').val(); WAS NOT ACCESSIBLE OTHERWISE IN THE ROUTINE THAT FOLLOWED:
var nv = $('#new_variable').val();
// HERE IT WAS IRRELEVANT WHAT ARGUMENT WENT INTO function(),
// EXCEPT IT COULD *NOT* BE message; YOU HAD SUGGESTED msg, WHICH WAS IMMATERIAL, IT TURNED OUT
request.then(function() {
// HERE I *HAD* TO USE message, NOT THE GENERIC msg THAT YOU HAD PASSED INTO THE FUNCTION:
if (message != '') {
alert(message);
} else {
// THE ORIGINAL FORM HERE WOULDN'T WORK, AS $('#new_variable').val() WAS INACCESSIBLE IN THE FUNCTION:
//var newKeyword = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + $('#new_variable').val() + '" checked /> ' + $('#new_variable').val() + '</label>';
// THIS, HOWEVER, WORKED...USING nv IN PLACE OF $('#new_variable').val();
var newVariable = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + nv + '" checked /> ' + nv + '</label>';
$('#checkboxes').append(newVariable);
}
});
I'm grateful to guest271314 for what s/he posted, although I'm unclear on why I had to make the changes that I did in order for the code to work. Elucidation, anyone?
Try utilizing deferred.then()
// If the integrity check passed, message will be empty.
// If the integrity check fails, message will hold text for an alert box.
var message;
var request = $.get('integrity_check.php'
, { add_new_variable: $('#new_variable').val() }
, function(data) {
if (data != 0) {
message = data;
}
return message
});
/*
[...some other code follows that may or may not set 'message' variable to a text message for alert box, so the following code must stand independently:]
*/
request.then(function(msg) {
// `msg`: `message`
if (msg != '') {
alert(msg);
} else {
// [...proceed with using new_variable in HTML...]
}
// return msg
}, function err(jqxhr, textStaus, errorThrown) {
console.log(errorThrown)
});
I have a mobile app.
It consists of 2 screens. The first is for capturing user
credentials and the 2nd is for displaying data.
The idea is to collect the credentials on screen 1.
Then make an ajax call with the credentials to get data and present it on
screen 2 as a series of links.
Then allow the user to touch a link on screen 2. This will return the link data to the javascript and pass it to the ajax call and get more data - THEN delete all the data on screen 2 and repopulate it with the new data.
First thing I want to find out: is showing a page with mobile.changePage(), populating it, deleting the contents and then repopulating it (without another call to mobile.changePage()) a reasonable thing to do?
I'm having a problem and I think its related to how I'm using onclick in the <a>
Each time I display the most recently received data, I want to display it in an <a>. I write each onclick to call the getData routine passing it information to determine the next ajax AND whatever is being displayed in the <a>. The only way I could figure out to access that was in onclick.
Is there a better way?
I'm able to display the results of the first ajax call just fine. But things get weird with the 2nd, 3rd etc.
Sometimes I'll touch a link and I'll progress thru the screens as I expect.
Sometimes I'll touch an <a> on the 1st result screen, the 2nd result screen will display and then (without me selecting data from the 2nd screen) the 3rd screen will display.
I've looked at the logs and the getData() routine is being executed.
What could be causing this? Am I somehow not destroying all the <a> properly? Am I using onclick in a fashion its not designed for? Should I be using buttons styled to look like links instead of <a>
Here's my code:
"use strict";
var app = {
onDeviceReady: function() {
$('#startButton').click(function(){
app.getDeptsForUser();
});
},
getDeptsForUser: function(){
var parms = new Object();
parms.userName = assignedUser;
app.getData(JSON.stringify(parms),"ENDPOINT1", "Departments");
$.mobile.changePage("#index", { transition: 'slide' });
},
getData: function(paramStr, endpoint, displayHeader){
var paramStrObj = JSON.parse(paramStr);
var serverName = server + ":" + port;
var encoded = Base64().encode(paramStrObj.userName + ':' + pass);
var authType = 'Basic ' + encoded;
var option = endpoint+"?action=start¶ms=" + paramStr;
var URL = serverName + "/rest/bpm/wle/v1/service/"+option;
$.ajax({
url: URL,
type: "POST",
crossDomain: true,
jsonp: "callback",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", authType);
},
success: function (result) {
console.log("MobileMockUp getData() ajax success result="+JSON.stringify(result));
if (endpoint === "ENDPOINT1"){
app.displayData(paramStr, endpoint,"Departments", result.data.data.depts.items);
}
else if (endpoint === "ENDPOINT2"){
app.displayData(paramStr, endpoint,displayHeader, result.data.data.checklists.items);
}
else if (endpoint === "ENDPOINT3"){
app.displayData(paramStr, endpoint,displayHeader, result.data.data.checks.items);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Unable to retrieve '+displayHeader);
},
});
},
displayData: function(currParms,currEndPt, headerText, list){
var nextEndpt;
var nextHeaderText;
var currParmsObj = JSON.parse(currParms);
if (currEndPt === "MD#getDeptsForUser"){
nextEndpt = "MD#getCheckLists";
nextHeaderText = "Check Lists";
}
else if (currEndPt === "MD#getCheckLists"){
nextEndpt = "MD#getChecks";
}
var htmlListString="";
var parmObj;
var newLink;
$('#headerText').text(headerText);
for (var i = 0; i < list.length; i++){
parmObj = new Object();
if (currEndPt === "ENDPOINT1"){
parmObj.userName=currParmsObj.userName;
parmObj.dept=list[i];
}
else if (currEndPt === "ENDPOINT2"){
parmObj.userName=currParmsObj.userName;
parmObj.dept=currParmsObj.dept;
parmObj.checklist=list[i];
}
else if (currEndPt === "ENDPOINT3"){
nextHeaderText = list[i];
}
var str = JSON.stringify(parmObj);
str = str.toString().replace(/"/g, '\\"');
newLink = "<a style='background:#ffffff;padding-top:5%;border-top: thin solid black; display:block;font-size:12px;font-weight:normal;color:#000000;text-decoration: none;' href='#' onclick='app.getData(\""+str+"\",\""+nextEndpt+"\",\""+nextHeaderText+"\")'><pre>" + list[i] + " </pre></a><br>";
htmlListString=htmlListString+newLink;
}
$('#taskListUL').empty();
$('#taskListUL').append(htmlListString);
}
};
Could this be multiple binding?
i figured out it was multiple bindings
I have set up Bootstraps nav-tabs via an index page. Each tab loads a seperate PHP file via AJAX:
<div class="container">
<ul class="nav nav-tabs" id="indextabs">
<li>NOTES</li>
<li>WHOIS</li>
<li>DIG</li>
<li>ETS</li>
<li>RESOURCES</li>
</ul>
</div>
JavaScript that takes care of the AJAX queries:
window.onload = function() {
$('[data-toggle="tabchange"]').click(function(e) {
var $this = $(this),
loadurl = $this.attr('href'),
targ = $this.attr('data-target');
$.get(loadurl, function(data) {
$(targ).html(data);
});
$this.tab('show');
return false;
});
}
This itself works fine. In some of the tabs, however, there is an input that requires a domain name which then needs to be submitted via a GET request so that the URL can be something like:
http://domain.com/?domain=google.com&record=mx
With this in mind, I have two problems:
How do I load a particular tab using a GET method URL?
How do I submit form data via AJAX using the GET method and have it change the URL AND load the content in the tab-panel divs?
Please consider the following more like a comment because I'm uncertain what's optimal (and also works) in your case. Anyway I think you need to pass query parameters in your $get method call, either in form of a object, key value pairs { domain: 'google.com', record: 'mx'} or as string. Below an object/key value pairs are used.
window.onload = function() {
$('[data-toggle="tabchange"]').click(function(e) {
var $this = $(this),
loadurl = $this.attr('href'),
targ = $this.attr('data-target');
//optional method call below, uncomment if needed
//loadurl = getDomainURL() + "/" + loadurl
$.get(loadurl, {
domain: 'google.com',
record: 'mx'
},
function(data) {
$(targ).html(data);
});
$this.tab('show');
return false;
});
}
//returns domain name: www.example.com in form of http://example.com
// or domain name: http://example.com is returned as it is, unchanged http://example.com
function getDomainURL() {
var index = window.location.hostname.indexOf("www.");
if (index === 0)
return "http://" + window.location.hostname.substr((index + 4));
else
return "http://" + window.location.hostname;
}
This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/