Rectangle 27 59

I figured it out. Need to use echo in PHP instead of return.

<?php 
  $output = some_function();
  echo $output;
?>
success: function(data) {
  doSomething(data);
}

How to return data from PHP to a jQuery ajax call - Stack Overflow

jquery ajax
Rectangle 27 666

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 662

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 648

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

This would be a better answer without the highly opinionated order of best practice.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 644

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 644

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 478

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.

There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more ;-)

As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...

Thanks. I am guessing I can insert the contents from $_POST into $postdata if I need to pass same POST params to the requested page?

content
param1=value1&param2=value2&param3=value3
http_build_query($_POST)

Wonderful! I was looking for a way to pass POST data to another page which is achievable by doing $postdata = http_build_query($_POST).

intresting enough this does not work for me at all i been tryiung it for a few hours and all my requets get turned into get querys

What if the parameters value are not strings but arrays or hashes etc ?

http - How to post data in PHP using file_get_contents? - Stack Overfl...

php http http-post file-get-contents
Rectangle 27 467

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.

There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more ;-)

As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...

Thanks. I am guessing I can insert the contents from $_POST into $postdata if I need to pass same POST params to the requested page?

content
param1=value1&param2=value2&param3=value3
http_build_query($_POST)

Wonderful! I was looking for a way to pass POST data to another page which is achievable by doing $postdata = http_build_query($_POST).

intresting enough this does not work for me at all i been tryiung it for a few hours and all my requets get turned into get querys

What if the parameters value are not strings but arrays or hashes etc ?

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

http - How to post data in PHP using file_get_contents? - Stack Overfl...

php http http-post file-get-contents
Rectangle 27 3

Given that only one user_spec row is returned you can use the built in json_encode function:

<?php
$username = "user";
$password = "********";
$hostname = "localhost";    
$dbh = mysql_connect($hostname, $username, $password) 
    or die("Unable to connect to MySQL");

//print "Connected to MySQL<br>";

$selected = mysql_select_db("spec",$dbh) 
    or die("Could not select first_test");

$query = "SELECT * FROM user_spec"; 
$result=mysql_query($query);

echo json_encode(mysql_fetch_assoc($result));

?>

Even if you are using an older version of PHP, you can find a suitable function in the user comments at the json_encode PHP Manual page to use in it's place.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How to return data fetched from MySQL into a php file as JSON? - Stack...

php mysql ajax json combobox
Rectangle 27 3

Given that only one user_spec row is returned you can use the built in json_encode function:

<?php
$username = "user";
$password = "********";
$hostname = "localhost";    
$dbh = mysql_connect($hostname, $username, $password) 
    or die("Unable to connect to MySQL");

//print "Connected to MySQL<br>";

$selected = mysql_select_db("spec",$dbh) 
    or die("Could not select first_test");

$query = "SELECT * FROM user_spec"; 
$result=mysql_query($query);

echo json_encode(mysql_fetch_assoc($result));

?>

Even if you are using an older version of PHP, you can find a suitable function in the user comments at the json_encode PHP Manual page to use in it's place.

How to return data fetched from MySQL into a php file as JSON? - Stack...

php mysql ajax json combobox
Rectangle 27 1

PHP

The reason you are not getting anything in console, is that success callback gets the data that is returned by server, not the data which is sent. Try console.log(jsonData).

On the PHP side, you might be passing data in request payload, thats because your form is type of JSON, not Content-Type: application/x-www-form-urlencoded

To access it use the following instead of $_POST:

$data = file_get_contents('php://input');
$processedData = json_decode($data);
foreach($processedData as $item){
        // do stuff
        echo $item;
}

Hi, thanks for the reply. I can now see the response as follows "{\"data\":[\"vipul\",\"mallapragada\",\"male\",\"-\",\"1994-10-25\"]}". But how do I access the elements in this structure. Could you please help.

javascript - How to post data of selected rows of a dataTable to php c...

javascript php jquery ajax datatables
Rectangle 27 4

AJAX uses UTF-8 encoding. If your data is not in UTF-8 format (such as Windows 1251 or ISO-8859-1) you're going to have trouble.

Specifying a different encoding scheme in the header doesn't convert your data to UTF-8. It just tells the client what to expect.

I start so suspect that as well. The downside for fixing it is I have to convert all my pages, but I think it is a "good business case" doing that.

@Nicsoft: You could try to use utf8_decode() on incoming AJAX requests to convert the input values to ISO-8859-1, though it's better to use UTF8 only, for everything.

nicksoft: Yup. Fortunately MS Office 21010 now allows Word users to save in UTF-8. Before that is was "paste-from-word" hell for many CMS developers.

Yup = with? ;) Is it the same paste from hell when copying code from internet (and using laint-1...) where a hex-editor can fix it?

php - Posting and returning data using jquery corrupts å ä ö - Stack O...

php javascript jquery html encoding
Rectangle 27 63

Firstly you should understand that when using file_get_contents you're fetching the entire string of data into a variable, that variable is stored in the hosts memory.

if that string is greater then the size dedicated to the PHP process then PHP will halt and display the error message above.

The way around this to open the file as a pointer, and then take a chunk at a time, this way if you had a 500MB File you can read the first 1MB of data, do what you will with it, delete that 1MB from the system's memory and replace withthe next MB, This allows you to manage how much data your putting in the memory.

An example if this can be seen below, I will create a function that acts like to node.js

function file_get_contents_chunked($file,$chunk_size,$callback)
{
    try
    {
        $handle = fopen($file, "r");
        $i = 0;
        while (!feof($handle))
        {
            call_user_func_array($callback,array(fread($handle,$chunk_size),&$handle,$i));
            $i++;
        }

        fclose($handle);

    }
    catch(Exception $e)
    {
         trigger_error("file_get_contents_chunked::" . $e->getMessage(),E_USER_NOTICE);
         return false;
    }

    return true;
}
$success = file_get_contents_chunked("my/large/file",4096,function($chunk,&$handle,$iteration){
    /*
        * Do what you will with the {&chunk} here
        * {$handle} is passed in case you want to seek
        ** to different parts of the file
        * {$iteration} is the section fo the file that has been read so
        * ($i * 4096) is your current offset within the file.
    */

});

if(!$success)
{
    //It Failed
}

One of the problems you will find is that your trying to perform regex several times on an extremely large chunk of data, not only that but your regex is built for matching the entire file.

With the above method your regex could become useless as you may only be matching a half set of data, what you should do is revert to the native string functions such as

strpos
substr
trim
explode

for matching the strings, i have added support in the callback so that the handle and current iteration are passed, this will allow you to work with the file directly within your callback, allowing you to use functions like fseek, ftruncate and fwrite for instance.

The way your building your string manipulation is not efficient what so ever, and using the proposed method above is by far a much better way.

thank god for a sane answer, +1

thank you so much for such detailed answer! I am a beginner and answers like yours motivate me to work harder. Thanks again.

just replace fread by fgets and 4096 with 1024 for line by line processing.

file_get_contents => PHP Fatal error: Allowed memory exhausted - Stack...

php
Rectangle 27 63

Firstly you should understand that when using file_get_contents you're fetching the entire string of data into a variable, that variable is stored in the hosts memory.

if that string is greater then the size dedicated to the PHP process then PHP will halt and display the error message above.

The way around this to open the file as a pointer, and then take a chunk at a time, this way if you had a 500MB File you can read the first 1MB of data, do what you will with it, delete that 1MB from the system's memory and replace withthe next MB, This allows you to manage how much data your putting in the memory.

An example if this can be seen below, I will create a function that acts like to node.js

function file_get_contents_chunked($file,$chunk_size,$callback)
{
    try
    {
        $handle = fopen($file, "r");
        $i = 0;
        while (!feof($handle))
        {
            call_user_func_array($callback,array(fread($handle,$chunk_size),&$handle,$i));
            $i++;
        }

        fclose($handle);

    }
    catch(Exception $e)
    {
         trigger_error("file_get_contents_chunked::" . $e->getMessage(),E_USER_NOTICE);
         return false;
    }

    return true;
}
$success = file_get_contents_chunked("my/large/file",4096,function($chunk,&$handle,$iteration){
    /*
        * Do what you will with the {&chunk} here
        * {$handle} is passed in case you want to seek
        ** to different parts of the file
        * {$iteration} is the section fo the file that has been read so
        * ($i * 4096) is your current offset within the file.
    */

});

if(!$success)
{
    //It Failed
}

One of the problems you will find is that your trying to perform regex several times on an extremely large chunk of data, not only that but your regex is built for matching the entire file.

With the above method your regex could become useless as you may only be matching a half set of data, what you should do is revert to the native string functions such as

strpos
substr
trim
explode

for matching the strings, i have added support in the callback so that the handle and current iteration are passed, this will allow you to work with the file directly within your callback, allowing you to use functions like fseek, ftruncate and fwrite for instance.

The way your building your string manipulation is not efficient what so ever, and using the proposed method above is by far a much better way.

thank god for a sane answer, +1

thank you so much for such detailed answer! I am a beginner and answers like yours motivate me to work harder. Thanks again.

just replace fread by fgets and 4096 with 1024 for line by line processing.

file_get_contents => PHP Fatal error: Allowed memory exhausted - Stack...

php
Rectangle 27 1

PHP

$.ajax({
          type: "POST",
          url: "coordsave.php?username=<?php echo(htmlspecialchars(isset($_GET['username']) ? $_GET['username'] : '', ENT_QUOTES, 'UTF-8'));?>",
          data: {x: pos_x, y: pos_y,}
        }).done(function( msg ) {
          alert( "Data Saved: " + msg );
        });
  }
header('Content-Type: text/plain; charset=utf-8');

$x = isset($_POST["x"]) or die('Param x required with POST');
$y = isset($_POST["y"]) or die('Param y required with POST');
$id = isset($_GET["username"]) or die('Param username required with GET');

//Setup our Query
$sql = sprintf(
    "UPDATE table_name SET x2='%s', y2='%s' WHERE user_uname='%s'",
    mysql_real_escape_string($x),
    mysql_real_escape_string($y),
    mysql_real_escape_string($id)
);

//Execute our Query
if (mysql_query($sql)) {
    echo "success $x $y";
} else {
    die("Error updating Coords :" . mysql_error());   
}

However, all mysql_* functions are officially deprecated, so you should use PDO or Mysqli.

javascript - Putting a $_GET variable in ajax function - Stack Overflo...

javascript php jquery html ajax
Rectangle 27 1

you need to change your code a little bit. no need to return data, just echo true or echo false from your controller. Hope you will get your desired result.

php - How to send/return data/value from CI_Controller to AJAX - Stack...

php ajax codeigniter web
Rectangle 27 15

An alternative, you can also use fopen

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

For some reason, this worked for me, but the PHP official example did not. +1 for the toto=1&tata=2 as well. I didn't use the fopen, however.

@i We don't call people 'noob' here. This is a friendly warning against such.

Daedalus should have told Icarus that he was a noob angel, maybe then he could have reached the youth.

http - How to post data in PHP using file_get_contents? - Stack Overfl...

php http http-post file-get-contents
Rectangle 27 15

An alternative, you can also use fopen

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

For some reason, this worked for me, but the PHP official example did not. +1 for the toto=1&tata=2 as well. I didn't use the fopen, however.

@i We don't call people 'noob' here. This is a friendly warning against such.

http - How to post data in PHP using file_get_contents? - Stack Overfl...

php http http-post file-get-contents
Rectangle 27 2

I had same problem. it happen because javascript expect json data type in returning data. but if you use echo or print in your php this situation occur. if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.

php - Ajax success event not working - Stack Overflow

php jquery ajax
Rectangle 27 2

That's because ajax expects json response and the query.php script does not return json. If you add error callback to your ajax you will see that it's triggered.

$.ajax({
            type: 'POST',
            url: 'query.php',
            data: key,
            dataType: 'json',
            success: function(msg){
                $('#show').html(msg);
            },
            error: function (err) {
                console.log(err);
            }

To fix this in your query.php you should echo json_encoded string like this

echo json_encode(array('message' => ''));

And then in your success callback you can access the message like this

success: function(response){
            $('#show').html(response.message);
}

Update: okay if your $db->query method returns json as string then you can do the following

$records = $db->query("SELECT * FROM m_cinfo LEFT OUTER JOIN m_jinfo ON m_cinfo.cinfo_id=m_jinfo.cinfo_id where fullName LIKE '%$str%'");

$decoded = json_decode($records, true);

echo json_encode($decoded);

Note that your query is vulnerable to SQL injection . You should escape the $str variable or use prepared statements. For example if somebody enters this string in the search field it could drop your 'm_cinfo' table

somestring'; DROP TABLE m_cinfo; #
                                 ^ this will comment the rest of your query

on top of that it should be $_POST['command'] rather than $_SESSION['command'] as command is part of the POST-Request-Body

Ah yes, you're correct. I didn't even bother to look at code above since OP said that the response is being returned.

Thanks that worked. Now if i want to use the data from my db what should i do? i get json like this: [{"cinfo_id":"1","fullName":" ","phone":"09151234576","mail":"ali.Alavi@gmail.com","description":" ","jinfo_id":"1","jobTitle":"","jobName":"","city":""}] and echo that but when i say $('#show').html(msg.fullName); for example, nothing would show.

$db->query('/**/'')

php - Jquery/Ajax return data but doesn't alert - Stack Overflow

php jquery ajax