Enhancing Form Fields Dynamically using AJAX and JSON

I'm trying to update specific fields in my form after fetching data from a database using AJAX and JSON.

Here is the code snippet:

In my form:

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'anagrafica-form',
    // Note: Ensure your controller action handles ajax validation correctly when enabling it.
    // You can refer to CActiveForm class documentation for more details.
    'enableAjaxValidation'=>false,
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

    <?php echo $form->errorSummary($model); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'codicefiscale'); ?>
        <?php echo $form->textField($model,'codicefiscale',array('size'=>20,'maxlength'=>16)); ?>
        <?php echo $form->error($model,'codicefiscale'); ?>

                <div id="bottone_ricerca" style="display:inline;">
                <?php    
                    echo CHtml::ajaxButton( 'Ricerca',
                                            $this->createUrl('anagrafica/popolaAnagrafica'),
                                            array(
                                                'type' => 'POST',
                                                'datatype' => 'json',
                                                'data' => array('codfisc' => 'js:$(\'#AnagraficaForm_codicefiscale\').val()'),
                                                'success' => 'function(response){
                                                    $("#cand").html(response);
                                                    $("#'.CHTML::activeId($model,'cognome').'").val(response.cognome);
                                                    $("#'.CHTML::activeId($model,'nome').'").val(response.nome);
                                                    $("#'.CHTML::activeId($model,'email').'").val(response.email);




                                                   }'
                                                ), 
                                            array()
                          );
                ?>    

                </div>
                <div id="cand">

                </div>     

    </div>            

    <div class="row">
        <?php echo $form->labelEx($model,'cognome'); ?>
        <?php echo $form->textField($model,'cognome',array('size'=>35,'maxlength'=>30)); ?>
        <?php echo $form->error($model,'cognome'); ?>
    </div>        

    <!-- Other form fields go here -->

<?php $this->endWidget(); ?>

</div><!-- form -->

In my controller:

public function actionPopolaAnagrafica()
{
    $codfisc = Yii::app()->request->getParam('codfisc');
    echo $codfisc;
    if (Yii::app()->request->isAjaxRequest) {
        if ($codfisc == '') {
            echo CJSON::encode(array(
                'error' => 'true',
                'status' => 'Invalid request.'
            ));
            Yii::app()->end();
        } else {   
            $sql = "SELECT * FROM user WHERE username = '".$codfisc . "'";
            $cmd = Yii::app()->db->createCommand($sql);
            $result = $cmd->queryRow();
                    
            if($result) {
                echo CJSON::encode(array(
                                        'error' => 'false',
                                        'status' => 'Existing Codice Fiscale',
                                        'username' => $result['username'],
                                        'cognome' => $result['cognome'],
                                        'nome' => $result['nome'],
                                        'email' => $result['email']
                                   )                                
                     );
                Yii::app()->end();
            } else {
                echo CJSON::encode(array(
                    'error' => 'true',
                    'status' => 'The codice fiscale ' . $codfisc . ' does not exist.'
                ));
                Yii::app()->end();
            }
        }

    }

The issue is that I am unable to update the fields. The response received is:

xxxyyyddxdd{"error":"false","status":"Codice Fiscale esistente","cognome":"Cognome","nome":"Nome","email":"[email protected]"}

However, the expected response should be:

{"error":"false","status":"Existing Codice Fiscale", "username":"xxxyyyddxdd","cognome":"Cognome","nome":"Nome","email":"[email protected]"}

Where did I go wrong?

Appreciate any assistance. Thank you.

Answer №1

Please eliminate the specified line below:

echo $codfisc;

This line is located on the second line of the function actionPopolaAnagrafica.

Answer №2

function populatePersonalData()
{

    $socialSecNum = Yii::app()->request->getParam('socialSecNum');


      // Important line below
    echo $socialSecNum;

Answer №3

Update the code :

'success' => 'function(response){
          $("#cand").html(response);

          var obj = jQuery.parseJSON( response );
          console.log(obj.cognome);
          $("#'.CHTML::activeId($model,'cognome').'").val(obj.cognome);

Replace the existing code with the updated one above.

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

Even though the correct headers were provided, the POST request is still returning a CORS

I've encountered an issue while attempting to execute my first POST call. The error message states: "Access to XMLHttpRequest at 'url' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field ...

Tips for sending a form and showing results without the need to refresh the page

I am currently working on developing a basic calculator that takes a user input number and displays the calculated output without redirecting or reloading the page. However, since I have no experience with JavaScript (js) and Ajax, I am seeking assistance ...

When using window.location.href and location.reload(), the updated page content from the server is not loaded properly

Currently, I am working on a form that is being updated via an AJAX call. Once the AJAX call successfully completes, I want to reload the page in order to display the new changes. Even though I tried using location.reload() and window.location.href after ...

Selenium WebDriver test for an Oracle ADF Task Flow application is failing on Internet Explorer 11

While I have successfully run a Selenium WebDriver test on Firefox and Chrome, the same test surprisingly fails on Internet Explorer 11. Upon investigation, it seems that the issue stems from using AJAX, as IE does not update the DOM Tree properly after an ...

Enhance the reusability of this function using Jquery

I have a group of checkboxes with classes like [.myCheckBox1, .myCheckBox2, ...] And another group with classes like [.myCheckBoxList1, .myCheckBoxList2, ...] How can I create reusable code to avoid duplication? Here is what I am aiming for: [FUNCTIO ...

Random crashes are observed in Selenium tests during the execution of JavaScript code

Currently, I am in the process of writing functional tests for a Zend application. These tests are executed using PHPUnit and a wrapper called https://github.com/chibimagic/WebDriver-PHP In order to handle the extensive use of JavaScript and AJAX in the a ...

How can PHP Ajax be used to determine when a modal should pop up?

Is there a way to automatically display a modal without refreshing the page? Currently, I have a button that submits to home.php and triggers the modal, but it requires a page refresh for the modal to appear. I'm looking for a solution that will eith ...

Email will be dispatched once reCAPTCHA verification is completed

I'm currently facing an issue with sending an email from my website's form via PHP after the reCAPTCHA verification. Whenever I click the submit button, the page refreshes but the email is not being sent. I believe I might be overlooking somethin ...

Changing a JSON Object into an Array Structure in Swift 4

I received the following JSON data: { "message": null, "data": { "Commodity Department": { "total": 2, "completed": 1, "completedWithDue": 0, "completedWithOutDue": 1, "inProgress": 1, "inProgressWithDue": 0, ...

How to Use Jquery to Track Mouse Movement Over a PNG Image

Need help with this issue Link to Example The first image is a puzzle, The second image is of earth. I can rotate, drag, and resize the earth image, but it appears behind the puzzle image. While I can interact with the puzzle image, I cannot move or ro ...

Using jQuery to validate a form and submit it via Ajax

I have encountered an issue with my validation process. While it works perfectly on a regular PHP form, it seems to only work sporadically on this Ajax form. After clicking the submit button once, the validation fails to run again on subsequent tries. I ...

I'm having trouble getting my ajax call to work properly when I include form-tags. What could

I am encountering an issue with my simple ajax call. It seems that adding form tags to my code is causing the entire ajax response to break. I'm curious as to why this is happening. <div id="overviewList" class="col-sm-3 offset-sm-1 text-center"&g ...

What is the best way to add a fluctuating array into a mySQL database?

I am facing a challenge with inserting an array into my mySQL table task. The array $workCard = $_POST['rep_list']; can have varying contents, sometimes including user:id, customer_id, tire, hub, break_adjust, and other times having different val ...

Uploading images to a database with Codignitor

Is there any way to store images in the MySQL database using a BLOB field? I need to upload them through a web form and then display them afterwards. It's not an ideal solution, but due to certain circumstances, I am forced to do it this way. Currentl ...

When you click on Highcharts, a bigger graph will be displayed

I am working on a feature that allows users to zoom in on small charts on my website. This involves revealing an overlay div and displaying a larger chart with the same data as the clicked chart inside it. function DrawSmallChart() { chart_data = [1, 2, 3 ...

Stop Caching with Jquery Infinite Scroll (IAS)

I am using jQuery + IAS to implement infinite scroll functionality on my website. However, I have encountered an issue where the cache is being disabled when making requests for new content. Specifically, the URL that is accessed to retrieve the next page ...

Having trouble with implementing the .addclass function in a dice roller project

I'm looking to have the element with id=die load initially, and then on a button click event labeled "click me," apply the corresponding CSS class such as 'die1,' 'die2,' and so forth. function roll() { var die = Math.floor(Ma ...

Change a comma delimited string into a JSON formatted array

Is there a way to convert a string of comma separated values into valid JSON format using either PHP or jQuery? The comma separated strings are currently stored in a database and have the following structure: Singapore,Andora,Australia The desired outpu ...

Customizing Slider knob design

I'm trying to customize the look of the JQueryUI slider by changing the handle images, but I can't seem to find any information on how to do it. Even the JQuery Themeroller doesn't offer an option for changing handle images. Does anyone have ...

Utilizing AngularJS to include information into JSON-LD

As a newcomer to AngularJS, I find myself stuck in one of my projects. My goal is to convert the user-entered data in a form into the format: << "schema:data" >> and then push and display it within the @graph of the json-ld. Here are my HTML and Angular co ...