Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple ajax requests - jQuery

Tags:

jquery

I have javascript as below;

$.ajax({
        type: "POST",
        url: "ajax.php",
        data: {
          filename: $("#title1").html()
        },
        success: function(response){
          $cell1.css("background-image", "url('pdfthumb/" + response + ".jpg')");
        }
      });
$.ajax({
        type: "POST",
        url: "ajax.php",
        data: {
          filename: $("#title2").html()
        },
        success: function(response){
          $cell2.css("background-image", "url('pdfthumb/" + response + ".jpg')");
        }
      });
$.ajax({
        type: "POST",
        url: "ajax.php",
        data: {
          filename: $("#title3").html()
        },
        success: function(response){
          $cell3.css("background-image", "url('pdfthumb/" + response + ".jpg')");
        }
      });
$.ajax({
        type: "POST",
        url: "ajax.php",
        data: {
          filename: $("#title4").html()
        },
        success: function(response){
          $cell4.css("background-image", "url('pdfthumb/" + response + ".jpg')");
        }
      });

and more... Each time when i want result, i have to ajax and this made the script lengthy. Is there any way to shorten the code??

You can see my complete code here. I will be very thankful if somebody correct my code..

like image 778
Alfred Avatar asked Dec 20 '25 21:12

Alfred


1 Answers

How about making a function to do it for you?

function updateImage(title, cell) {
    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: {
            filename: title
        },
        success: function (response) {
            cell.css("background-image", "url('pdfthumb/" + response + ".jpg')");
        }
    });
}

You could then call this:

updateImage($('#title1').html(), $cell1);
updateImage($('#title2').html(), $cell2);
updateImage($('#title3').html(), $cell3);
updateImage($('#title4').html(), $cell4);
like image 71
lonesomeday Avatar answered Dec 22 '25 11:12

lonesomeday



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!