-1

I am currently using AJAX to pass the PHP output to JavaScript, but I want to pass only one of the PHP variables to JavaScript and I don't know how to obtain it from the general this.responseText property.

I've tried searching Stackoverflow/Google but most questions/answers talk about returning the entire PHP output. What I want is not the entire PHP output (I've got that settled already), but one variable from the PHP code. This is the PHP output I have now:

    echo $hex;
    echo '<br>';
    echo 'R: ' . $r . ' G: ' . $g . ' B: ' . $b;

What I want is to get just the $hex variable. How do I obtain it?

EDIT To those who marked it as a duplicate:
I have read the replies to that question, but I felt like it didn't exactly answer my question, so I posted a new one. In the Ajax example, there is only 1 output (42) and it is in this.responseText. I am outputting a couple of sentences using this.responseText but I also want one of the variables in it for a separate javascript function. How do I extract it from this.responseText?

freesushi
  • 69
  • 7

2 Answers2

1

You mean to set it as a javascript variable?

<?php
    echo '<script>';
    echo 'var Hex = ' . $hex . ';';
    echo '</script>';
?>
Vladimir Ramik
  • 1,920
  • 2
  • 13
  • 23
  • 1
    This is not a recommended way. This is a bad way of doing this. – Loko Mar 17 '15 at 09:18
  • Can you please clarify what's the issue with passing php data to javascript or provide a better way please? Always considered this a default for passing javascript data. – Vladimir Ramik Mar 17 '15 at 09:28
  • Using **Ajax** is the way to go. – Loko Mar 17 '15 at 09:38
  • Im not going to post an answer myself. Since this question is a duplicate. http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript – Loko Mar 17 '15 at 09:43
  • I have read the replies to that question, but I felt like it didn't exactly answer my question, so I posted a new one. In the Ajax example, there is only 1 output (42) and it is in this.responseText. I am outputting a couple of sentences using this.responseText but I also want one of the variables in it for a separate javascript function. How do I extract it from this.responseText? – freesushi Mar 19 '15 at 02:44
0

If you want to return only $hex if it is a ajax request and render the other variable if its a normal page view then you could place it in a if statement like

/* AJAX check  */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    echo $hex;
} else {
    echo $hex;
    echo '<br>';
    echo 'R: ' . $r . ' G: ' . $g . ' B: ' . $b;
}
Raheel
  • 8,716
  • 9
  • 60
  • 102