Category : JavaScript &Jquery

create ajax request with file upload with formData

how to create ajax request without using serialize

Json Data, stringfy, parse

IN javascript you can convert js data such as array into JSON using JSON.stringfy() , and back from JSON to js array using JSON.Parse, Here is the syntax :

json_encode & JSON.parse

Sometimes, you will need to transform a php array into a json string in order to send it to a javascript code to work on it. In this case you will have to use the php built in function json_encode($phpArray) and then in javascript code, you have to transform this json string into an object so that you can iterate over it or do whatever you want with it, Now on javascript you can do this by using JSON.parse(allSearchableTags)

Highlight elements inside a list once clicked

If you have let's say an unordered list and it is populated with multiple items and you need to highligh the clicked item and if clicked again remove the highlight. A very good and interresting way to do this is to make use of the buble behavoir for events and add event listener only for the parent container element, and then use the event.target to get to the clicked element itself, which is the list item in our example.

Creating a loading div and hiding it - Ajax with loader

Here is a snippet for a function to create a loader or a loading div to be used with ajax request and then can also hide it.

DOM HELPER CLASS

In this class, we will have a helper class that will allow us to do the following: clear event listener from an element. move an element to another location ..etc

Prototype Methods

If you need to use the prototype to add new general methods to any general protoype or construct functions such as Object, Array, String .. etc, here are few examples

Convert an object into an array or a string

In order to convert an object into an array, this is easy using the Object.values() method. On the other hand if you want to convert an object into a string, any Object can be converted to a string using the JSON.stringify() method.

bind(), call() and apply()

In alot of cases in javascript, you will find it very difficult to pass certain parameter values or context to the function call. For example, the keyword 'this' which will mean very different things each time it is used depending on the context in which it was used and how it was used, inside a function or outside it, inside a function defined with the function keyword or an arrow function. Also when triggering an event that call a function and you need to pass/bind some parameters to this function. So here is a good explanation for the bind(), call() and apply() functions.

Looping through an object to get its properties and values

In case you have an object and need to loop through all its keys or properties and its related values you can use the following syntax