PHP Get AJAX Data on the same page


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>

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

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

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.


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:

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

Answered By – Amir Hasani

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published