Ajax and jQuery - javascript

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);
}
});
});

Related

Detect website form agnostic submissions in JS (widget)

I'm working on a small proof of concept. The goal is to produce a small javascript widget that clients would be able to drop into their site. This widget should detect all forms on the page (think name, email phone, etc) and post any submissions to our API before returning control to the form.
I've searched a bit to see if patterns or libraries exist for this and did not come up with many results (if anyone has some to share, thank you)
Considerations:
Won't know what other libraries are running on the site
Won't know if the page has 1 form or 100 forms
Won't know if the form submits with a simple action tag or something more complex
Do want to be as lightweight (vanilla) as possible
The approach that I've been working out so far does something like the following. However, a lot of forms tend to prevent the submit event for their own validation or method of submissions. Is there a better way to do this that would handle a wider set of use-cases?
window.onload = function() {
for(var i=0; i<document.forms.length; i++){
var form = document.forms[i];
form.addEventListener("submit", (e) => { // Hook, but not all forms will use this
e.preventDefault();
const formData = new FormData(form)
console.log(formData.entries()) // Submitted data
fetch('//some-api-url/', {
method: 'POST',
headers: {'Content-Type': 'application/json',},
body: JSON.stringify(formData.entries()),
}); // Send the data to our backend
return true; // Return control back to the original form
});
}
}

How to allow page refresh/redirect after Ajax POST submission (of Django form)

I'm a client-side newbie learning the ropes, and need to clarify Ajax concepts.
e.preventDefault(); is a typical method of preventing form submission (page refresh) in JS.
One use case where the above is handy is Ajax-based form submission. Sample code is:
function overwrite_default_submit(e) {
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("reply", text_field.value);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
xhr.send(form_data);
}
I have two questions:
1) Imagine the POST request is being sent to a function that ends with a redirect to a different URL. For example, I use Django to develop web applications; a typical Django view may end up with return redirect("home") where home is the home page of the said app. In such a scenario, how does preventDefault() prevent the redirect statement in server-side code from executing? I'm trying to understand the exact mechanics behind it.
2) What if one wanted page refresh (or redirect) to proceed normally after an Ajax POST request? What tweaks need to be made? Would love to see an illustrative example to clarify my concepts.
I'm well-versed in Django (Python) so in case you need to show server-side code, Django would be a good example.
Note: prefer to stick to pure JS for this, since I'm learning JS these days. JQuery's on my radar, but only after I've mastered the fundamentals of JS.
The preventDefault() cancels the event, Default action that event of element will not occur. This will simply halt further execution of javascript code after that statement.
For i.e.
- Clicking on a submit button, prevent it from submitting a form.
- Clicking on a link, prevent the link from following the given
URL
To redirect to the next page or to add notification or may be to add html through javascript, but here is to redirect only.
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) //Here we need to check OK response and last state of ajax call.
{
window.location.href = 'REDIRECT_URL'
window.location.reload() // To refresh page.
}
};
=== I've added that in your function ===
function overwrite_default_submit(e)
{
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("reply", text_field.value);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) //Here we need to check OK response and last state of ajax call.
{
window.location.href = 'REDIRECT_URL'
window.location.reload() // To refresh page.
}
};
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(form_data);
}
Now in case of Django you need also need to add view / call proper action that should return either json or xml.
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
To know how ajax work you can check here https://www.w3schools.com/xml/ajax_intro.asp
1) Ajax request should not receive redirect response. Usually it supposed to be a valid json-string. Django has a JsonResponse for this purpose. If you want your django view to process ajax data you should check it on your backend side, for example:
if request.is_ajax():
return JsonResponse({'data': data})
2) You can do redirect with your javascript code, for instance:
window.location.href = 'https://stackoverflow.com'

Not sure how to use AJAX

I'm very new at this. I've read books to learn javascript and HTML, so unfortunately I haven't learn much about this.
I never used AJAX before, so not sure how it works, searched online, but find all examples too complicated.
Basically what I want to do is save a playlist (although not with cookies). Something everyone can see and add-on to it (similarly to a comments section).
This is just an example, I'm doing something else, but the html + js would be a bit big. Just want to know how I would do it on this, so that I could understand it (hopefully) and apply it elsewhere.
This would be the body and below it the code I have (currently all my code is in [head]):
<body>
<form>
<input type="text" id="songInput" size="40" placeholder="Song Name">
<img id="addButton" src="button.png">
</form>
<ul id="playlist"></ul>
</body>
<script>
window.onload = load;
function load() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
function buttonClick() {
var text = document.getElementById("songInput");
var song = text.value;
var button = document.getElementById("addButton");
var add = document.createElement("li");
add.innerHTML = song;
var ul = document.getElementById("playlist");
ul.appendChild(add);
}
</script>
First you have to understand what AJAX is. AJAX is not a "tool" that you can use, instead, it's a name for the techniques (asynchronous JavaScript + XML). Basically it means "getting/posting data from/to server."
In vallina JavaScript, XMLHttpRequest lets you send and receive data to and from a server:
var xhr = new XMLHttpRequest(); //Create an XMLHttpRequest object
xhr.open('get', url); //Set the type and URL
xhr.onreadystatechange = function(){ //Tell it what to do with the data when state
// changes
if(xhr.readyState === 4){ //4 is the code for "finished"
if(xhr.status === 200){ //Code 200 means "OK"
//success
var data = xhr.responseText; //Your data
}else{
//error //Deal with errors here
}
}
};
xhr.send(null); //After finished setting everything, send the
// request. null here means we are not send-
// ing anything to the server
It might look complicated, and xhr is repeated quite a lot. Not to mention the problems that we have to deal with when executing in IE.
There is solution for that. We will use libraries to simplify the process and let it do the hard works for us.
In jQuery, this is what you have to do to for a basic XMLHttpRequest:
$.ajax({
url: url,
data: { /*data here*/ },
type: /*"GET" or "POST"*/
}).done(function(data){
//success
}).fail(function(){
//error
});
//Not complicated at all with jQuery
Since AJAX is a group of techniques to send/receive data, there're more ways to do the "same" thing. You might realize the code above only works for URL that has the same domain (pages on your server). To bypass that limitation, there's another technique called JSONP. Sounds fancy, but what it means is simply "using the <script> tag to get pass that limitation". And of course, jQuery got you covered:
$.ajax({
url: url,
data: { /*data here*/ },
type: /*"GET" or "POST"*/,
dataType: "JSONP" //specifying dataType to be JSONP
}).done(function(data){
//success
});
Here is a simple example of getting content off Wikipedia using JSONP: http://jsfiddle.net/DerekL/dp8vtjvt/
With a normal XMLHttpRequest call to Wikipedia's server would not work. However by exploiting the fact that script tags are not restricted by the Same-Origin Policy we can achieve the same thing. Note that for JSONP to work, the server must be programmed internally to allow returning a JSON with wrapped callback call.

JavaScript to make some calculations and pass data to PHP

This is what I want to do:
When a HTML form is submitted, the form data is passed to JavaScript to do some calculations, then the form data along with the results (of JavaScript calculations) are passed to PHP to save data to the database.
Now, I know how to pass form data to JavaScript (or) PHP alone. But how to pass the data to both of them at the same time? And how to pass JavaScript data to PHP?
Also, am I going about it the wrong way?
1. Make calculations in Server Side:
"I wish to use client side for the maximum possible effect to reduce server costs" is not the best reason for doing so, if the calculations are not O(4^n), you should go ahead with doing this in the server side.
$myvariable = $_POST['numbers']; //I will skip sanitize
SomeCalculations($myvariable); //Making the calculations
2. If you really want to use Javascript:
If you really want to use javascript (I will use Jquery for simplicity) for learning or because you really think that is necessary in this case, then you can get the form data before submit and doing the calculations:
2.1 Submit the form like a normal form after make the calculations:
$('form').submit(function(e){
e.preventDefault()
var $this = $(this)
var formData = $this.serialize()
// do some calculations
var yourData = makeCalculations(formData);
$(this).submit();
});
2.2 Submit the form via Ajax (recommended since you are already using Javascript)
$('form').submit(function(e){
e.preventDefault()
var $this = $(this)
var formData = $this.serialize()
// do some calculations
$.ajax({
type: "POST",
url: "http://nakolesah.ru/",
data: makeCalculations(formData),
success: function(msg){
//This is returned in the server side
alert('wow'+msg);
}
});
});
Why not just do the needed calculations on PHP end? It's much easier and saves you headache making sure the data isn't tampered with, etc. The data is being passed there already.
Anyway - You'd either need to have javascript monitor the form and run the calculations as the user completes it. You can:
store those values in other (hidden?) form fields, which then get passed to php
use php to do the same calcs (not recommended)
cancel the form send action and send the data via ajax
You can use AJAX method for your stuff. $.ajax() or $.post() and etc. you can use any one of the method for your use.
Ref: http://api.jquery.com/jQuery.ajax/
Ref - POST: http://api.jquery.com/jQuery.post/
Since you wish to pass data to both PHP and JavaScript at the same time, I can think of only one method. It's not really simultaneous but it's very close to it.
So, let us say that you have this form #myAwesomeForm.
Write a JavaScript like this (assuming you are using jQuery $.post):
$( '#myAwesomeForm' ).submit( function( e ) {
var result = someAwesomeFunction() // this will do your calculation and return it
$.post(
'someAwesomePHPScript.php',
{
formData: $( this ).serialize(),
calculatedData: result
}, function( data ) {
// some more awesome stuff happens here
}
);
});
If you want to pass the data without changing the page, then use AJAX.
http://www.w3schools.com/ajax/
Otherwise use window.location("someFile.php?var1=xyz&...");

Do ajax requests works if JavaScript is disabled in the browser?

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.

Categories

Resources