Rectangle 27 1

As you say you don't have problem buying new server's, I suggest the best way would be to get a new server deploy you application there first. Follow below steps: 1. Add any certificates if required to this new server and Test your application with new settings. 2. Shutdown your old server and assign it's IP to the new Server, the downtime would be the same as much your server takes to shutdown and you assigning the new IP to the new Server. 3. If you see the new Deploy is not working you can always revert back by following the step 2 again. Regarding your database backup you would have to set a backup schedule.

I'm sorry, but point nr.2 is exactly 180 degrees in contradiction with the definition of "zero downtime"

c# - Is it possible to deploy an enterprise ASP.NET application and SQ...

c# asp.net sql-server iis deployment
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 16

I switched from Mongrel Cluster to Passenger two weeks ago (Debian Linux Server). I didn't look back for a second. Passenger is probably the easiest way to get your new server up and running. Performance and reliability are reasonable too.

Personally, I like to spend my time working on exciting new Rails projects rather than dealing with deployment issues - Passenger enables me to do exactly that. However, Mongrel or something else may still be preferable if you have some kind special requirements (doesn't apply for most products).

+1 for Passenger -- super easy deployment as just as fast (sometimes faster for my app) as Mongrel used to be. Wonderful!

another +1 for passenger. I struggled for a week trying to set up a pack of mongrels on debian, but finished a deployment setup in an afternoon with passenger.

ruby - Best practices for new Rails deployments on Linux? - Stack Over...

ruby-on-rails ruby linux deployment release-management
Rectangle 27 19

When I try to upload my app to the Chrome Web Store, I get this error:...

This behaviour seems to happen especially if you're logged in with more than one Google Account at the same time.

Google recommends logging out and back in with the account you want to use to publish your app or extension.

This error occasionally occurs if you've been logged into the Chrome Web Store for a long time. If you sign out of your Google Account and then sign back in, you should be able to upload your app.

Didn't worked for me. Made two attempts still not working for me getting the message as below again. Chrome Web Store system error, please try again later.

Thanks ... finally it worked for me after clearing browser cache and browser restart.

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

Chrome extension update - Chrome Web Store system error - Stack Overfl...

google-chrome-extension
Rectangle 27 4

The reasons why you would get a new session ID are

  • You cleared the session ID cookie (typically named PHPSESSID)
  • You visited a page that called session_regenerate_id() (unlikely)
  • Your session hit the max lifetime and was garbage collected. This is a distinct possibility if banana.com has a lot of visitors, because garbage is collected randomly when PHP is invoked
  • session_id() was invoked with a different session
  • Check out the session files on the server. They're simple text so you can open them and see what's inside. Make sure your session exists.
  • Check php.ini for a short session lifetime.
  • Load sessions into something else and see if continues. Using a MySQL/memcached system with a custom session handler could reveal issues.

Why does the session id change when requesting through ajax in php? - ...

php ajax session session-cookies
Rectangle 27 13

The practical case where you will have a problem is that the HTTP GET is often retried in the event of a failure by the HTTP implementation. So you can in real life get situations where the same GET is received multiple times by the server. If your update is idempotent (which yours is), then there will be no problem, but if it's not idempotent (like adding some value to an amount for example), then you could get multiple (undesired) updates.

Yes correct - I was trying to make a call that was not idempotent and I guess I had one that still was. I just updated my example with 'AddToTotalAmount=10' to make the call not idempotent.

Is the re-trying of the GET call the only main pitfall you can see? Great one though and still justification enough, just wondering if there are any more reasons.

Yes, that's really the only one as far as I know. If you look at the HTTP implementations that's really the only difference between a GET and the other HTTP requests.

One last question - is the GET automatically retried on failure (like built in functionality), or you were just saying in practice developers often work in a programatic re-try?

It depends on the HTTP client implementation. I wrote the Oakland Software implementation and it automatically retried. I think the Sun Java one and the Apache HTTPClient do as well. It's not something the developers worry about.

rest - Why is using a HTTP GET to update state on the server in a REST...

http rest post get restful-architecture
Rectangle 27 9

Preparation step 1: Install gettext and the locales on the server

I know this is an old question, but I feel that the answers are lacking a more hands-on approach from start to finish. This is what I did to get translation working using PHP's gettext library and Poedit without using any additional PHP libraries on a Debian server:

I am not sure how this is done with other operating systems, but for Debian, you do:

sudo apt-get install gettext
sudo dpkg-reconfigure locales

Edit: I assumed Ubuntu would be the same as Debian, but apparently it's slightly different. See this page for instructions for installing locales on Ubuntu.

Make sure you select all of the locales that you want to use. You should then see something like:

Generating locales (this might take a while)...
  en_US.UTF-8... done
  es_MX.UTF-8... done
  fr_FR.UTF-8... done
  zh_CN.UTF-8... done
Generation complete.

Note: Make sure you select the right variants and character encodings (most likely UTF-8) for each language. If you install es_MX.UTF-8 and try to use es_ES.UTF-8 or es_MX.ISO-8859-1 it won't work.

Poedit is available from the software repository for most Linux operating systems. For Debian-based, just execute:

sudo apt-get install poedit

Ok, now you're ready to get started coding. I wrote the following gettext() wrapper function to translate both singular and plurals:

function __($text, $plural=null, $number=null) {
    if (!isset($plural)) {
        return _($text);
    }
    return ngettext($text, $plural, $number);
}
// Singular
echo __('Hello world');

// Plural
$exp = 3;
printf(
    __(
        'Your account will expire in %d day',
        'Your account will expire in %d days',
        $exp
    ),
    $exp
);

This will work for all languages, not only languages where plural is anything where n != 1 - this includes languages with multiple plural types.

You can also add translator notes like this:

/** NOTE: The name Coconut Hotel is a brand name and shouldn't be 
 translated.
*/
echo __('Welcome to Coconut Hotel');

You can change the text from NOTE to whatever you want, but you will have to alter it in the shell script below. Important: The translators note must be part of a comment on the line immediately preceding the __() function or it won't be picked up when we scan the PHP files for translatable strings.

// Warning! THIS WILL NOT WORK!
/* NOTE: This translator's note will not be picked up because it is
not immediately preceding the __() function. */
printf(
    __(
        'Your account will expire in %d day',
        'Your account will expire in %d days',
        $exp
    ),
    $exp
);
// Warning! THIS WILL NOT WORK!

After you are ready to send the strings off to the translators, save the following as a shell script (e.g. update.sh) in your application's root directory:

#!/bin/sh
find . -iname "*.php" | xargs xgettext --add-comments=NOTE --keyword=__:1,2 --keyword=__ --from-code=UTF-8 -o i18n.pot
find . -name '*.po' | xargs -I{} msgmerge -U {} i18n.pot
cd /path/to/script && sh update.sh

This will recursively scan for all PHP files in that directory and create a .pot file (I called it i18n.pot, but feel free to name it whatever you like) and update any existing .po files it finds with the new strings.

We then need to create the directories that all the locale files will be stored, one for each locale. They need to be of the format ./locale/{locale}/LC_MESSAGES. For example:

cd /path/to/your/project
mkdir -p ./locale/en_US.UTF-8/LC_MESSAGES
mkdir -p ./locale/es_MX.UTF-8/LC_MESSAGES
# ...etc.

You need to decide on a text domain to use. This can be anything you want, but the script will look for a file called {yourTextDomain}.mo within the LC_MESSAGES folder for that language. Put the following in your PHP script:

define('TEXT_DOMAIN', 'yourdomain');
bindtextdomain(TEXT_DOMAIN, __DIR__.'/locale');
textdomain(TEXT_DOMAIN);
bind_textdomain_codeset(TEXT_DOMAIN, 'UTF-8');
$lang = 'es_MX.UTF-8'; // Change this to the language you want to use
if (setlocale(LC_ALL, $lang) === false) {
    throw new Exception("Server error: The $lang locale is not installed");
}
putenv('LC_ALL='.$lang));

Initially, you send the .pot file generated by the script above to the translators. They then open Poedit and click on File > New from POT/PO file. When they save it, they need to save it as {yourTextDomain}.po. The {yourTextDomain} needs to be exactly the same as the text domain you have in your PHP script. When they save it, it will automatically create both the .po file and the .mo file. Both of these need to be saved in that language's LC_MESSAGES directory when they are done translating.

Now when you update the strings in your PHP file, just re-execute the shell script and send the newly updated .po files to the translators. They then translate the strings and both the .po and .mo files need to be re-uploaded.

internationalization - Best way to internationalize simple PHP website...

php internationalization multilingual
Rectangle 27 6

Aborting a GET request

Using the :content_cb option, you can provide a callback function to get() that will be executed for each chunk of response content received from the server. You can set* the chunk size (in bytes) using the :read_size_hint option. These options are documented in LWP::UserAgent (get() in WWW::Mechanize is just an overloaded version of the same method in LWP::UserAgent).

The following request will be aborted after reading 1024 bytes of response content:

use WWW::Mechanize;

sub callback {
    my ($data, $response, $protocol) = @_;

    die "Too much data";
}

my $mech = WWW::Mechanize->new;

my $url = 'http://www.example.com';

$mech->get($url, ':content_cb' => \&callback, ':read_size_hint' => 1024);

print $mech->response()->header('X-Died');
Too much data at ./mechanize line 12.

Note that the die in the callback does not cause the program itself to die; it simply sets the X-Died header in the response object. You can add the appropriate logic to your callback to determine under what conditions a request should be aborted.

Based on your comments, it sounds like what you really want is to never send a request in the first place if the content is too large. This is quite different from aborting a GET request midway through, since you can fetch the Content-Length header with a HEAD request and perform different actions based on the value:

my @urls = qw(http://www.example.com http://www.google.com);

foreach my $url (@urls) {
    $mech->head($url);

    if ($mech->success) {
        my $length = $mech->response()->header('Content-Length') // 0;

        next if $length > 1024;

        $mech->get($url);
    }
}

Note that according to the HTTP spec, applications should set the Content-Length header. This does not mean that they will (hence the default value of 0 in my code example).

* According to the documentation, the "protocol module which will try to read data from the server in chunks of this size," but I don't think it's guaranteed.

Thanks, I will try this. Since I am going through a list of URLs, I would like to skip to the next URL in the list when I observe that the size of HTTP response (Content-Length response header) is greater than some threshold. Is it possible to go to the next URL in the list instead of using a callback function? I would just need to do something like next() in the loop to cancel the current request and read the next URL from the list.

Cancelling a request midway (your original question) and just not making a request in the first place are totally different. You can use the HEAD method to just get the headers for each URL and check the Content-Length. If too large, skip to the next URL; otherwise, send a GET request.

Cancel Download using WWW::Mechanize in Perl - Stack Overflow

perl www-mechanize
Rectangle 27 6

Aborting a GET request

Using the :content_cb option, you can provide a callback function to get() that will be executed for each chunk of response content received from the server. You can set* the chunk size (in bytes) using the :read_size_hint option. These options are documented in LWP::UserAgent (get() in WWW::Mechanize is just an overloaded version of the same method in LWP::UserAgent).

The following request will be aborted after reading 1024 bytes of response content:

use WWW::Mechanize;

sub callback {
    my ($data, $response, $protocol) = @_;

    die "Too much data";
}

my $mech = WWW::Mechanize->new;

my $url = 'http://www.example.com';

$mech->get($url, ':content_cb' => \&callback, ':read_size_hint' => 1024);

print $mech->response()->header('X-Died');
Too much data at ./mechanize line 12.

Note that the die in the callback does not cause the program itself to die; it simply sets the X-Died header in the response object. You can add the appropriate logic to your callback to determine under what conditions a request should be aborted.

Based on your comments, it sounds like what you really want is to never send a request in the first place if the content is too large. This is quite different from aborting a GET request midway through, since you can fetch the Content-Length header with a HEAD request and perform different actions based on the value:

my @urls = qw(http://www.example.com http://www.google.com);

foreach my $url (@urls) {
    $mech->head($url);

    if ($mech->success) {
        my $length = $mech->response()->header('Content-Length') // 0;

        next if $length > 1024;

        $mech->get($url);
    }
}

Note that according to the HTTP spec, applications should set the Content-Length header. This does not mean that they will (hence the default value of 0 in my code example).

* According to the documentation, the "protocol module which will try to read data from the server in chunks of this size," but I don't think it's guaranteed.

Thanks, I will try this. Since I am going through a list of URLs, I would like to skip to the next URL in the list when I observe that the size of HTTP response (Content-Length response header) is greater than some threshold. Is it possible to go to the next URL in the list instead of using a callback function? I would just need to do something like next() in the loop to cancel the current request and read the next URL from the list.

Cancelling a request midway (your original question) and just not making a request in the first place are totally different. You can use the HEAD method to just get the headers for each URL and check the Content-Length. If too large, skip to the next URL; otherwise, send a GET request.

Cancel Download using WWW::Mechanize in Perl - Stack Overflow

perl www-mechanize
Rectangle 27 11

The user should be redirected to the authentication server again and get a new token (JWT), one that is specifically targeted for example2.com. This is how OpenID Connect and any other cross-domain federated SSO protocol works.

But without the user having to resend the authentication credentials (username/password for example) since it's SSO, right? So how is it done? Should the authentication server set a standard cookie on the user the first time, so it can automatically authenticate him when this user is back from a new domain?

Single sign-on flow using JWT for cross domain authentication - Stack ...

authentication single-sign-on jwt openid-connect
Rectangle 27 19

My application server (jBoss, Glassfish..) located in Iraq, Syria, wha...

Questions from the top of my head since that time I gone crazy with jacoco.

Yes. You have to use jacoco agent that runs in mode output=tcpserver, jacoco ant lib. Basically two jars. This will give you 99% success.

You append a string

-javaagent:[your_path]/jacocoagent.jar=destfile=/jacoco.exec,output=tcpserver,address=*

to your application server JAVA_OPTS and restart it. In this string only [your_path] have to be replaced with the path to jacocoagent.jar, stored(store it!) on your VM where app server runs. Since that time you start app server, all applications that are deployed will be dynamically monitored and their activity (meaning code usage) will be ready for you to get in jacocos .exec format by tcl request.

Yes, for that purpose you need jacocoant.jar and ant build script located in your jenkins workspace.

That's not right, jacoco maven plugin can collect unit test data and some integration tests data(see Arquillian Jacoco), but if you have for example rest assured tests as a separated build in jenkins, and want to show multi-module coverage, I can't see how maven plugin can help you.

.exec

No, sonar does, but not jacoco. When you do mvn sonar:sonar path to classes comes into play.

jacoco.xml
<project name="Jacoco library to collect code coverage remotely" xmlns:jacoco="antlib:org.jacoco.ant">
    <property name="jacoco.port" value="6300"/>
    <property name="jacocoReportFile" location="${workspace}/it-jacoco.exec"/>

    <taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
        <classpath path="${workspace}/tools/jacoco/jacocoant.jar"/>
    </taskdef>

    <target name="jacocoReport">
            <jacoco:dump address="${jacoco.host}" port="${jacoco.port}" dump="true" reset="true" destfile="${jacocoReportFile}" append="false"/>
    </target>

    <target name="jacocoReset">
            <jacoco:dump address="${jacoco.host}" port="${jacoco.port}" reset="true" destfile="${jacocoReportFile}" append="false"/>
        <delete file="${jacocoReportFile}"/>
    </target>
</project>

Two mandatory params you should pass when invoking this script -Dworkspace=$WORKSPACE use it to point to your jenkins workspace and -Djacoco.host=yourappserver.com host without http://

jacocoant.jar

Did you start your app server with jacocoagent.jar?

Did you put ant script and jacocoant.jar in your jenkins workspace?

If yes the last step is to configure a jenkins build. Here is the strategy:

jacocoReset
jacocoReport
it-jacoco.exec

Look at the screenshot, I also have ant installed in my workspace in $WORKSPACE/tools/ant dir, but you can use one that is installed in your jenkins.

Maven sonar:sonar will do the job (don't forget to configure it), point it to main pom.xml so it will run through all modules. Use sonar.jacoco.itReportPath=$WORKSPACE/it-jacoco.exec parameter to tell sonar where your integration test report is located. Every time it will analyse new module classes, it will look for information about coverage in it-jacoco.exec.

mvn sonar:sonar
clean
sonar.dynamicAnalysis=reuseReports

How to configure multi-module Maven + Sonar + JaCoCo to give merged co...

maven code-coverage sonarqube jacoco
Rectangle 27 3

To get the last day you can do this:

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,'2014-08-12')+1,0))
select @New_date = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@date)+1,0))
EOMONTH()

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

How to get last date of month SQL Server 2008 - Stack Overflow

sql sql-server sql-server-2008
Rectangle 27 55

Neither of these answers get to the core reason refresh tokens exist. Obviously, you can always get a new access-token/refresh-token pair by sending your client credentials to the auth server - thats how you get them in the first place.

So the sole purpose of the refresh token is to limit the use of the client credentials being sent over the wire to the auth service. The shorter the ttl of the access-token, the more often the client credentials will have to be used to obtain a new access-token, and therefore the more opportunities attackers have to compromise the client credentials (although this may be super difficult anyway if asymmetric encryption is being used to send them). So if you have a single-use refresh-token, you can make the ttl of access-tokens arbitrarily small without compromising the client credentials.

This is interesting as in Google's case when you ask for a refresh token, you also send over the client id and client secret. So you're compromising every hour anyway.

Alexander, actually the shorter the ttl, the more often the client will have to get a new access-token (which requires using the client credentials). So I do in fact mean 'shorter' there. I'll add a note in to clarify.

"sole purpose" - doesn't wash. Making the TTL of the access-token as long as that of the imagined refresh-token will achieve just the same.

Since the standard requires that the client credentials be sent along with the refresh token, the premise of this answer is simply false. "Because refresh tokens are typically long-lasting credentials used to request additional access tokens... the client MUST authenticate with the authorization server." Also see the comment by @Rots.

A) I think you are mixing up client secrets and user secrets. The client secret is never sent from the user device, only from the accessing backend application to the data providing backend application. B) The oAuth server that allows for password grant for a Public Client (a client that cannot keep a client secret such as a native or javascript app) will also provide a refresh-token grant for that public client, thus you do not need to send a client secret when refreshing your token. C) The refresh-token provides the backend with a "hart-beat" when to check the validity of the user!

security - Why Does OAuth v2 Have Both Access and Refresh Tokens? - St...

security oauth access-token refresh-token
Rectangle 27 60

Did your server use the new registration ID returned by the GCM server to your app? I had this problem, if trying to send a message to registration IDs that are given out by the old C2DM server.

And also double check the Sender ID and API_KEY, they must match or else you will get that MismatchSenderId error. In the Google API Console, look at the URL of your project:

https://code.google.com/apis/console/#project:xxxxxxxxxxx

The xxxxxxxxx is the project ID, which is the sender ID.

And make sure the API Key belongs to 'Key for server apps (with IP locking)'

I have a huge doubt here.Is it possible to deploy my application to load of other cellphones with only one SERIALID?

Have you looked at the GCM architectural overview developer.android.com/guide/google/gcm/gcm.html? Every Android phones that is using your app will register with GCM with your app's Sender ID, and they will receive a unique GCM registration ID, that you have to store on your server. If you wish to send a message to all of your users, you need to go through all of those registration ids.

This is really silly, but it works. The Project ID listed in the page on the dashboard is a named id that I got to pick, however you must use the numeric ID from the url which is very confusing.

This information may be out of date. Now you should use your project NUMBER

android - Why do I get "MismatchSenderId" from GCM server side? - Stac...

android push-notification google-cloud-messaging
Rectangle 27 1

You may get more success if you do a "search" for the runtime env from the preferences screen instead of hitting "add" - see this demo on youtube. http://www.youtube.com/watch?v=EOkN5IPoJVs&playnext_from=TL&videos=rVnITzSU2Z8 - When you hit search, you are prompted to point to the tomcat directory and then it SHOULD add it as a server runtime environment. Unfortunately for me, that is not the case (I get "no new server runtime environments were found") But you might have more success.

java - Apache Tomcat Not Showing in Eclipse Server Runtime Environment...

java eclipse tomcat
Rectangle 27 7

There is no way to get the user location using PHP since it's running on the server side. You can get the user location using javascript through the browser.

Here is an example. In this example I separated the code in two files. One for processing and storing the information using PHP (geocoordinates.php) and another one (HTML) for collecting the geocoding informantion (index.html), index.html.

<?php

if(isset($_POST['lat'], $_POST['lng'])) {
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];

    $url = sprintf("https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s", $lat, $lng);

    $content = file_get_contents($url); // get json content

    $metadata = json_decode($content, true); //json decoder

    if(count($metadata['results']) > 0) {
        // for format example look at url
        // https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452
        $result = $metadata['results'][0];

        // save it in db for further use
        echo $result['formatted_address'];

    }
    else {
        // no results returned
    }
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Geocoding Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script>
  function getLocation() {
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(savePosition, positionError, {timeout:10000});
      } else {
          //Geolocation is not supported by this browser
      }
  }

  // handle the error here
  function positionError(error) {
      var errorCode = error.code;
      var message = error.message;

      alert(message);
  }

  function savePosition(position) {
            $.post("geocoordinates.php", {lat: position.coords.latitude, lng: position.coords.longitude});
  }
  </script>
</head>
<body>
    <button onclick="getLocation();">Get My Location</button>
</body>
</html>

Keep in mind that in this example the once the user clicks "Get My Location" the browser will prompt the user to allow the geolocation. You could also call the getLocation function once the page loads, but the browser will always ask for the user's permission

Yoel, the browser indicates that it's tracking my location, but I'm not able to echo the results of the location altogether or the $lng or $lat variables separately. Do you know what's up?

@pol_guy I've just tried and experienced the same issue. I updated the answer with an error callback in case it fails to acquire your position. Apparently this is an know issue, check out stackoverflow.com/a/3885172/4114033

Nicely done +1. Fast and pretty reliable. Off by 2 houses in my test. Thanks!

Can it work on localhost? I try doing that but its not working

javascript - How to get a User's Current Location Using Google Geocode...

javascript php geolocation google-api reverse-geocoding