jQuery ajax get request method example

jQuery ajax get request method example

### jQuery Ajax Get Request Method Example This article is originally published at [https://www.tutsmake.com/jquery-api-ajax-get-method-example/](https://www.tutsmake.com/jquery-api-ajax-get-method-example/...

jQuery Ajax Get Request Method Example

This article is originally published at https://www.tutsmake.com/jquery-api-ajax-get-method-example/

Let's see example of jquery ajax get request.

<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Ajax GET Request Example</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
<style>  
.formClass
{
    padding: 15px;
    border: 12px solid #23384E;
    background: #28BAA2;
    margin-top: 10px;
} 
</style> 
<script type="text/javascript">
$(document).ready(function(){
   $("button").click(function(event){
 
    var name = "Tutsmake";
     
    $.get('https://www.tutsmake.com/Demos/html/ajax-get-method.php', {webname: name}, function(data){
 
        $("#output").html(data);
    });
 
  });
 
});
</script>
</head>
<body>
    <div class="formClass">
      <button type="button">Click &amp; Get Data</button><br>
      <div id="output">Hello</div>    
    </div>
</body>
</html>   ```                         

This article is originally published at [https://www.tutsmake.com/jquery-api-ajax-get-method-example/](https://www.tutsmake.com/jquery-api-ajax-get-method-example/ "https://www.tutsmake.com/jquery-api-ajax-get-method-example/")

Ajax Form Submit examples using jQuery

Ajax Form Submit examples using jQuery

In this jquery ajax form tutorial – you have learned how to send or submit the form data or multipart form using the jquery ajax on the server. Also, you have known the related queries of jquery ajax form.

Overview

In this jQuery Ajax submits a multipart form or FormData tutorial example – you will learn how to submit the form using the jquery ajax with multi-part data or FromData. Here you will know about the basic faqs of jquery ajax form.

In this tutorial, learn jquery ajax form submits with the form data step by step. A simple jQuery Ajax example to show you how to submit a multipart form, using Javascript FormData and $.ajax().

If you will be using jQuery’s Ajax Form Submit, you can send the form data to the server without reloading the entire page. This will update portions of a web page – without reloading the entire page.

AJAX: AJAX (asynchronous JavaScript and XML) is the art of exchanging data with a server and updating parts of a web page – without reloading the entire page.

Table Of Contents

  • Create HTML Form
  • jQuery Ajax Code

FAQs

  • How to add extra fields or data with Form data in jQuery ajax?
  • ajax FormData: Illegal invocation
  • How to send multipart/FormData or files with jQuery.ajax?

Create HTML Form

In this step, we will create an HTML form for multiple file uploads or FormData and an extra field.

<!DOCTYPE html>
<html>
<title>jQuery Ajax Form Submit with FormData Example</title>
<body>
 
<h1>jQuery Ajax Form Submit with FormData Example</h1>
 
<form method="POST" enctype="multipart/form-data" id="myform">
    <input type="text" name="title"/><br/><br/>
    <input type="file" name="files"/><br/><br/>
    <input type="submit" value="Submit" id="btnSubmit"/>
</form>
 
<h1>jQuery Ajax Post Form Result</h1>
 
<span id="output"></span>
 
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> 
 
</body>
</html>

jQuery Ajax Code

In this step, we will write jquery ajax code for sending a form data to the server.

$(document).ready(function () {
 
    $("#btnSubmit").click(function (event) {
 
        //stop submit the form, we will post it manually.
        event.preventDefault();
 
        // Get form
        var form = $('#fileUploadForm')[0];
 
       // Create an FormData object 
        var data = new FormData(form);
 
       // If you want to add an extra field for the FormData
        data.append("CustomField", "This is some extra data, testing");
 
       // disabled the submit button
        $("#btnSubmit").prop("disabled", true);
 
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "/upload.php",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 800000,
            success: function (data) {
 
                $("#output").text(data);
                console.log("SUCCESS : ", data);
                $("#btnSubmit").prop("disabled", false);
 
            },
            error: function (e) {
 
                $("#output").text(e.responseText);
                console.log("ERROR : ", e);
                $("#btnSubmit").prop("disabled", false);
 
            }
        });
 
    });
 
});

FAQs – jQuery Ajax Form Submit

1. How to add extra fields with Form data in jQuery ajax?

The **append()** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.

// Create an FormData object 
    var data = new FormData(form);
 
// If you want to add an extra field for the FormData
    data.append("CustomField", "This is some extra data, testing");

2. ajax FormData: Illegal invocation

jQuery tries to transform your FormData object to a string, add this to your $.ajax call:

processData: false,
contentType: false

3. How to send multipart/FormData or files with jQuery.ajax?

In this step you will learn how to send multiple files using jQuery ajax. Let’s see the below code Snippet:

var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file-'+i, file);
});
 
$.ajax({
    url: 'upload.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    success: function(data){
      console.log('success');
    }
});

Note

Conclusion

In this jquery ajax form tutorial – you have learned how to send or submit the form data or multipart form using the jquery ajax on the server. Also, you have known the related queries of jquery ajax form.

Laravel 6 Ajax Request Tutorial

Laravel 6 Ajax Request Tutorial

In this post, you'll learn how to write jquery ajax form submit in Laravel 6. We will write Jquery Ajax post request Laravel 6. We will protect csrf token with Ajax request in Laravel 6. I will give you very simple example of Laravel 6 Ajax post request tutorial.

You can easily use Ajax get request, Ajax post request, Ajax put request, Ajax delete request ect with Laravel 6.

Ajax request is a basic requirement of any PHP project, we are always looking for without page refresh data should store in database and it's possible only by Jquery Ajax request. same thing if you need to write ajax form submit in Laravel 6 then i will help you how you can pass data with ajax request and get on controller.

If you want to add ajax request with validation then you can follow this article: Laravel 6 Ajax Form Validation

You have to just do three things to understand how to use ajax request in Laravel 6, so just follow this three step and you will learn how to use Ajax request in your Laravel 6 application.

Step 1: Create Routes

First thing is we put two routes in one for displaying view and another for post Ajax. So simple add both routes in your route file.

routes/web.php

Route::get('ajaxRequest', '[email protected]');
Route::post('ajaxRequest', '[email protected]')->name('ajaxRequest.post');

Step 2: Create Controller

Same things as above for routes, here we will add two new method for routes. One will handle view layout and another for post ajax request method, so let's add bellow:

app/Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class AjaxController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function ajaxRequest()
{
return view('ajaxRequest');
}

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function ajaxRequestPost(Request $request)
{
    $input = $request-&gt;all();
    \Log::info($input);

    return response()-&gt;json(['success'=&gt;'Got Simple Ajax Request.']);
}

}

Read Also: Laravel 6 CRUD Application Tutorial

Step 3: Create Blade File

Finally we require to create ajaxRequest.blade.php file and here we will write code of jquery ajax and pass Laravel token. So blade file is very important in ajax request. So let's see bellow file:

resources/views/ajaxRequest.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel 6 Ajax Request example</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>

&lt;div class="container"&gt;
    &lt;h1&gt;Laravel 6 Ajax Request example&lt;/h1&gt;

    &lt;form &gt;

        &lt;div class="form-group"&gt;
            &lt;label&gt;Name:&lt;/label&gt;
            &lt;input type="text" name="name" class="form-control" placeholder="Name" required=""&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;label&gt;Password:&lt;/label&gt;
            &lt;input type="password" name="password" class="form-control" placeholder="Password" required=""&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;strong&gt;Email:&lt;/strong&gt;
            &lt;input type="email" name="email" class="form-control" placeholder="Email" required=""&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;button class="btn btn-success btn-submit"&gt;Submit&lt;/button&gt;
        &lt;/div&gt;

    &lt;/form&gt;
&lt;/div&gt;

</body>
<script type="text/javascript">

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(".btn-submit").click(function(e){

    e.preventDefault();

    var name = $("input[name=name]").val();
    var password = $("input[name=password]").val();
    var email = $("input[name=email]").val();

    $.ajax({
       type:'POST',
       url:"{{ route('ajaxRequest.post') }}",
       data:{name:name, password:password, email:email},
       success:function(data){
          alert(data.success);
       }
    });

});

</script>

</html>

Now you can run your example and see.

You will get output like as bellow:

Output

[2019-09-17 03:54:19] local.INFO: array (
'name' => 'Hardik Savani',
'password' => '123456',
'email' => '[email protected]',
)

I hope it can help you

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

☞ Tutorial Laravel 6 with Docker and Docker-Compose

☞ Laravel 6 CRUD Application Tutorial

☞ What's New in Laravel 6.0?

Originally published https://itsolutionstuff.com


ASP.NET MVC Application with JQuery, AJAX

ASP.NET MVC Application with JQuery, AJAX

Let's have a sample example: We have a submit button in our JQuery AJAX MVC application. Let's try to show a message when it is clicked. ASP.NET MVC Application - Using JQuery, AJAX

Before diving into the core topic let’s have an overview about JQuery and Ajax. What is it?

What is JQuery?
Well, JQuery is a framework (tools) for writing JavaScript, Written as "write less, do more", jQuery is to make easier to use JavaScript.

What is JavaScript?
JavaScript is an object-oriented computer programming (Scripting) language commonly used to create interactive effects within web browsers.

Let’s have a sample example:
We have a submit button in our JQuery AJAX MVC application. Let’s try to show a message when it is clicked.

Here is our button with defined id="btnSubmit":

<input type="submit" value="Create" class="btn btn-default" id="btnSubmit" />

Now we need to write some script to do that, here is some JavaScript code:

var myBtn = document.getElementById('btnSubmit');  
myBtn.addEventListener('click', function(e) {  
    e.preventDefault(); //This prevents the default action  
    alert('Hello'); //Show the alert  
});

By this code the result will show “Hello”:

Now if we can get the same result by using jQuery instead of it. Let’s have a look:

$('#btnSubmit').click(function(event) {  
    event.preventDefault(); //This prevents the default action  
    alert("Hello"); //Show the alert  
});

Note: Here use of 'e' is just a short for event which raised the event. We can pass any variable name. Notice that the ‘e’ is changed to name ‘event’ in JQuery part.

This piece of code is also producing the same result “Hello”. This is why jQuery is known as "write less, do more".

Finally the script:

<script type="text/javascript">  
    $(document).ready(function() {  
        $(function() {  
  
            /*var myBtn = document.getElementById('btnSubmit');  
            myBtn.addEventListener('click', function(e) {  
                e.preventDefault();  
                alert('Hello');  
            });*/
  
            $('#btnSubmit').click(function(event) {  
                event.preventDefault();  
                alert("Hello");  
            });  
        });  
    });  
</script>

Let's focus on Ajax:

AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without reloading the whole page. It is a technique for creating fast and dynamic web pages.

In .NET, we can call server side code using two ways:

  1. ASP .NET AJAX
  2. jQuery AJAX

In this article we will focus on JQuery Ajax.

$.ajax () Method:

JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:

  • $.ajax() Performs an async AJAX request.
  • $.get() Loads data from a server using an AJAX HTTP GET request.
  • $.post() Loads data from a server using an AJAX HTTP POST request.

To know more click.

$.ajax () Method Configuration option:

Options that we use:

  • async:
  • type:
  • url:
  • data:
  • datatype:
  • success:
  • error:

Let’s have details overview:

async

Set to false if the request should be sent synchronously. Defaults to true.

Note that if you set this option to false, your request will block execution of other code until the response is received.

Example:

async: false,

type

This is type of HTTP Request and accepts a valid HTTP verb.

The type of the request, "POST" or "GET" defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all the web browsers.

Example:

type: "POST",

url

The URL for the request.

Example:

url: "/Home/JqAJAX",

data

The data to be sent to the server. This can either be an object or a query string.

Example:

data: JSON.stringify(model_data),

dataType

The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified.

Accepted values are text, xml, json, script, html jsonp.

Example:

dataType: "json",

contentType

This is the content type of the request you are making. The default is 'application/x-www-form-urlencoded'.

Example:

contentType: 'application/json; charset=utf-8',

success

A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the DataType was JSON), as well as the text status of the request and the raw request object.

Success: function (result) {  
   $('#result').html(result);  
}

error

A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.

error: function (result) {  
   alert('Error occured!!');  
},

Let’s Post Values using JQuey,Ajax:

We often use the jQuery Ajax method in ASP.NET Razor Web Pages. Here is a sample code:

<input type="submit" id="btnSubmit" value="Add Student" />  
<script type="text/javascript">  
    $(document).ready(function() {  
        $(function() {  
            $('#btnSubmit').click(function(event) {  
                event.preventDefault();  
                var Student = {  
                    ID: '10001',  
                    Name: 'Shashangka',  
                    Age: 31  
                };  
                $.ajax({  
                    type: "POST",  
                    url: "/Home/JqAJAX",  
                    data: JSON.stringify(Student),  
                    dataType: "json"  
                    contentType: 'application/json; charset=utf-8',  
                    success: function(data) {  
                        alert(data.msg);  
                    },  
                    error: function() {  
                        alert("Error occured!!")  
                    }  
                });  
            });  
        });  
    });  
</script>

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(Student st) {  
    try {  
        return Json(new {  
            msg = "Successfully added " + st.Name  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

Posting JSON

JSON is a data interchange format where values are converted to a string. The recommended way to create JSON is include the JSON.stringify method. In this case we have defined:

JSON.stringify(Student)

And the data type set to:

datatype: "json"

And the content type set to application/json

contentType: 'application/json; charset=utf-8'

Syntax:

JSON.stringify(value[, replacer[, space]])

Post Script:

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: JSON.stringify(Student),  
    contentType: 'application/json; charset=utf-8',  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(Student st) {  
    try {  
        return Json(new {  
            msg = "Successfully added " + st.Name  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

JSON Response Result:
Sent data format:
{"ID":"10001","Name":"Shashangka","Age":31}
Received Data format:
{"msg":"Successfully added Shashangka"}

Let’s Post JavaScript Objects:

To send JavaScript Objects we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

data: Student

And the datatype set to:

datatype: "html"

And the content type set to default.

contentType: 'application/x-www-form-urlencoded'

Post Script

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: Student,  
    contentType: 'application/x-www-form-urlencoded',  
    datatype: "html",  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: Student,  
    contentType: 'application/x-www-form-urlencoded',  
    datatype: "html",  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

JavaScript Objects Response Result:

Sent data format:
ID=10001&Name=Shashangka&Age=31
Received Data format:
{"msg":"Successfully added Shashangka"}

Let’s Post JavaScript Arrays:

To send Array we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

data: Student

And the datatype set to:

datatype: "html"

And the content type set to default

contentType: 'application/x-www-form-urlencoded'

Post Script:

var ID = ["Shashangka", "Shekhar", "Mandal"];  
  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: {  
        values: ID  
    },  
    datatype: "html",  
    contentType: 'application/x-www-form-urlencoded',  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(string[] values) {  
    try {  
        return Json(new {  
            msg = String.Format("Fist Name: {0}", values[0])  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

Array Response Result:

Sent data format:
values[]=Shashangka&values[]=Shekhar&values[]=Mandal
Received Data format:
{"msg":"Fist Name: Shashangka"}

Hope this will help to understand different datatypes and Ajax posting. Thank you!