1

Okay so I'm trying to follow this tutorial but instead of storing it in a database I'm gonna store it somewhere else.

One problem though I have no clue how to append PHP variables with jQuery to the body!

Here is index.php

<html>

<head>
    <title>Store Your Browser Resolution!</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="js/main.js"></script>
</head>

<body>
    <button id="btn-POST">CLICK</button>
</body>

Here is Main.js

$(document).ready(function(){
$("#btn-POST").click(function(){
   $.ajax({
    type: 'POST',
    url: '/index.php',
    data: {
        width        : $(window).width(),
        height       : $(window).height(),
        screen_width : screen.width,
        screen_height: screen.height
    },
    success: function( data )
    {
        console.log('SUCCESS!');
        $("body").append($('<?php $width = $_POST["width"]; $height = $_POST["height"]; $screen_width = $_POST["screen_width"]; $screen_height = $_POST["screen_height"]; ?>'));
        $("body").delay(800).append($('<?php echo  ?>'))
    }
    }); 
});
console.log('Test!');
});

Any help would be appreciated :)

-Alex

1
  • index.php should insert the POST variables into the result that it returns. Commented Jun 21, 2016 at 18:36

2 Answers 2

2

Once the user has loaded the HTML / PHP site from your server it's impossible to execute more PHP commands.

This is because PHP is server sided, the user requests the document, your server executes all php commands and give the user the resulting HTML document.

Adding PHP code via JavaScript is clientside, so it won't work.

Sign up to request clarification or add additional context in comments.

8 Comments

So what could I do to, echo this data on my index.php page?
@abrad1212 That's exactly what you should do.
@abrad1212 simply add the data to your body or content. (Maybe in a div / span) e.g. $("body").append(data);
Thank YOU SO MUCH :)
Actually how would I go about doing Width: then the width Height: then the height Cause it looks like 600 775 1600 900
|
0

You wont be able to use php in your javascript file, but you could always declare you javascript variable in your index.php file and call those javascript objects in your javascript file.
ex:

//index.php
<script>
    var width = '<?php echo $_POST["width"]; ?>';
    ....
<script>

now just call the variables in your javascript file.

//Main.js
$("body").append(width+....);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.