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.
Related
Following is the exact scenario in my ASP.NET MVC application:
The parent page is having 3 tabs, and following javascript is written to bind click event to each of the tabs:
Each function invokes a controller action (specified in the data-url attribute), and renders the result in the partial view which is expected to be displayed within "ContactMainContainer" div.
jQuery(document).ready(function () {
$('#ContactTabs a').on('click', function () {
var dr = $(this).closest('li');
var url = $(this).attr("data-url");
if (url != undefined && url != '') {
var projectDetailTabModel = $("#ContactID").val();
$('#successDiv').hide();
$('#errorDiv').hide();
$.ajax({
type: "POST",
url: getUrlWithTabId(url),
data: projectDetailTabModel,
success: function (result) {
$('#ContactMainContainer').html(result);
},
error: function (errMessage) {
if (errMessage != null && errMessage.length > 0) {
$("#errorDiv").show();
$("#errorText").html(errMessage);
}
}
});
}
});
});
Contents of one of the partial view is built using javascripts (mostly ajax calls). (I am unable to put the whole javascript here as it is a client project and confidentiality agreement, and the javascript library is too large to place here).
The issue is that when a user navigates to that particular tab (having Ajax call), it takes a long time to execute and render the result. But after that if user clicks on any other tab the browser stucks and hangs for infinitely.
This issue is only in IE11, and works very well in all other browsers (Chrome, firefox, and all).
Could anyone please suggest what could be the reason?
It's a caching issue and IE is well known for caching. You need to make sure in your Ajax call to set the catching as false
Setting the cache property in an AJAX call
$.ajax(url, {
dataType: 'json',
cache : false,
//Other things ...
}
I prefer to use cache buster in the request URL, that is adding the current timestamp as parameter, so that it cant be cached
I've tried to search it through but not getting a starting point of how to approach AJAX in WordPress (or as a concept in whole), how is it different from jQuery, or is it a different/same module?
Why do we use it when we have jQuery (what circumstances forces us to use it?).
Should I learn jQuery basics first, then AJAX, or other way around?
You cannot really compare jQuery, AJAX and WordPress in this way:
jQuery is a JavaScript library designed to simplify the client-side scripting of HTML
AJAX is a technique to send data to, and retrieve data from, a server asynchronously
Wordpress is a blogging platform
To illustrate the point (with a very simple example), say you had a JavaScript event handler that was triggered when a form was submitted:
var f = document.getElementById("myForm");
f.onsubmit = doSomething;
You could have the event handler prevent the default submit action, instead making an AJAX request to a PHP script, optionally passing it some data (form values etc), then doing something with the response.
This has the advantage that the page is not refreshed, giving it a snappier, more responsive feel and generally making for a better user experience.
Here's how you'd implement it in plain JS:
var f = document.getElementById("myForm");
f.onsubmit = function(e){
e.preventDefault();
var r = new XMLHttpRequest();
r.open("POST", "submit.php", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
r.send("a=1&b=2&c=3");
}
Now, as mentioned, jQuery is a JavaScript library, that just adds a layer of syntactic sugar and smooths out browser incompatibilities.
The same code using jQuery:
var f = $("#myForm");
f.on("submit", function(e){
e.preventDefault();
$.ajax({
url: "submit.php",
type: "POST",
data: "a=1&b=2&c=3",
success: function(d) {
console.log(d);
}
});
});
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
I have a simple form which has only one textarea element.
We use this text area to pass JavaScript code and save it into a MySQL database using PHP.
It works fine with any text, but not with text which has the JavaScript
$(function(){
$("#hotbar").submit(function(){
$.ajax({type:'POST',
url: 'modules/hotbar.php',
data:$('#hotbar').serialize(),
beforesubmit : function() {
return $('#hotbar').validate().form();
},
success: function(response) {
$('#action').html(response);
}
});
return false ;
});
});
It works fine with any text only; when passing the JS code we want to save it does nothing and never lets the value pass to the PHP page
Hard to tell without more detail, but I'd start by checking if either the jQuery validation plugin or some form processing component on the server-side is removing the script tags to try and protect you from Cross-site Scripting (XSS) attacks.
How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php