0

I have created a page with Ajax function (jQuery & PHP). My problem is when I load content via Ajax in my page. I want to read width of images placed inside of Ajax-container.

I noticed something quite remarkable.

My script:

<script>
 $(window).ready(function () {
  var bildBreite = $("#wrapper > #target-image").width();
   alert(bildBreite);
  $("#wrapper > #image-wrapper").css({"width": bildBreite});
 });
</script>

It does not work, but when I insert alert ("load"); then work it.

<script>
 $(window).ready(function () {
  alert("Load");
  var bildBreite = $("#wrapper > #target-image").width();
   alert(bildBreite);
  $("#wrapper > #image-wrapper").css({"width": bildBreite});
 });
</script>

What happens here, how can I read the image width?

user6834389
  • 73
  • 1
  • 11
  • How are you calling your ajax? Can you also show those code? – vusan Feb 16 '17 at 09:27
  • – user6834389 Feb 16 '17 at 13:39

1 Answers1

1

In that case you need success callback because AJAX is Asynchronous so on Window Load it will not the get the element width so try it like,

$.ajax({
    ...
    success:function (response) {
       var bildBreite = $("#wrapper > #target-image").width();
       $("#wrapper > #image-wrapper").css({"width": bildBreite});
    }
});

Read more about jQuery.ajax

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • Thank you for your solution but, i have a little problem with it. I should push the Button two times! Befor i get a image size do you know why??? Thank you! – user6834389 Feb 16 '17 at 13:09
  • If your AJAX call is working in a single click then you don't need to click it twice. See in your browser's console when you click on button and make sure XHR request is made or not. – Rohan Kumar Feb 16 '17 at 13:11
  • if a cache is clean and i click on the button my first value is 0 if i click again i get a right value. – user6834389 Feb 16 '17 at 13:15
  • $(document).ready(function(){ var id = '1'; $.ajax({ dataType:"html", type: "POST", cache:false, async: true, data: "seite=" + id, url: "verzeichnis/script.php", success: function(breite) { $("#result").html(breite); var width = $('#result img').width(); alert(width); } }); }); – user6834389 Feb 16 '17 at 13:16
  • where is click event in this code – Rohan Kumar Feb 16 '17 at 13:18
  • – user6834389 Feb 16 '17 at 13:22