Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Moving To Javascript Development

Over the last couple of years there's been a growing trend in web development, this is the moving away from traditional back-end development and more to front-end development using Javascript.
This has been helped by the increase of nodeJS in web applications allowing Javascript to slowly but surely take over the world.
For many years PHP has been the leading web language, whether you like it or not it's market share has always won out for many years. This has now been overtaken by Javascript and it's easy to see why.
It moves away from the traditional web development approach of having to hire
  • Frontend developer - Traditionally just converted PSDs to HTML and CSS
  • Backend developer - PHP, Ruby, ASP.net who will code up the linking of the front-end to server
  • Devops developers - To handle the server construction
  • Mobile developers - Creating the ios and android apps
  • Desktop application developers
In the current day Javascript developers can handle all these areas of development. Frontend development is no longer just processing HTML and CSS you can build the entire product in Javascript. It's used to handle events on your frontend, Javascript then becomes the API to process the data storing in JSON, NodeJS is now your web server and using something like React Native you can create native mobile apps in Javascript.
Now companies no longer have to hire 4 specialist developer positions as these can all be done by a Javascript developer. This shift from hiring 4 specialist developers to hiring 4 Javascript developers will not only massively improve the process of development but the speed of development too. No longer does each stage have to wait for a dependency from another developer in a different section of the app, each developer can cover all areas of the application.
You can see if you're a Javascript developer you have some good years coming to you.
I've been a PHP developer for many years and I can see the direction that the web is heading to be more Javascript development and away from traditional development processes.
So it's time to change my development practises and learn more about Javascript development. I've been using Javascript for over 15 years but have never used Javascript to build an entire website. So the question I ask when learning a new language/process is where do I start? How to I go about learning frontend development with Javascript?

Where To Start With Javascript Development?

This has been the hardest question to answer with Javascript development as there are so many good frameworks out there at the moment, which one do you choose?
This just names a few of the frameworks.
Which one do you choose?
I asked this question on Twitter, but I didn't want to just say what framework should I learn? I did some research and saw that the 2 main frameworks used are Angular or React. As these were the biggest with the largest communities and with the highest job prospects I wanted to go with one of these. Therefore I asked the question which framework should I learn Angular or React?

The replies I had to this tweet were very surprising, there was a mix between Angular and React with React coming slightly ahead. The surprising part was with the amount of people suggesting vue.js over any over framework.
Looking into Vue.js on github you can see how quickly this is gaining popularity and should be taken seriously. But looking at employability the main contenders are between Angular and React.
While searching for a comparison of the two frameworks I found this projectTodoMvc which is a Github repository that builds a simple To-do application using multiple different frameworks, this is a great way of comparing the different frameworks while they're performing the same actions.
To see the code of the React Todo project you can view it here.
To see the code of Angular2 Todo project you can view it here.
To see the code of Vue.js Todo project you can view it here.

Angular Vs React

As I'm not in a good position to compare these two frameworks so I've linked to the resources I used to make my decision.
The main difference between these two is that Angular is a Javascript framework and React is a Javascript library, which means it's the difference between buying a complete computer compared with buying the parts to build your computer.
Going on what I've read in the above articles about both Angular 2 and React, I've decided React is a better framework for me to learn. But then I was thinking about what people were saying on Twitter and how most people replied with VueJs, so I had to consider this in my choice.

VueJs

Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is very easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.
If you are an experienced frontend developer and want to know how Vue compares to other libraries/frameworks, check out the Comparison with Other Frameworks.
Compared with the other frameworks Vue looks very powerful, easy to learn and fast.
When using a language the size of the community is very important, the more people that use it the easier it is to find support. Looking at the top Javascript frameworks on Github you can see that Vue is gaining a lot of popularity.
As you can see from the image above Vue is 3rd most popular framework on Github behind Angular and React. When you consider the fact that Vue hasn't been around as long as the other two you can see it's going to catch up quickly.
Another point you need to look into when picking a language/framework is the progression of the product, if it hasn't been updated for a couple years then you don't really want to be using it. Vue have recently released version 2 of the framework increasing the speed of the framework.

Laravel

From Laravel 5.3 Vue is being included in the build and will be the focus to creating the front-end of your application. This is just the start of using Vue but this could mean the move away from Blade to be replaced with Vue.
This makes laravel a very good choice to use for the API of your app and use Vue to consume the API.
With Laravel making this move to include it in the build you will see a lot more people taking up Vue for their applications as opposed to React or Angular. For these reasons I've chosen to start learning Vue as I believe in the next coming of years it will gain more and more popularity in front-end development.
What's your opinions on the different frameworks?

Ajax Sending credentials with cross-domain posts?

Functionality is supposed to be broken in jQuery 1.5.
Since jQuery 1.5.1 you should use xhrFields param.
$.ajaxSetup({
    type: "POST",
    data: {},
    dataType: 'json',
    xhrFields: {
       withCredentials: true
    },
    crossDomain: true
});

Golden Rules of programming


1 . The AND operator is used when we use (=) and the operator OR is used when we use (!=)
2. True ( || )     False ( && )

Comments urs.

dynamically Adding options to a "select" using jQuery/JavaScript

Personally, I prefer this syntax for appending options:
$('#mySelect').append($(', {
    value: 1,
    text: 'My option'
}));
If you're adding options from a collection of items, you can do the following:
$.each(items, function (i, item) {
    $('#mySelect').append($(', { 
        value: item.value,
        text : item.text 
    }));
});

lazyload Image

JQuery

$(window).bind("load", function(){
 var timeout = setTimeout(function() {
  $('.lazyload1second').each(function(){      
   $(this).attr('src', $(this).attr('original_link')).fadeIn(700);
   $(this).removeAttr('original_link');   
  });
 }, 500);
});

HTML

width="100%"  src="//www.example.com/images/right_banner_loader.jpg" original_link="https://example.blob.core.windows.net/images/offers/website.jpg?v3=3" alt="True Rupees" class="lazyload1second">


Replace Or hide Broken Image

// Replace source
$('img').error(function(){
        $(this).attr('src', 'missing.png');
});

// Or, hide them
$("img").error(function(){
        $(this).hide();
});

Display Image Preview Be four Uploading Image.

See Live Demo.

http://stackoverflow.com/a/12369027


HTML



   type='file' onchange="readURL(this);" />
     id="blah" src="#" alt="your image" />

JQuery
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
}

JavaScript – Confirm Before Window is Closed

Here is the JavaScript code:
1
2
3
4
5
6
7
8
9
10
/** Confirms when closing the window **/
function checkClose()
{
    $("#s_scan_number").focus();
    return "Please DON'T close the window. Use the form button on the bottom.";
}
window.onbeforeunload = checkClose;
 
//to remove the confirmation dynamically:
window.onbeforeunload = null;

Cross Domain AJAX Requests

Introduction

Now on the web AJAX calls are becoming more and more common, they can be very useful to create a better user experience on your web applications. But on most modern browsers they will block anycross domain AJAX calls mainly for security reasons and the fact that AJAX uses client side scripting which might not work on another domain. If you are using jQuery to make your AJAX calls you can't post data to another domain, but PHP can post data to other domains by using the cURL extension. So to get around the cross domain AJAX problem, post data to your own PHP page and let cURL post this to the required URL.
In this article I will show you how to use cURL to post data from a jQuery post.

Change The jQuery POST Function

In this tutorial I am going to use PHP cURL to post data to another domain.
In jQuery to make an POST AJAX call you use the following.
var data = "parameters=1&para=2";             

             $.ajax({
    url: "http://www.example.com/post_url.php",
    data: data,
    type: "POST",
    success: function(data, textStatus, jqXHR){
   console.log('Success ' + data);
    },
    error: function (jqXHR, textStatus, errorThrown){
   console.log('Error ' + jqXHR);
    }
  });
This will post 2 parameters to http://www.example.com/post_url.php, but when this is sent you will get cross domain AJAX errors which means you aren't allowed to POST data to a different domain.
To get round this we are going to post to a page on our domain and then use this page to post the data.
var data = "url=http://www.example.com/post_url.php&parameters=1&para=2";             

             $.ajax({
    url: "our_domain_url.php",
    data: data,
    type: "POST",
    success: function(data, textStatus, jqXHR){
   console.log('Success ' + data);
    },
    error: function (jqXHR, textStatus, errorThrown){
   console.log('Error ' + jqXHR);
    }
  });
Notice it is the same AJAX call but I have changed the URL to a page on our server and moved the previous URL into data as a separate parameter. This is so we can get in from our PHP page and use this URL parameter to post the data.

Create A PHP Page To Post Data

Create a new PHP file and paste the following into the file.
//set POST variables
$url = $_POST['url'];
unset($_POST['url']);

$fields_string = "";
//url-ify the data for the POST
foreach($_POST as $key=>$value) { 
 $fields_string .= $key.'='.$value.'&'; 
}
$fields_string = rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($_POST));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);
This will first grab the URL out of the POST variable and then save this in a local variable this is so we can use this to send the data to. We need to then remove the URL from the POST variable to make sure we don't send this through as well.
Then we can loop through the POST variable and create our own query string.
Now we use cURL to post the data through to the URL.
That's it we have performed a cross domain AJAX call using jQuery and cURL.