Home > Enterprise >  PHP Get AJAX Data on the same page
PHP Get AJAX Data on the same page

Time:05-21

I need to get a DOM element's width to work with the data later with PHP. The ajax call and the PHP is on the same page.

Here's how the page looks like:

<div id="elem" width="200px"></div>

<script>
let wd = document.getElementById('elem').offsetWidth;
$.ajax({ type: "POST", url: "index.php", data: {"width": wd} });
</script>

<div id="elem2">
<?php
  echo $_POST['width'] . 'px';
?>
</div>

So I have elem which has a not fix width and I need to get that so I can work with that in PHP later. It is important to get the width first, because elem is rendered before elem2 and I need elem's width to show elem2 properly.

The current output for echo $_POST['width'] is nothing. I have seen people getting the ajax data on the same page but they used form inputs, but I POST elem's width.

CodePudding user response:

I don't know this is can help you or not, but you can use success of ajax to show elem1's width inside elem2:

 $.ajax({
type: "post",
url: "index.php", //or somewhere else,
data: { width: wd },
dataType: "json",
success: function( response ) {
document.getElementById("elem2").innerHTML = response.width
}
})
  • Related