onClick a font awesome icon, run PHP without Ajax? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Okay right, Ajax. But is there any other solution besides ajax. You cannot really make a font-awesome icon a button or can you? If you have no clue what I am talking about when I mean a font-awesome icon this is what I mean:
<i id="like1" onClick="like(this);" class="fa fa-thumbs-o-up">5</i>
So back on topic. I want to make it as soon as you click on this icon it runs a php script which adds a +1 to a text file, but how would you run that without using ajax and without refreshing the page. The site I am working on is a random youtube video site where people will be able to rate videos. I want to save when someone clicks the thumbs up button but I cannot refresh the page or else it goes to another random video. Now you see my issue. However if it is not possible to do without ajax then please explain the ajax solution, I do not have enough experience with ajax to do it on my own. Heres some code that I've already done.
JS:
<script>
function like(obj) {
if (obj.style.color === "green") {
// set obj color to something other than green
obj.style.color = "white";
// get the innerText for the object that was clicked, parse as int, decrement by 1
obj.innerText = parseInt(obj.innerText) - 1;
}
else {
// we are incrementing, so check the dislike and decrement if necessary
var dislike = document.getElementById("dislike1");
if (dislike.style.color === 'red') {
dislike.style.color = 'white';
dislike.innerText = parseInt(dislike.innerText) - 1;
}
// set the colour of the object that was clicked
obj.style.color = "green";
// get the innerText for the object that was clicked, parse as int, and increment by 1
obj.innerText = parseInt(obj.innerText) + 1;
}
}
</script>
<script>
function dislike(obj) {
if (obj.style.color === "red") {
// set obj color to something other than green
obj.style.color = "white";
// get the innerText for the object that was clicked, parse as int, decrement by 1
obj.innerText = parseInt(obj.innerText) - 1;
}
else {
// we are incrementing, so check the dislike and decrement if necessary
var like = document.getElementById("like1");
if (like.style.color === 'green') {
like.style.color = 'white';
like.innerText = parseInt(like.innerText) - 1;
}
// set the colour of the object that was clicked
obj.style.color = "red";
// get the innerText for the object that was clicked, parse as int, and increment by 1
obj.innerText = parseInt(obj.innerText) + 1;
}
}
</script>
Dislike & like buttons:
<strong><i id="like1" onClick="like(this);" class="fa fa-thumbs-o-up">5</i>
<i id="dislike1" onClick="dislike(this);" class="fa fa-thumbs-o-down">1</i> <br/></strong>
EDIT:
Is this correct?
<script>
function like(obj) {
var jqxhr = $.ajax(
type: "POST",
url: "liketest.php", //Name of your current file name
data: shareline //Here pass some parameters. Detect it in your php file before proceeding furthur. These parameters are available in post global variable when you send an ajax call.
)
.done(function(msg ) {
echo "Ajax seems fine";
})
.fail(function() {
echo "Failed";
})
});
if (obj.style.color === "green") {
// set obj color to something other than green
obj.style.color = "white";
// get the innerText for the object that was clicked, parse as int, decrement by 1
obj.innerText = parseInt(obj.innerText) - 1;
}
else {
// we are incrementing, so check the dislike and decrement if necessary
var dislike = document.getElementById("dislike1");
if (dislike.style.color === 'red') {
dislike.style.color = 'white';
dislike.innerText = parseInt(dislike.innerText) - 1;
}
// set the colour of the object that was clicked
obj.style.color = "green";
// get the innerText for the object that was clicked, parse as int, and increment by 1
obj.innerText = parseInt(obj.innerText) + 1;
}
}
</script>

No you can not execute any php script on client computer. PHP is a server side scripting language and its only executable on server side. You have to use ajax function if you don't want to refresh the page.
Use jQuery ajax function to save values in your text file.
You can get more help about ajax function on following website. Following is the syntax for jquery.
var jqxhr = $.ajax(
type: "POST",
url: "pageFileName.php", //Name of your current file name
data: data //Here pass some parameters. Detect it in your php file before proceeding furthur. These parameters are available in post global variable when you send an ajax call.
)
.done(function(msg ) {
// Here you will put the code which will execute after successful ajax call. msg variable contain data which is received from your php script file.
})
.fail(function() {
// Code if ajax call fail
})
});

I have not tried it myself (except in nodejs with Socket.io) but if you don't want to use an ajax call, for some reason, you could maybe try WebSockets.
Short presentation here: MDN WebSockets API

Related

How to keep the current view after refreshing the page

Hello I have made this js code to change the view from List to Grid and the opposite as well but I want to keep the current view state after refreshing the page, I have seen many videos talking about cookie and localStorage but I don't know how to use them since I am still beginner in programming could you tell me how to do ?
script.js:
let x = document.getElementById('x');
let z = document.getElementById('z');
x.addEventListener('click', function() {
let className = z.className;
if (className == 'list') {
z.className = 'grid';
}else{
z.className = 'list';
}
});
index.php:
<i class="" id="x"></i>
<div class="list" id="z">
.
centent
.
</div>
You can:
load the stored class from localStorage
see whether it's valid and different from the current class
store its current value upon each click
let x = document.getElementById('x');
let z = document.getElementById('z');
let cl = localStorage.getItem("class");
if (cl !== z.className) z.className = cl;
x.addEventListener('click', function() {
let className = z.className;
if (className == 'list') {
z.className = 'grid';
}else{
z.className = 'list';
}
localStorage.setItem("class", z.className);
});
Since stackoverflow.com considers direct operation with localStorage to be unsafe, I had to create a Fiddle for proof-of-concept. See here: https://jsfiddle.net/q68vnctL/
You can test by running it, clicking the "Click Me!" button as many times as you like, click on "Run" again and see that the color remains whatever it was.
localstorage is used as key-value pairs, both being always strings.
you can use localStorage.setItem('view-setting', 'list').
this will create a localstorage variable named view-setting and will define its value as list. You can fetch the data using localStorage.getItem('view-setting'). Similarly items can be deleted using localStorage.removeItem('view-setting').
So after setting the view in localStorage, you can fetch it and on reload check its last stage and add conditionals in HTTP accordingly.
You can get further help from:
Loading JS LocalStorage into PHP Variable
or
https://www.w3schools.com/html/html5_webstorage.asp

Assigning string to div value from javascript function across pages

I have a web app that outputs the results of a function as a double. The function compares two text documents and returns the percentage indicating the percentage of similarity between the two documents. When the user clicks a Compare button, the function runs and takes the user from the compare.jsp page to the results.jsp page, and displays a loading-bar that is filled in like so:
<div id="levenshtein-distance"
class="ldBar label-center levenshtein-distance"
data-preset="fan"
data-value="${result.percentage}"
data-stroke="">
</div>
This works fine, the fan bar gets the correct percentage. However, I am also trying to color the fan bar using the data-stroke value based on this percentage. I have a simple javascript function to do this, but can't figure out how to pass the value. I've tried running the function in the body tag of the results.jsp page using "onload", but this doesn't work. Here is my JavaScript function:
function barSetLD(percent) {
var red = "red";
var green = "green";
var orange = "orange";
var elem = document.getElementById("levenshtein-distance");
if (percent <= 40.00) {
elem.setAttribute("data-stroke", green);
} else if (percent > 40.00 && percent <= 70.00) {
elem.setAttribute("data-stroke", orange);
} else {
elem.setAttribute("data-stroke", red);
}
}
I've done quite a bit of searching and can't seem to find an example that helped me solve this. Any help is very much appreciated.
////Update:
Trinh, that worked to change the color, thanks! My problem now is that I do, in fact, have multiple 'levenshtein-distance' ids and I am looping through them. So currently everything is being set to the same color. I should have mentioned this initially, sorry. I am comparing multiple pairs of files and outputting the loading-bar for each pair. If you have some idea about how to resolve the looping issue, that would be great, but thanks for the original solution either way! I updated my javascript function as follows:
function barSetLD(percent) {
var red = "red";
var green = "green";
var orange = "orange";
var elem = document.querySelectorAll("[id^=levenshtein-distance]");
for (var i in elem) {
if (percent <= 40.00) {
elem[i].setAttribute("data-stroke", green);
} else if (percent > 40.00 && percent <= 70.00) {
elem[i].setAttribute("data-stroke", orange);
} else {
elem[i].setAttribute("data-stroke", red);
}
}
}
And the full bit of code with the html loop is, and I am now calling the barSetLD(percent) at the very bottom of the page as you suggested:
<c:forEach items="${studentResults}" var="result" varStatus="loop">
<div id="levenshtein-distance"
class="ldBar label-center levenshtein-distance"
data-preset="fan"
data-value="${result.percentage}">
</div>
</c:forEach>
<script type="text/javascript">
barSetLD("${result.percentage}");
</script>
Put your code at the very bottom of the page where all DOM has been loaded. Or at least make sure <div id="levenshtein-distance"/> exist and fully loaded before calling this document.getElementById("levenshtein-distance");. Also double check if you have multiple levenshtein-distance id...

AJAX based search returning page information

I found the source of the error but do not know how to fix it. I'm using codeigniter and I'm trying to make a textbox with search results showing under it to help the user find what they are looking for. Think similar to google's search. When I make the AJAX call, it's returning everything on the webpage as well as the search results.
Example of issue: https://gyazo.com/244ae8f3835233a2690512cebd65876d
That textbox within the div should not be there as well as the white space. Using inspect element I realized the white spaces are my links to my CSS and JS pages. Then there's the textbox which is from my view.
I believe the issue lies within my JS.
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
}
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = encodeURI(document.getElementById('txtSearch').value);
searchReq.open("GET", '?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('txtSearch').value = value;
document.getElementById('search_suggest').innerHTML = '';
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var ss = document.getElementById('search_suggest');
ss.innerHTML = '';
var str = searchReq.responseText.split("\n");
for (i = 0; i < str.length - 1; i++) {
var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
}
}
}
More specifically the getXmlHttpRequestObject function. it is returning the entire page including my header and footer. I don't believe any more info is needed but if anyone feels that way, I'll supply the view and controller.
https://gyazo.com/d0c43326191a4b09cc4b1d85d67a1bf6
This image shows the console and how the response and response text are the entire page instead of just the results.
Your call to the view method is loading the header view, the suggest view and the footer view while your suggest model is echoing the data that you're after.
You could just remove the line $this->view("suggest"); and your suggestions will be echoed.
This isn't great though. I would pass the titles back to the controller from the model then create a new controller method that outputs the data in a structured way (probably JSON).

Inserting button with function? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here is my code:
function ayee() {
confirm("Ready to play?");
var age = prompt("How old are you?"),
replacement = document.getElementById('container'),
message;
if (age >= 18) {
message = "Let's get started!" ;
} else {
message = "You're under 18? Be careful out there....";
}
replacement.innerHTML = message ;
}
What I want to do is in the return if age is greater then 18, add a button along with the message(or containing the message) that on click will send into the next function.
PS: this is for a choose your own adventure game.
try this
replacement.innerHTML = message+"<button>Next</button>"
var s = replacement.getElementsByTagName("button")[0];
s.addEventListener("click",function() {alert("next");}) // change the function to
// suit your needs
The idea is innerHTML creates the DOM. You can then use normal JavaScript function getElementsByTagName to get the button inside your replacement
Then add an event listener on the click of the button using addEventListener
This will work only on modern browsers. To make it work in IE prior to IE9 please add the following code. See the following link for more details
if(s.addEventListener)
s.addEventListener("click",myFunction);
else if (s.attachEvent)
s.attachEvent("click", myFunction);
fiddle
Write your function with some param
function myfunction(message){
//do something with message
}
and change message = "Let's get started!" ; to myfunction('Let's get started!')
Do something like this:
var btn = document.createElement("button");
btn.value = "Begin";
if (age >= 18) {
btn.addEventListener("click", function() {
eighteen();
});
}
else {
btn.addEventListener("click", function() {
notEighteen();
});
}
container.appendChild(btn):
You could also call one generic function that checks the age and runs two different sections of code instead of adding event listeners for two different functions.
Just a note: when you declare a variable, you should place "var" behind it. (var a = "test";.)
attach a button, alongside your html to be displayed, and add a click handler to the button with the function you want to trigger when the button is clicked, for example a simple code can be like:
function ayee() {
confirm("Ready to play?");
var age = prompt("How old are you?"),
replacement = document.getElementById('container'),
message;
if (age >= 18) {
//create a button
var btn = "<input type='button' name='test' onclick='checkThis();' value='Click'>";
//add the button to the message
message = "Let's get started!" + btn ;
} else {
message = "You're under 18? Be careful out there....";
}
replacement.innerHTML = message ;
}
function checkThis() {
alert("Clicked the button");
}

Javascript to build mvc actionlink conditionally

This is in a VB.NET MVC 3 Razor view and fires when a JsonResult of success is returned. The problem is that I would like to conditionally build an actionlink if data.Object.Status == 'Completed';
I have looked around and nothing seems to be fitting at all to solve this. This is what the actionlink should look like in razor:
#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = currentItem.firstName, .lastname = currentItem.lastName, .classRef = currentItem.course_ref, .cNumber = currentItem.conf_number}, Nothing)
And this is the javascript function that will do it. Currently it just Places the contents of data.Object.Status. Which should only show like that when data.Object.Status != 'Completed';
function updateSuccess(data) {
if (data.Success == true) {
//we update the table's info
var parent = linkObj.closest("tr");
parent.find(".CompletedClass").html(data.Object.Status);
//now we can close the dialog
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Update Complete");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").html(data.ErrorMessage);
$("#update-message").show();
}
}
Below is what I am thinking will work I am still trying to figure it out but this is a rough markup of it.
function updateSuccess(data) {
if (data.Success == true) {
//we update the table's info
var parent = linkObj.closest("tr");
var d = parent.find(".CompletedClass");
if (data.Object.Status == 'Completed') {
d.html = #Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = Model(0).firstName, .lastname = Model(0).lastName, .classRef = Model(0).Completed_Class, .cNumber = Model(0).conf_number}, Nothing)
}
//now we can close the dialog
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Update Complete");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").html(data.ErrorMessage);
$("#update-message").show();
}
}
What you suggest right now should work, there is a typo on your code assigning the HTML, you probably know it but the way you add HTML to an element is (You have a = sign which is not valid) :
d.html (#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", ....)
Assuming is an element that accepts html, otherwise, use the "text" function.
In any case, my recommendation would be to generate the HTML before hand but have it hidden on the page (unless you have thousands of them, of there are security concerns). Then you just have your Javascript simply show the element:
var parent = linkObj.closest("tr");
var linkElement = parent.find(".mylinkelement-class");
if (data.Object.Status == 'Completed') {
linkElement.show();
}
This should give you the benefit of allowing better separation between your Javascript and your MVC code.
HTH,
-Covo
You should update your code to something like this
d.html('#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = Model(0).firstName, .lastname = Model(0).lastName, .classRef = Model(0).Completed_Class, .cNumber = Model(0).conf_number}, Nothing)');
To assign html with jQuery you should use jQuery.html().
The Razor #Html.ActionLink will print HTML to the page, to not break your Javascript, put those inside quotes d.html('#Html...')

Categories

Resources