A jQuery ajax example

56 1 0 0

Last Updated : 2020-10-20 19:59:41

If you need to call a resource on the server using the jquery ajax technique, here is an example


  1. Here is a complete ajax examplex
    var theForm = $("#activeTagsForm") ;
    var formAction = theForm[0].action;
    var formMethod = theForm[0].method;
    var formData = theForm.serialize();
    //console.log(formData);

    var theAction = "{{ URL('activetags') }}" ;

    $.ajax({
    type: "post",
    //activetags.blade.phpurl: theAction+'?'+'&searchWord='+searchWord+"&page="+url2,
    url: theAction+'?'+"&page="+url2,
    data:formData,
    headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    dataType: "json",
    success: function (msg) {//alert('Success');

    if (msg) {
    if(msg['myResponseStatus'])
    {
    $("#allResults").html(msg['myResponseData']);
    }
    else
    {
    //The process has failed on srerver
    alert('Nooo');
    }

    } else {
    alert('There is NO message');
    }
    },

    }).done(function (data) {//alert('donee');

    }).fail(function () {alert('Failure');
    alert('Failed to load.');
    });​


  2. Another example using only Get


$(document).on("click","[id^='favIconProvincial-']",function(){
var theId = this.id ;
var dbId = this.id.substring('favIconProvincial-'.length);

$.get("{{url('addToFavorite')}}"+"/"+dbId+"/provincial" , function(ajaxResponse,ajaxStatus){

if(ajaxResponse == 'notLogged')
{
alert("Please Login first");
}
else
{
$("#"+theId).removeClass('active');
$("#"+theId).css('fontWeight','normal');
$("#"+theId).removeClass('active');

if(ajaxResponse == 'favored'){
$("#"+theId).css('fontWeight','900');
$("#"+theId).addClass('active');
}else{//Not Favored
$("#"+theId).css('fontWeight','normal');
$("#"+theId).removeClass('active');
}
}
});
});

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .