What is the best way to send an array of objects to the server side using ExtJS4 in a single request?

Working in extjs4 MVC has presented a challenge for me as I try to figure out how to send an object array in a single request. While I understand how to send a single object to the server, sending multiple objects has proven to be more complex.

1)Below is a snippet of my controller code:

    check:function () {
    console.log("Inside check function.");
    //creating objects in javascript
    var obj = new Object();
    for (var i = 0; i < 4; i++) {
        var inputs = document.getElementsByName(i);
        var radio = "";
        for (var j = 0; j < inputs.length; j++) {
            if (inputs[j].checked) {
                name = inputs[j].name;
                value = inputs[j].value;
                obj[i] = {'questionId': name, 'option': value};
                console.log("questionId=" + name + " value=" + value);
                console.log("object name=" + obj[i].questionId + " Object value=" + obj[i].option);

                var check = Ext.ModelManager.create(
                    {
                        questionId: name,
                        option: value,
                    }, 'Balaee.model.qb.QbquestionoptionModel');
                console.log("User Info...:" + check.get('option'));
            }// End of if statement
        }// End of inner for loop
    }//End of outer for loop
    var storeObject = this.getStore('qb.QbquestionoptionStore');
    storeObject.sync();
    console.log("data send");

}// End of check function

2)My Model class definition:

Ext.define('Balaee.model.qb.QbquestionoptionModel',{
    extend: 'Ext.data.Model',
    idproperty:'',
    fields: ['optionId','questionId','isAnswer','option','media','keyword','mediaTypeId',],
});

3)Here is my store configuration:

Ext.define('Balaee.store.qb.QbquestionoptionStore',{
    extend: 'Ext.data.Store',
    model: 'Balaee.model.qb.QbquestionoptionModel',
    proxy:
    {
        type:'ajax',
        api:
        {
            read:'http://localhost/balaee/Balaee/index.php?r=QuestionBank/qbpaper/SetUserAnswer11',
            create: 'http://localhost/balaee/Balaee/index.php?r=QuestionBank/qbpaper/SetUserAnswer12',
            update: 'http://localhost/balaee/Balaee/index.php?r=QuestionBank/qbpaper/SetUserAnswer13',
        },
        reader:
        {
            type:'json',
        },
        writer:
        {
            type:'json',
            root:'data'
        }   
    }
});

I am seeking suggestions on how to efficiently handle sending an object array in a single request. Any advice would be greatly appreciated.

Answer №1

Before anything else, it's best to send the data as JSON, which can easily be achieved using the Ext.Ajax.request() method.

Ext.Ajax.request({
    url: 'YourURL',
    jsonData: YourObjectRef, // could be any object or JSON string
    success: function(response, opts) {
        // your code here
    }
});

If you prefer working with a store, set the type to auto for the Modelfield. This type allows for any object. Check out this JSFiddle example of objects within a model.

This is an adjusted version of your store configuration. Remember that you can define a read-only API or a CRUD API. When opting for the latter, make sure all actions are set, such as destroy. Also, note that having a root property in the writer signifies encoding the data, sending everything via get, which may not be desired.

About the proxy: By default, batch is set to true, causing the store to submit all changes at once during sync. If multiple changes exist for an action, the proxy sends an array of objects instead of a single one. To avoid confusion, consider using the allowSingle property on the writer. Setting it to true ensures always sending back an array of objects to the server, even if there's only one. This guarantees consistency in receiving data as an array every time.

proxy:{
    type:'ajax',
    api: {
        read:'index.php?r=...',
        create: 'index.php?r=...',
        update: 'index.php?r=...',
        destroy: 'index.php?r=...',
    },
    reader: {
        type:'json',
        root:'data'
    },
    writer: {
        type:'json',
        allowSingle: false
    }   
}

Answer №2

If you need to send multiple records from a store in one proxy request as an array, make sure to set the allowSingle configuration of your writer to false. By doing this, the proxy request will always wrap the request object in an array, even if only one model instance is being saved or added.

http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.writer.Json-cfg-allowSingle

writer: {
    type:'json',
    root:'data',
    allowSingle: false
}   

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

Is there a way to properly validate the innerText of a multiline form field in SharePoint?

I'm facing an issue with a code snippet related to my problem. The output from console.log(field1[0].innerText); seems correct, but the if statement validation is always resulting in false. I've attempted various types of string validations like ...

Controlling multiple bx-sliders with a single pager using only JavaScript

Is there a way to control 3 sliders using the same pager? I attempted to use the following code but it did not work: <script language="javascript"> $('.mobile_left_mble,.mobile_right_mble,.text_btn').bxSlider({ //pagerCustom: '#bx- ...

Absence of a connectivity pop-up within Ionic 2

Whenever the app loads, my "network check" should run automatically instead of waiting for the user to click on the Check Connection button. I tried putting it in a function but couldn't get it to work. Can anyone help me identify the syntax error in ...

Ways to Retrieve the Value of an Object

Here is some sample data: { "id": 1, "title": "Title one", "category_data": { "2": "Team", "7": "Queries" } }, A function is used to remove duplicate categories from the data: remove_category_duplicates: function () ...

Dynamically restricting the fields returned in MongoDB

My situation involves using Meteor to query a mongo collection. One of the entries looks something like this: { "_id": "uCfwxKXyZygcWQeiS", "gameType": "foobar", "state": "starting", "hidden": { "correctAnswer": "secret", ...

Node.js is experiencing difficulties loading the localhost webpage without displaying any error messages

I am having trouble getting my localhost node.js server to load in any browser. There are no errors, just a buffering symbol on the screen. The code works fine in VS Code. Here is what I have: server.js code: const http = require("http"); const ...

How to obtain mouse coordinates on a texture using three.js

I am looking to develop an engaging interactive panorama similar to the one showcased here: However, I am interested in allowing users to have the ability to interact with it. Is it feasible to retrieve coordinates from the texture based on mouse movemen ...

Unable to trigger a click on the submit button using JavaScript

I'm encountering difficulties in triggering a click using JavaScript on a Mailchimp pop-up subscribe form and I require your assistance. <!-- Title & Description - Holds HTML from CK editor --> <div class="content__titleDescripti ...

Does React JS set initial value after re-rendering its state?

Every time the state is updated, the function is triggered once more (please correct me if I am mistaken). And since the initial line of the App function sets the state, the values of data and setData will not revert to their defaults. For instance, i ...

What is the best way to retrieve data from my JSON file?

When working with a JSON file that contains a single value, how can I extract specific information from it? "audio_services": "{\"node-input-audio_services1\":\"network addresses\",\"audio_ip_1\":\"ports\",\"au ...

Transformation of Array of Objects to Array of Values using Node.js

I am looking to transform the following: [{ prop1: '100', prop2: false, prop3: null, prop4: 'abc' }, { prop1: '102', prop2: false, prop3: null, prop4: 'def' } ] into this format: [[100,false,null,'abc&ap ...

Transferring information from parent page to child page using Angular version 8.2.4

As a newcomer to Angular, I am facing a challenge in sharing data between pages upon loading the main page. The structure involves using dynamic forms to generate dynamic pages within the main page. However, when trying to pass data from the main page to t ...

Troubleshooting problems with AngularJS placeholders on Internet Explorer 9

On my partial page, I've included a placeholder like this: <input name="name" type="text" placeholder="Enter name" ng-class="{'error':form.name.$invalid}" ng-model="Name" required /> I have also set up client side validation for the ...

Sending data to HTML using parameters in a .cshtml document

I encountered a situation where I had to deal with the following code snippet within a .cshtml file: var peopleList = $('#PeopleListTable').dataTable({ // not relevant "fnRender": function (oObj) { ...

Using ng serve to upload multipart files in Angular 2

I am currently working on the front end of a file uploading service and have encountered a strange issue. When I restart the server using ng serve, it throws an error related to generated components within the app component. The error message can be seen h ...

Fading out, switching HTML, and fading back in

I'm encountering some challenges with a basic jQuery function that is supposed to fade an element out, switch the image inside it, and then fade back in. Here's how my function looks: function flipPage() { $("#leftPage").fadeOut("slow", ...

Updating options in a <select ..> element using Javascript

I'm working on a form that allows users to select multiple options, but I'm having trouble replicating the same functionality using JavaScript. Can anyone help me figure out where I've gone wrong? <form name="myForm"> ...

Retrieve the file that has been uploaded to AWS S3

Here is a snippet of code to consider : var express = require('express'), aws = require('aws-sdk'), bodyParser = require('body-parser'), multer = require('multer'), multerS3 = req ...

Error: Unable to access the 'Stream' property as it is undefined" encountered when trying to establish a connection to Athena using React

I am having trouble connecting to AWS Athena and running a query using athena-express. Whenever I attempt to execute a query, I encounter the following error message. Error: TypeError: Cannot read property 'Stream' of undefined I have double-c ...

The app running in node.js encountered a "connection timed out" error

Whenever I try to run my Node.js app by executing "node app.js" and setting NODE_ENV to production, it doesn't seem to be recognized as production. Instead, I encounter a connection timeout error when trying to run the app. My goal is to establish a c ...