Ensuring JSON data protection when sending Ajax requests in JavaScript (for(;;);)

After extensive research, I have not been able to find the answer I'm looking for despite similar questions being asked.

My query concerns the usage of for(;;); while(1); before an Ajax response outputs a JSON string.

I am curious about how this technique works and would like to implement it similarly to popular sites such as Facebook.

In the ajax.php file, I believe the following needs to be done:

ajax.php

$arr = array("value" => "something", "moreValues" => "moreSomething");
die("for(;;);".json_encode($arr));

The response will look like this:

for(;;);{"value":"something","moreValues":"moreSomething"}

What should one do with this string? Should we remove for(;;); with a substr or something and then use JSON.parse(string)? (If so, why include for(;;); in the response at all?)

Furthermore, how does this approach enhance security and guard against potential infinite loops with the for(;;); statement if something goes wrong?

I feel like there is a missing piece to this puzzle, and I am yet to find a clear example illustrating how to execute this. Any guidance or examples demonstrating the implementation in code would be greatly appreciated! Thanks!

Answer №1

I managed to resolve this issue using a simple JavaScript solution, which can be implemented as follows:

$.ajax({
    url: mylink',
    type: 'post',
    complete: function(){
        self.removeAttr('disabled');    
        removeLoading();
    },
    success: function(data){
        s1 = new handleData(data);
        if(s1.getError()){
            return setMsgPopup(s1.getError(),1);
        }

        arr = s1.getResult();

    }
});

Below is the handleData class structure:

var handleData = (function(){
    var result=false;
    var error=false;
    var objSize=0;

    var handleData = function(data){
        fixedData = data;
        arr = data.split('for (;;);'); 

        if(!arr[1]){
            this.result = false;
        }else{
            fixedData = arr[1];
        }

        try{
            this.result = JSON.parse(fixedData);
        }catch(e){
            this.result = false;
        }

        if(this.result){
            if(this.result['t'] == undefined){
                if(this.result['error'] != undefined)
                    this.setError(this.result['msg']);
                else
                    this.setError("An error have occured.");
            }
            if(this.result['error'] != undefined)
                this.setError(this.result['msg']);

            if(this.result['t'])
                delete this.result['t'];            
        }else
            this.setError("An error have occured.");

        this.setSize();
    };

    handleData.prototype.setError = function(msgError){
        this.error = msgError;
    };

    handleData.prototype.getError = function(){
        return this.error;
    };

    handleData.prototype.getResult = function(){
        return this.result;
    };

    handleData.prototype.setSize = function(){
        if(!this.result)
            return;

        var size =0;
        for(key in this.result) {
            if(this.result.hasOwnProperty(key))
                size++;
        }
        this.objSize = size;
    };

    handleData.prototype.getSize = function(){
        return this.objSize;
    };

    return handleData;
})();

It's worth noting that this code is quite outdated like the original question itself. There are probably more efficient ways to handle this now, but at the time I applied this fix.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine if a cell is editable within the `renderEditCell` function by using MUI

I am working with a MUI data grid that contains different cell types. I am currently seeking a way to implement user permission-based editing for cells in the grid. However, I only want the permission testing to occur when a user attempts to edit a cell, r ...

Organizing a NodeJS module - properties and functions

I've been struggling to structure my NodeJS application with modules, and after hours of searching, I haven't found a definitive answer. Let's say I want to create a "user" module for creating new users in my code: var newUser = new User(); ...

Having difficulty retrieving model values from the angular ui modal dialog

Being only on my second day in the world of Angular, I am trying to navigate around Angular UI and build my first modal dialog. The modal dialog displays properly, but I'm encountering an issue with using models within it. You can view my demo on Plun ...

Having difficulty sending data to a controller through AJAX in Code Igniter. Can anyone help troubleshoot

I recently started learning PHP OOP and am currently using the Code Igniter framework. I encountered some difficulties in sending data to the controller using AJAX, so I attempted a simple test to check if AJAX was functioning properly, but unfortunately, ...

Exploring the art of reading and writing to a file with JavaScript and NodeJS

I am currently working on creating a function that will scan a file and remove all content below a specific line before adding new lines to the file. So far, I have successfully read the file and identified the target line: function analyze() { lineRe ...

How can we update the form builder or form group in Angular 2 when making changes to the existing data in a table? I'm a bit confused on how to implement router

<tr *ngFor="let row of categories "> <td>{{row.categoryName}}</td> <td>{{row.visible}}</td> <td>{{row.instanceNumber}}</td> <td> <a class="btn btn-info btn-fill " [routerLink]="['/con ...

Challenges encountered while formatting Json strings for WCF service transmission

I need assistance in connecting a JavaScript application to a WCF service. The WCF Service I have includes the following method: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFor ...

Having trouble getting Vue.js data to show up on the screen. I'm attempting to show a list of todos, but all that

I'm currently working on my App.vue file where I have set up the data for a todo list. However, despite creating an array of todos and attempting to display them, nothing is showing up on the screen. I'm at a standstill and could really use some ...

Display an alert message using alert() if duplicate data is submitted through ajax

I'm using a form and jQuery to submit the form via AJAX. $("form#form").submit(function (event) { //submitting vendor name event.preventDefault(); var formData = new FormData($(this)[0]); //validation for duplicates goes here ...

Express.js Server Side Rendering - GET request for '/json/version/'

I have a running express server that pre-renders my react application. The routes file matches the HomeContainer to the base route / and all other routes match to the page not found. import HomeContainer from 'containers/home-container/home-container ...

Can you explain the functionality of the DataTable drawCallback feature?

I'm currently facing an issue where CSS is not being applied to all cells in a DataTable based on their values when using drawCallback(). While the CSS gets applied to some cells, it's inconsistent. You can check out the JsFiddle of my problem he ...

What steps can be taken in Next.js to display a 404 page when data is not retrieved from the Wordpress admin?

I am working with JSON data that looks like this: [ { "taxonomy_slug": "product_cat", "taxonomy_name": "Categories", "frontend_slug": "product-category" }, { ...

The function $(...) does not recognize tablesorter

Currently, I am encountering issues with the tablesorter plugin as my system is unable to recognize the existing function. It is unclear whether there might be a conflict with other JavaScript files, especially since I am implementing changes within a Word ...

Web browser local storage

Looking to store the value of an input text box in local storage when a button is submitted <html> <body action="Servlet.do" > <input type="text" name="a"/> <button type="submit"></button> </body> </html> Any sug ...

Encountering a Parsing JSON Issue

When working with JSON data from Facebook's Graph request, I decided to utilize an NSMutableArray named json to store the results in JSON format. My goal was to parse this information and display it on a table. To achieve this, I initialized an NSDict ...

Using Angular 2 to trigger an event when a native DOM element is loaded

I am working towards my main objective of having a textarea element automatically focused upon creation. I recently came up with an idea to use e.target.focus() on the onload event. It would look something like this: <textarea rows="8" col="60" (load)= ...

Tips for dynamically incorporating input forms within AngularJS

I am trying to dynamically change the form inputs using ng-bind-html. However, I am only able to display the label and not the text box on the DOM. The content inside ctrl.content will depend on the values received from the server. Important Note: The ...

Converting a JSON object into a format suitable for transmission through AJAX requests

I am attempting to transmit data in a JSobject via AJAX using jQuery. Below is the json object: var cookieData = { 'land' : document.URL, 'ref' : document.referrer }; The object is then stored in a cookie... throu ...

Tips for properly storing "u**" in a JSON file using Python

Here's a scenario involving a dictionary: data = {"data": "\u512b"} When trying to convert it to json: import json print json.dumps(data) The result obtained is:{"a":"\\u512b"} How can I achieve the exact output of {"a":"\u512b ...

Button to close Jquery Dialog

I've set up a custom alert UI using jQuery UI, but I'm having trouble getting the close button to work properly. Here's my code snippet where I'm trying to override the default alert() function with jQuery UI dialog as described in this ...