Debug School

rakesh kumar
rakesh kumar

Posted on

How to to optimize multiple AJAX requests using arrays and for loops in jquery

step1: create a form element contain input type,dropdown and different kind of elements

  <form method="post" id="addProfile_Sample_Form" class="form-horizontal" enctype="multipart/form-data">
                    @csrf
                    <div class="row">

                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-facebook" id="basic-addon1" style="font-size:24px; color: blue;"></span>
                                </div>
                                <input type="text" name="facebook" id="facebook_url" class="form-control" placeholder="Enter your facebook url" value="{{$profile_user_url->facebook}}">


                            </div>
                        </div>

                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-twitter" id="basic-addon1" style="font-size:24px; color: #00cccc;"></span>
                                </div>
                                <input type="text" name="twitter" id="twitter_url" class="form-control" placeholder="Enter your twitter url" value="{{$profile_user_url->twitter}}">
                            </div>
                        </div>

                    </div>

                    <div class="row">
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-youtube" id="basic-addon1" style="font-size:24px; color: #ff0000;"></span>
                                </div>
                                <input type="text" name="youtube" id="youtube_url" class="form-control" placeholder="Enter your youtube url" value="{{$profile_user_url->youtube}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-wordpress" id="basic-addon1" style="font-size:24px"></span>
                                </div>
                                <input type="text" name="wordpress" id="wordpress_url" class="form-control" placeholder="Enter your wordpress url" value="{{$profile_user_url->wordpress}}">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-tumblr-square" id="basic-addon1" style="font-size:24px; color: #9900e6;"></span>
                                </div>
                                <input type="text" name="tumblr" id="tumblr_url" class="form-control" placeholder="Enter your tumblr url" value="{{$profile_user_url->tumblr}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-instagram" id="basic-addon1" style="font-size:24px; color: #ff0066;"></span>
                                </div>
                                <input type="text" name="instagram" id="instagram_url" class="form-control" placeholder="Enter your instagram url" value="{{$profile_user_url->instagram}}">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-quora" id="basic-addon1" style="font-size:24px; color: #990000;"></span>
                                </div>
                                <input type="text" name="quora" id="quora_url" class="form-control" placeholder="Enter your quora url" value="{{$profile_user_url->quora}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-pinterest" id="basic-addon1" style="font-size:24px; color: #b30000;"></span>
                                </div>
                                <input type="text" name="pinterest" id="pinterest_url" class="form-control" placeholder="Enter your pinterest url" value="{{$profile_user_url->pinterest}}">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-reddit" id="basic-addon1" style="font-size:24px; color: #ff0000;"></span>
                                </div>
                                <input type="text" name="reddit" id="reddit_url" class="form-control" placeholder="Enter your reddit url" value="{{$profile_user_url->reddit}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text koo" id="basic-addon1" style="font-size:24px; color: #ffaa00;"> </span>
                                </div>
                                <input type="text" name="koo" id="koo_url" class="form-control" placeholder="Enter your koo url" value="{{$profile_user_url->koo}}">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text scoopit-favicon" id="basic-addon1" style="font-size:24px"></span>
                                </div>
                                <input type="text" name="scoopit" id="scoopit_url" class="form-control" placeholder="Enter your scoopit url" value="{{$profile_user_url->scoopit}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text slashdot-favicon" id="basic-addon1" style="font-size:24px"> </span>
                                </div>
                                <input type="text" name="slashdot" id="slashdot_url" class="form-control" placeholder="Enter your slashdot url" value="{{$profile_user_url->slashdot}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-telegram" id="basic-addon1" style="font-size:24px"> </span>
                                </div>
                                <input type="text" name="telegram" id="telegram_url" class="form-control" placeholder="Enter your Telegram url" value="{{$profile_user_url->telegram}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-facebook" id="basic-addon1" style="font-size:24px"> </span>
                                </div>
                                <input type="text" name="fb_grp" id="fb_grp_url" class="form-control" placeholder="Enter your Facebook Group Url" value="{{$profile_user_url->fb_grp}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-linkedin" id="basic-addon1" style="font-size:24px"> </span>
                                </div>
                                <input type="text" name="linkedin_grp" id="linkedin_grp_url" class="form-control" placeholder="Enter your linkedin Group Url" value="{{$profile_user_url->linkedin_grp}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text fab fa-linkedin-in" id="basic-addon1" style="font-size:24px"> </span>
                                </div>
                                <input type="text" name="linkedin" id="linkedin_url" class="form-control" placeholder="Enter your linkedin Url" value="{{$profile_user_url->linkedin}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text" id="basic-addon1" style="font-size:24px"><img src="{{url('assets/images/roposo-icons.png')}}" width="30"> </span>

                                </div>
                                <input type="text" name="roposo" id="roposo_url" class="form-control" placeholder="Enter your Roposo Url" value="{{$profile_user_url->roposo}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text chingari-icons-icon" id="basic-addon1" style="font-size:24px"><img src="{{url('assets/images/chingari-icons.webp')}}" width="30"> </span>
                                </div>
                                <input type="text" name="chingari" id="chingari_url" class="form-control" placeholder="Enter your Chingari Url" value="{{$profile_user_url->chingari}}">
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text mitron-icon" id="basic-addon1" style="font-size:24px"><img src="{{url('assets/images/mitron.png')}}" width="30"> </span>

                                </div>
                                <input type="text" name="mitron" id="mitron_url" class="form-control" placeholder="Enter your Mitron Url" value="{{$profile_user_url->mitron}}">
                            </div>
                        </div>
                    </div>
                    <input type="hidden" value="{{ Auth::user()->id }}" name="admin_id" id="profile_store_hidden_id" />
                    <input type="hidden" value="{{ Auth::user()->email }}" name="admin_email" id="admin_email" />
                    <input type="hidden" value="{{ Auth::user()->name }}" name="user_name">                   
            </div>
            <div class="form-group text-center">
                <input type="hidden" name="action" id="action" />
                <input type="hidden" name="profile_hidden_id" id="profile_hidden_id" />
                <input type="submit" name="action_button" id="action_add_profile_button" class="btn btn-warning float-center" value="Add" />
            </div>
            </form>
        </div>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

output

Image description

step2:submit a form

 $('#addProfile_Sample_Form').on('submit', function(event) {
        event.preventDefault();
        if ($('#action_add_profile_button').val() == "Add") {
       console.log('addprofile button pefr click ho rha hai');  
       var facedurl = $('#facedprice').text();
Enter fullscreen mode Exit fullscreen mode

Image description

step3:Create an object to store form element apply validation while submitting form

 $('#addProfile_Sample_Form').on('submit', function(event) {
        event.preventDefault();
        if ($('#action_add_profile_button').val() == "Add") {
       console.log('addprofile button pefr click ho rha hai');  
       var facedurl = $('#facedprice').text();

       var socialUrls = {
        'facebook': $('#facebook_url').val(),
        'twitter': $('#twitter_url').val(),
        'youtube': $('#youtube_url').val(),
        'wordpress': $('#wordpress_url').val(),
        'tumblr': $('#tumblr_url').val(),
        'instagram': $('#instagram_url').val(),
        'quora': $('#quora_url').val(),
        'pinterest': $('#pinterest_url').val(),
        'reddit': $('#reddit_url').val(),
        'koo': $('#koo_url').val(),
        'scoopit': $('#scoopit_url').val(),
        'slashdot': $('#slashdot_url').val(),
        'telegram': $('#telegram_url').val(),
        'fb_grp': $('#fb_grp_url').val(),
        'linkedin_grp': $('#linkedin_grp_url').val(),
        'linkedin': $('#linkedin_url').val(),
        'chingari': $('#chingari_url').val(),
        'roposo': $('#roposo_url').val(),        
        'mitron': $('#mitron_url').val()
    };
Enter fullscreen mode Exit fullscreen mode

step4:declare Flag to track overall validation status

 var isValid = true; 
Enter fullscreen mode Exit fullscreen mode

step5 Loop through each element of above created object

for (var platform in socialUrls) {
    if (socialUrls.hasOwnProperty(platform)) {
        if (!validateSocialUrl(socialUrls[platform], platform)) {

            let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
             please put correct url in ${platform} field.
            </h5>`;            

    $('#cannotupdate').modal('show');
    $('#updateno').html(htmlCode);
            // If validation fails for any platform, set isValid to false
            isValid = false;
            break; // No need to continue checking other platforms
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Note

// Example object
var socialUrls = {
    'facebook': 'https://www.facebook.com/user123',
    'twitter': 'https://twitter.com/user456',
    'instagram': 'https://www.instagram.com/user789'
};

// Iterate over properties using for...in loop
for (var platform in socialUrls) {
    if (socialUrls.hasOwnProperty(platform)) {
        // Access each property and its value
        console.log('Platform:', platform);      // e.g., 'facebook'
        console.log('URL:', socialUrls[platform]); // e.g., 'https://www.facebook.com/user123'
    }
}
Enter fullscreen mode Exit fullscreen mode
// Create an object with a property and a method
var myObject = {
    prop1: 'Property 1 Value',
    method1: function() {
        console.log('Method 1 called');
    }
};

// Check if the object has a specific property using hasOwnProperty
console.log(myObject.hasOwnProperty('prop1')); // true
console.log(myObject.hasOwnProperty('method1')); // true
console.log(myObject.hasOwnProperty('toString')); // false (inherited from Object prototype)
Enter fullscreen mode Exit fullscreen mode

step6:Call the validateSocialUrl function to check the URL validity for the current platform

function validateSocialUrl(url, platform) {
    console.log('validateSocialUrl button pe click ho rha hai profile');
    function containsDigits(str) {
    return /\d/.test(str);
} 

var socialPlatforms = [
    { platform: 'facebook', elementId: '#facedprice' },
    { platform: 'twitter', elementId: '#twitterdprice' },
    { platform: 'youtube', elementId: '#youtubedprice' },
    { platform: 'wordpress', elementId: '#wordpressdprice' },
    { platform: 'tumblr', elementId: '#tumblrdprice' },
    { platform: 'instagram', elementId: '#instagramdprice' },
    { platform: 'quora', elementId: '#quoradprice' },
    { platform: 'pinterest', elementId: '#pinterestdprice' },
    { platform: 'reddit', elementId: '#redditdprice' },
    { platform: 'koo', elementId: '#koodprice' },
    { platform: 'scoopit', elementId: '#scoopitdprice' },
    { platform: 'slashdot', elementId: '#slashdotdprice' },
    { platform: 'telegram', elementId: '#telegramdprice' },
    { platform: 'fb_grp', elementId: '#fb_grpindprice' },
    { platform: 'linkedin_grp', elementId: '#linkedin_grpdprice' },
    { platform: 'linkedin', elementId: '#linkedindprice' },
    { platform: 'chingari', elementId: '#chingaridprice' },
    { platform: 'roposo', elementId: '#roposodprice' },
    { platform: 'mitron', elementId: '#mitrondprice' }
    // Add more platforms as needed
];
if (!url) {
for (var i = 0; i < socialPlatforms.length; i++) {
    var platformObj = socialPlatforms[i];
    var platforms = platformObj.platform;
    var elementId = platformObj.elementId;
    var price = $(elementId).text();   
        if (platform === platforms && containsDigits(price)) {
            console.log("data comes")
            let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
             Cannot update data facebook price is assigned .
            </h5>`;           
    $('#cannotupdate').modal('show');
    $('#updateno').html(htmlCode);
    return false;
        }          
    }
    return true; 
}
Enter fullscreen mode Exit fullscreen mode

apply wrong flow for loop

if (!url) {
for (var i = 0; i < socialPlatforms.length; i++) {
    var platformObj = socialPlatforms[i];
    var platforms = platformObj.platform;
    var elementId = platformObj.elementId;
    var price = $(elementId).text();   
        if (platform === platforms && !containsDigits(price)) {
            console.log("data comes")

        }  
        else
        {
            let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
             Cannot update data facebook price is assigned .
            </h5>`;           
    $('#cannotupdate').modal('show');
    $('#updateno').html(htmlCode);
    return false;
        }
    }
    return true; 
}
Enter fullscreen mode Exit fullscreen mode

Another way using if-else

function validateSocialUrl(url, platform) {
    console.log('validateSocialUrl button pe click ho rha hai profile');
    function containsDigits(str) {
    return /\d/.test(str);
} 

var instagramdprice = $('#instagramdprice').text();
var tumblrdprice = $('#tumblrdprice').text();
var wordpressdprice = $('#wordpressdprice').text();
var facedurl = $('#facedprice').text();
var youtubedprice = $('#youtubedprice').text();
var twitterdprice = $('#twitterdprice').text();
var telegramdprice = $('#telegramdprice').text();
var redditdprice = $('#redditdprice').text();
var pinterestdprice = $('#pinterestdprice').text();
var quoradprice = $('#quoradprice').text();
var linkedindprice = $('#linkedindprice').text();
var linkedin_grpdprice = $('#linkedin_grpdprice').text();
var fb_grpindprice = $('#fb_grpindprice').text();
var koodprice = $('#koodprice').text();
var scoopitdprice = $('#scoopitdprice').text();
var slashdotdprice = $('#slashdotdprice').text();
var roposodprice = $('#roposodprice').text();
var chingaridprice = $('#chingaridprice').text();
var mitrondprice = $('#mitrondprice').text();


    if (!url) {

        if (platform === 'facebook' && !containsDigits(facedurl)) { 

            console.log('Valid URL'); 

        }
        else if (platform === 'twitter' && !containsDigits(twitterdprice)) {
                console.log('Valid URL'); 
            } 
            else if (platform === 'youtube' && !containsDigits(youtubedprice)) {
                console.log('Valid URL');    
            } 
            else if (platform === 'wordpress' && !containsDigits(wordpressdprice)) {
                console.log('Valid URL');    
            } 
            else if (platform === 'tumblr' && !containsDigits(tumblrdprice)) {
                console.log('Valid URL');   
            } 
            else if (platform === 'instagram' && !containsDigits(instagramdprice)) {
                console.log('Valid URL');  
            } 
            else if (platform === 'quora' && !containsDigits(quoradprice)) {
                console.log('Valid URL');  
            } 
            else if (platform === 'pinterest' && !containsDigits(pinterestdprice)) {

            } 
            else if (platform === 'reddit' && !containsDigits(redditdprice)) {
                console.log('Valid URL');   
            } 
            else if (platform === 'koo' && !containsDigits(koodprice)) {
                console.log('Valid URL');   
            } 
            else if (platform === 'scoopit' && !containsDigits(scoopitdprice)) {

            } 
            else if (platform === 'slashdot' && !containsDigits(slashdotdprice)) {
                console.log('Valid URL');   
            } 
            else if (platform === 'telegram' && !containsDigits(telegramdprice)) {
                console.log('Valid URL');    
            } 
            else if (platform === 'fb_grp' && !containsDigits(fb_grpindprice)) {
                console.log('Valid URL');    
            } 

            else if (platform === 'linkedin_grp' && !containsDigits(linkedin_grpdprice)) {
                console.log('Valid URL');  
            } 
            else if (platform === 'linkedin' && !containsDigits(linkedindprice)) {
                console.log('Valid URL');  
            } 
            else if (platform === 'chingari' && !containsDigits(chingaridprice)) {
                console.log('Valid URL'); 
            } 

            else if (platform === 'roposo' && !containsDigits(roposodprice)) {
                console.log('Valid URL'); 
            } 
            else if (platform === 'mitron' && !containsDigits(mitrondprice)) {
                console.log('Valid URL'); 
            } 

        else
        {
            let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
             Cannot update data facebook price is assigned .
            </h5>`;           
    $('#cannotupdate').modal('show');
    $('#updateno').html(htmlCode);
    return false;  

        }

        return true;
    }
Enter fullscreen mode Exit fullscreen mode

step7:Call the submitSocialUrlAjax function to submit or store data based on flag is true

if (isValid) {
    for (var platform in socialUrls) {
        if (socialUrls.hasOwnProperty(platform)) {
            submitSocialUrlAjax(socialUrls[platform]);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
    function submitSocialUrlAjax(url) {
        console.log('submitSocialUrlAjax Faceboo button pe click ho rha hai');
    // Use the URL to make the AJAX call
    $.ajax({
        url: "{{ url('addprofile/social-url') }}",
        type: "POST",
        data: new FormData($('#addProfile_Sample_Form')[0]),
        contentType: false,
        cache: false,
        processData: false,
        dataType: "json",
        headers: {
            "Authorization": "Bearer " + localStorage.getItem('a_u_a_b_t')
        },
        success: function (data) {
            var html = '';
            if (data.success) {
                html = '<div class="alert alert-success">' + data.message +
                    '</div>';
                $('#store_url_result').html(html);
                setTimeout(function () {
                    $('#addProfileModal').modal('hide');
                    location.reload(true);
                }, 2000);
            } else {
                html = '<div class="alert alert-danger">' + data.message +
                    '</div>';
                $('#store_url_result').html(html);
            }
        },
        error: function (data) {
            console.log('Error:', data);
            console.log('Update function kamm nahi kr rha hai');
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)