aaronlbrink aaronlbrink - 2 years ago 77
PHP Question

Adding PHP Variables to JQuery's Ajax data

So as you can probably tell, I'm a bit amateur when it comes to jQuery. So if there's any better methods to do what I'm trying to do, please share kindly :) Here's what's happening. Everything works smoothly in the script when you substitute

<?php echo $header_id; ?>
for a given id that is compatible, say
. Although
is defined before this script, it must not be really outputting '17'.

I did research before this, not finding anything to help.

So I guess the main question is, does adding a PHP echo really work in this instance, or do I need another method, or is that not even the problem...

$(".vote-button-disabled").click(function (evt) {
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();

var quizid = "";
url: "scripts/vote-post.php",
type: "POST",
data: {
'quizid' : '<?php echo $header_id; ?>',
'upvote' : '1',
success: function() {

error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
complete: function( xhr, status ) {
alert( "The request is complete!" );


Thanks in advanced!

Answer Source

Something to understand is that PHP is executed on the server side, and JavaScript is executed on client side.

PHP does not actually have any awareness of what is HTML, what is JavaScript, or what is plain text. It just knows that it's serving back some kind of content (maybe). So when you echo HTML or JavaScript code, you're really just creating a text file as far as PHP is concerned. You're creating a file that contains some text (that happens to be HTML + JS code) and sending that as the response to the HTTP request. Your browser interprets the resulting text in the response (which happens to be HTML + JS code). So one way you can think of PHP is as a HTML + JS generator. You can use PHP to output HTML + JS (and of course much more).

Once you understand that PHP is completely done executing by the time the page is sent back for the browser to interpret the HTML and JavaScript, the answer to what you can and can't do with JavaScript becomes much simpler. PHP is not interacting with JS, it's creating the JS code as text for your browser to read after PHP execution has completed.

So, as @charlietfl mentioned in the comments on the question, you should add the quizid to a data-quizid attribute on the button (assuming you're using HTML5), and then get the attribute for the specific element that was clicked, using var quizid = $(this).data('quizid');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download