Except the fact I am not able to use PHP. I have a single HTML file I can work with. So the only way is JS I think. And I have an "email" user input where the user sets his email and the n he is able to proceed, but I have to save his email first. Any ideas?
If you only need to save the element in a short term way you can use javascript and the HTML5 data element to save the email as an element of the current page. It is very temporary storage, but is the best you're going to get.
Edit:
Here's how you can do this using jQuery based javascript.
HTML:
<input type="text" id="email">
<input type="button" id="emailButton">
<div id="data_div"></div>
jQuery Javascript:
function retrieveEmail() {
var email = $('#data_div').data("email");
// do something with the email variable as needed here
// here's an example of retrieving it to send it to the server
var paramStr = "email=" + email;
$.ajax({
url: './your_server_file_here',
dataType: 'json',
data: paramStr,
success: function(data) {
callBack(data);
});
}
function callBack(data) {
// do something with information passed back from the server after you sent the data to the server (you didn't say you needed to do this, but here's where it should be done)
}
function storeEmail() {
var email = $('#email').val();
$('#data_div').data("email", email);
}
$(document).ready( function() {
$('#emailButton').click( function() {
storeEmail();
});
});
Edit: I know you already accepted this answer, but it struck me that HTML5 also includes another way to do this and it may provide the increase in power and flexibility that you're looking for. The HTML5 storage element can do pretty much the same thing as the data element except that it can persist and be accessed by other pages from the same domain either until the browser is closed (unlimited amount of data in the sessionStorage) or indefinitely (5mb of data in the localStorage). For implementation details and a greater understanding see here.
Be advised though, the HTML5 storage element is only available in HTML5 compatible browsers and should not be used if you fear your user base won't be using a modern browser. The HTML5 Data element will work even in older browsers, so it does have that advantage.
You could always use Javascript to create a text file where you can save information...
Related
I have a function called 'delete' like this :
<div onclick="delete($post_id, $_SESSION['id']">somelink</div>
function delete(post_id, session_id) {
var p_id = post_id;
var s_id = session_d;
$.ajax({
url:"delete.php",
type:"POST",
data: {
p_id: p_id,
s_id: s_id
},
});
})
delete.php is a page to delete the post = p_id which was added from user id = s_id.
My problem is any user can delete any post for only the console when typing in it the function 'delete();' with parameters it called and delete posts!
Any ideas, please.
You can not. Nor should you.
You should always assume that data from the client side is corrupted and should be treated accordingly. That includes form data, or in this case, a AJAX request.
This means that you have to apply validation at the server side, let PHP do it for you. E.g.: Limit the number of posts you can delete per X time. And double check that the post actually belongs to the person who is deleting it.
The reason you can't do this, is because you create javascript which is clientside. If you create a function to prevent changing the code, the client can alter the code on their machine to ignore that. You could make a function to check of the function to check is changed, but again; client can change it.
Unfortunately you can't. What you need to make sure though is making the function safe on the server which, in simple terms, boils down to
Validating every request and input parameters on the server so that people won't be able to manipulate or change server side data from client side.
make sure all data that you send to the client is originated from server as well.
one of the ways to prevent calling a function from client side is NOT to expose your methods in the global scope. and remember if your code is very critical and important, always move it to server-side. it is not a good practice to cover application design issues with programming workarounds. calling functions from client side shouldn't be an issue if the program is designed right.
First of all, this is bad. You should have authentication.
However, you can do that:
(function() {
$('#BUTTON_ID').on('click', function(post_id, session_id) {
var p_id = post_id;
var s_id = session_d;
$.ajax({
url:"delete.php",
type:"POST",
data: {
p_id: p_id,
s_id: s_id
},
});
})
})();
And add "BUTTON_ID" as id for your button.
Not that even that way, it is still not secure.
With this way, you can't call delete from the console. But someone can look into the source code and copy your ajax call and paste it into his console and it will works. It is not a good way to prevent people deleting your posts.
You should read about web application security. You should have an authentication process with tokens that expires after x time. Tokens will authenticate the user and from here, you can check if the user have the right to delete post. If the user do not have the right, you don't show the button. Then if the user call it from it console, he will get an error from the backend server.
I have a URL that I'd like to scrape a certain bit of information from and I'd preferably do that by obtaining the element. I'd also need to get it as plaintext, but I'm still pretty new to Ajax/jQuery and don't quite know what the correct syntax is..
My ajax call is:
$.ajax({
url: URL,
dataType: 'text',
success: function(data) {
var info = data; //How can I get a table from the data without loading the whole site extracting a small portion?
if(info != undefined) {
console.log(info); //Needs to be plaintext.
}
}
});
I hope my question is clear... I'm essentially loading a website and retrieving a table or class name as plaintext... How could I do that? Thanks.
Your options on the client-side are:
1.) First, optionally use a regular expression to isolate that tag contents, but this is usually considered rather costly.
2.) Create a node, then drop the text into it's innerHTML.
That's usually the standard way of rendering text responses to the DOM.
Neither one are all that lightweight.
If you just need to pick something out of the text, use Regular Expression. Also, as mentioned, be aware of XSS and cross-origin policy.
Additionally, you may want to handle this on the server-side.
I have a javascript array which stores seat numbers (in a cinema), which are selected by the user via clicking and added to the array each time using a function. I want the page to show the total cost of these seats, which means accessing an sql table inside some php.
So I have e.g. seatNumbers = ["a1", "d6", "e3"] and three sql query like 'select cost from seat where seat_number='a1';'. The function that adds to the array on clicking a seat and prints the seats is something like:
var seatArray = [];
function addSeat(seat) {
seatArray.push(seat);
document.getElementById("textarea").innerHTML="Seats : ";
for (x in arraytest) {
document.getElementById("textarea").innerHTML+=arraytest[x];
document.getElementById("textarea").innerHTML+=" ";
}
}
And I want to show the total cost in the HTML.
I'm wondering if what I'm trying to achieve is possible? What would be the general method and would I need to load a new page instead? And if it's not possible, what would be a better way to go about this?
Your question is very broad, and to answer it, quite some stuff needs to be known and used.
What you want is very possible though. In fact, there are technologies that in their core focus on providing solutions to problems like yours! What you need is some solid info (and possibly experience with) AJAX and maybe even REST. By using AJAX your page wont have to reload, and in your situation AJAX is probably the best choice anyway.
To point you in the right direction: AJAX javascript W3Schools Tutorial and PHP AJAX W3Schools tutorial
Then, use jQuery to make it all a LOT easier: jQuery (i'd go for 1.x)
You'll have to create an API that accepts an HTTP (preferably GET) request and returns the cost for the seat that you refer to in your URL like (more REST like, should return a whole seat object with price included): /seat/200, or (not REST like)/seat/cost/200).
Your choice if you want to follow (if you haven't read up on it, possibly confusing) REST rules. In your situation i'd just begin with some good old AJAX, it just works and is even better suited for stuff like this.
You should use AJAX. Try using jQuery library and ajax function.
Covert Your array with seats on JSON string and send it by AJAX to page which check the whole price. Then, You can update Your HTML code with total cost.
var json_data = '{...}';
$.ajax({
url: "total_cost.php",
dataType: "json",
type: 'POST',
data: { json: json_data },
success: function(response) {
// .. on success
var json_response = jQuery.parseJSON(response);
var cost = json_response.total_cost;
}
});
I have been tasked with using my skills with HTML/CSS/JavaScript/jQuery to solve a block of code according to these requirements:
Requirements:
- Use ajax via the add_user function to submit the user entered data.
- You can assume the service will respond with 200 status.
- Display an error in red at the top of the form when the add user service responds with success property with a value of false. Use the error property as the message.
- Display new users in the users list when the response returns a success property
- Highlight the email input when a user enters an invalid email address. Also, display the text "please enter a valid email address" in red.
NOTE: The service will not provide this validation functionality, and will accept invalid emails.
//example usage.
addUser('john', 'smith', function(response){
console.log('response is: ' + JSON.stringify(response));
});
/*
################################### DO NOT MODIFY BELOW THIS LINE ##########
############################################################################
*/
// Add user service wrapper.
function addUser(username, email, callback) {
var response;
if(username === "Error"){
response = JSON.stringify({
success: false,
error: "Error is not acceptable username."
});
} else {
response = JSON.stringify({
success: true,
user: {
username: username,
email: email
}
});
}
$.ajax({
url: '/echo/json/',
type: "post",
data: {
json: response
},
success: callback
});
};
The following HTML applies:
<h2>Add a User:</h2>
<form>
<input type="text" name="username" placeholder="name">
<input type="email" name="email" placeholder="email">
<button>add user</button>
</form>
<h2>Users:</h2>
<ul id="users"></ul>
CSS:
body {
font-family: Helvetica, Sans, Arial;
}
p, ul {
padding: 10px;
}
ul {
margin: 5px;
border: 2px dashed #999;
}
OK, hopefully you're still with me. I have a strong understanding of Object-Oriented JavaScript, as well as jQuery, HTML, and CSS. However, I have very little experience with AJAX, and none with JSON syntax/application. Therefore, some aspects of this project seem very straightforward to me, and I do not believe I need assistance in figuring them out. The things I already know how to do properly include:
Displaying an error in red above the form (retrieving the error information is a different story)
Displaying new users in the unordered list section
Highlight the email input when an invalid email address is entered (using client-side validation)
The issues I am having in understanding this project focus on submitting and retrieving the data that is entered in the form. It appears as though the function addUser() first defines the variable response with a 'String' data type version of an 'Object' that contains key:value pairs of 'success: boolean, error: string' or 'success: boolean, user: {username:string,email:string}' - Here is where I run into my first area of trouble...
If the objects containing those key:value pairs are to be relied on for determining whether or not an error has occurred during validation, and to retrieve data such as error messages and strings associated with the username and email, it would make sense to keep them as actual objects, rather than 'stringified' objects. As strings, I do not know how to access the value of a property of that object. If they were objects, I could simply refer to them using dot notation and retrieve their properties' values. (i.e. sampleObj.success or sampleObj.error) It seems as though JavaScript functions such as eval() and JSON.parse() would suffice to return these strings into proper objects, but I have no idea how to implement those functions properly.
The second major issues I am experiencing relates to the jQuery call of the .ajax() method. I have a very rudimentary understanding of how AJAX operates, but the syntax used here confuses me. I understand that the data: {json:response} is being sent to the url:'/echo/json/' using the type:'post', but I do not understand how that data can be retrieved after this has taken place. I also do not understand what the value of 'response' is referring to in that process.
Finally, I do not understand the use of a callback function at the end of the $.ajax() statement, and how it relates to the initial call of the addUser() function as a result of clicking the form button input. I do not understand its purpose, or how it would be used syntactically.
I understand this is a fairly complicated project, and I may be asking a lot. But I have spent many hours over several days trying to make sense of this using my own knowledge and existing online resources, but have not gotten very far despite my diligence. I hope someone can assist me in understanding this example.
A link to a live version of this project (jsfiddle.net)
//EDIT// An updated link to the jsfiddle workflow, with correct jQuery selectors and additional functionality for displaying error messages / user input: http://jsfiddle.net/brianjsullivan/5vv5w/
The problem is that you forget the # (id) in your code:
JSFIDDLE
$(document).ready(function(){
$('#button').click(function(){
$userInput = $('#username').val();
$emailInput = $('#email').val();
addUser($userInput,$emailInput,function(response){
$('#users').html(JSON.stringify(response));
});
});
});
The JSON/string issue is a matter of a little experimentation/familiarity with JSON and JSON objects, but requires tons of explanation in lieu of a little testing, so I will focus on parts 2 and 3 of your question. Perhaps someone else is better able than I to address the first part.
An AJAX code block (1) Defines some variables with values, (2) Transmits them to a server-side script for processing, (3) Receives a response from the server.
The "old" construction (we now use the Promises interface) is the easiest way to envision how AJAX works:
$.ajax({
type: "POST",
url: "pagename.php",
data: "varName=" +varValue+ "&nextVarName=" + nextVarValue,
success: function(returned_data) {
//Var returned_data is ONLY available inside this fn!
alert("Server said: " + returned_data);
}
});
On the server side (using PHP for this example):
<?php
$one = $_POST['varName']; //$one contains varValue
$two = $_POST['nextVarName']; //$one contains nextVarValue
//Do something with the received data, for eg a MySQL lookup
$result = mysql_result(mysql_query(some lookup),0);
$out = '<h1>Server says:</h1>';
$out .='<p>For the purpose of this test, the server sends back:</p>';
$out .= $result;
echo $out; //NOTE: uses echo, not return
Whatever the server side sends to the browser is received as the contents of the variable we have named returned_data.
Note that we must deal with that variable ONLY inside the success function. If we need access to it later on, we can either save the contents into global vars, or inject the data into a hidden DOM element, or ...
These days, though, you want to use the promises interface -- which essentially does the same stuff, but not as clear for the purpose of explanation in an SO post. See below:
Sources:
Kevin Chisholm on jQuery Promise Interface
jQuery 4 U
Daniel Demmel on Promises
José F. Romaniello
Change your code to
$(document).ready(function(){
$('#button').click(function(){
$userInput = $('#username').val();
$emailInput = $('#email').val();
addUser($userInput,$emailInput,function(response){
$('#users').html(JSON.stringify(response));
});
});
});
Here is Fiddle.
I am developing a web application and am using jQuery to provide a good user interface for users. Therefore, I am using ajax requests and many jQuery functions.
If I disable JavaScript in the browser most of the function will not work because I am sending asynchronous ajax requests for many functions. But how can I handle this? Do I need to rewrite the code without using jQuery and ajax?
Find a below a sample button click event:
$("#renameCategory").live('click', function (event) {
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: '#Url.Action("UpdateCategoryName", "Category")',
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
How can I handle this?
Ajax requests and jQuery will not work when the client has JavaScript disabled. The best way to make this work is to use the URL from the <a> tag href like so:
Click Me!
$("#renameCategory").on('click', function (evt) {
//To prevent the link from sending the default request
//call preventDefault() on the jQuery event object
evt.preventDefault();
//
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
//GET THE URL FOR THE AJAX REQUEST
var actionUrl = $(this).attr('href');
//
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: actionUrl,
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
You will also need to check for ajax requests in your Controller like below:
public ActionResult UpdateCategoryName() {
...
if(Request.IsAjaxRequest()) {
return Json(yourData);
}
return View();
}
This way, if your user has JavaScript disabled, the link will function like a normal HTTP request. If the user has JavaScript enabled, then they will get the Ajax experience. This is called graceful degradation.
Ajax call works when javascript is enabled.
You can handle it by server-side scripting, when javascript is disabled, you must do works by post/get requests, so you have to recode your web application.
If a lot of modification is needed for your website to work without javascript, then just force the users to enable javascript. One way to notify users to enable javascript is to use the noscript tag. http://www.w3schools.com/tags/tag_noscript.asp
View stackoverflow's page source to see how they use noscript
If JavaScript is disabled in the browser, the <script> tags won't be interpreted and executed in your document, including all your jQuery and AJAX JS code. The most common way to implement interactive web application other than Javascript is Flash, so you can still have a backup plan. You can also go with the old-school server side only generated dynamic pages.
Today, however it is very rare for someone not to have JavaScript enabled, so it should not be an issue at all.
Anyway you can make use of the <noscript> html tag to display a message to these users.
<script type="text/javascript">
... Js code ...
</script>
<noscript>You have JavaScript disabled in your browser. Please enable it.</noscript>
Obviously any functionality depending on script will not work if scripting is disabled, not available or incompatible with the environment it is trying to run in.
It is considered by many to be a good strategy to develop web applications so that they work without script support. You can then add scripting to improve the workflow and efficiency, but you will do so knowing that you have a fall back to a working system available if at any point the script should not run.
The discipline of designing and implementing a good workflow based on just HTML and forms may well lead to an easier interface to script and a more efficient workflow.
All too often developers throw together some minimal HTML and CSS, then try and do everything in script. The extreme is to have a DOCTYPE, title element, one block element and one script element that does everything. Not recommended.