CakePhp form experiencing issues with Ajax script functionality

Having trouble with my CakePHP3 and Ajax code in the add.ctp action. I want to load another div after submitting the form, but for some reason, the script isn't working as expected. The jQuery on the page seems fine, but the console logs inside the script are not showing up. Any help would be appreciated as I'm still new to this.


<?php
echo $this->Form->create($article, ['id' => 'ajaxform']);
echo $this->Form->input('title', array('class'=>'form-control'));
echo $this->Form->input('body', ['rows' => '3','class'=>'form-control']);
echo '<p></p>';
echo $this->Form->button(__('Salvar artigo'), array('class'=>'btn btn-success', 'id' => 'butao'));
echo $this->Form->end();
?>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
console.log("test");
$(document).ready(function(){
  $('#butao').click(function(e){
    console.log("teste2");
    $("#ajaxform").submit();
    e.preventDefault;
      $(".content-wrapper").load("main #main");
  });

  $("#ajaxform").on('submit',function(e)
  {
    console.log("teste");
      var postData = $(this).serializeArray();
      var formURL = $(this).attr("action");
      $.ajax(
      {
          url : formURL,
          type: "POST",
          data : postData,
          success:function(data, textStatus, jqXHR)
          {
            $('#main').html(data);
              //data: return data from server
          },
          error: function(jqXHR, textStatus, errorThrown)
          {
              //if fails
          }
      });
      e.preventDefault(); //STOP default action
      e.unbind(); //unbind. to stop multiple form submit.
  });

  $("#ajaxform").submit(); //Submit  the FORM

});
</script>

ArticlesController:


public function add()
{
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
    $article = $this->Articles->patchEntity($article, $this->request->getData());
    // Added this line
    $article->user_id = $this->Auth->user('id');
    // You could also do the following
    //$newData = ['user_id' => $this->Auth->user('id')];
    //$article = $this->Articles->patchEntity($article, $newData);
    if ($this->Articles->save($article)) {
        $this->Flash->success(__('Your article has been saved.'));
        return $this->redirect(['action' => 'main']);
    }
    $this->Flash->error(__('Unable to add your article.'));
}
$this->set('article', $article);
}

--EDIT-- My Main page code which goes to add

<?php foreach ($articles as $article): ?>
<tr>
<td><?= $article->id ?></td>
<td>
<?= $this->Html->link($article->title, ['action' => 'view', 
$article->id]) ?>
</td>
<td>
<?= $article->created->format(DATE_RFC850) ?>
</td>
<td>
<?= $this->Form->postLink(
    'Apagar',
    ['action' => 'delete', $article->id],
    ['confirm' => 'Têm a certeza?','class'=>'btn-danger btn-sm'])

?>
<?= $this->Html->link('Editar', ['action' => 'edit', $article->id],array('class'=>'btn-warning btn-sm')) ?>
<?= $this->Html->link('Copiar', ['action' => 'copy', $article->id],array('class'=>'btn-warning btn-sm')) ?>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
<button id="add" class="btn btn-primary btn-xs">
<h6>Adicionar Artigo</h6>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $('#add').click(function(){
      $("#main").load("add #addctp");
  });
});
</script>
</button>

Answer №1

It is recommended to have your controller return JSON data.

To enable this functionality:

Add the following code in app/Config/routes.php:

Router::extensions(['json']);

This will allow the JSON extension to be utilized.

In your controller, include the following snippet:

public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
}

This enables automatic switching of view classes based on content types.

Replace

$this->set('article', $article);
with:

$this->set(compact('article'));
$this->set('_serialize', ['article']);

By doing this, you can avoid creating specific view files for your controller actions if no custom formatting is needed before converting data into json/xml.

You can now request ArticlesController::add() with the json extension, and the action will serialize $article as JSON.

Lastly, create app/webroot/js/Articles.js:

Articles = {
    init: function () {
        this.add();
    },

    add: function(){
        $( "#ajaxform" ).submit(function( event ) {

            var that    = $(this),
                data    = that.serializeArray(),
                formURL = $('#ajaxform').attr('action') + '.json';

            event.preventDefault();

            $.ajax(
            {
                url: formURL,
                dataType: 'JSON',
                type: 'POST',
                data: data,
                success: function(data,text,xhr)
                {
                    console.log(data);
                },
                error: function()
                {

                },
                complete: function ()
                {

                }
            });


        });
    }
};

$(document).ready(function () {
    Articles.init();
});

and include in your view:

<?= $this->Html->script('Articles', ['block' => true]); ?>

For further reference, check out:

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

Creating an HTML string and then displaying its outer HTML in IE10 can be easily achieved. Just write the

My task is to write an HTML string to an element and then retrieve the resulting outer HTML from that element. This needs to be operational in IE10, latest versions of FF, Chrome, Safari, Android, iOS Safari but does not have to support any older browsers. ...

"Accessing your account only requires a simple two-click login process

Why do I need to click the log in button twice for data validation on my forum website? While designing a forum website, I noticed that users have to click the log-in button twice before the system validates and processes the input data. Below is the code ...

I can't seem to establish a connection with my MongoDB Atlas cluster. I encountered the MongooseError, which is as follows:

Error [MongooseError]: The uri parameter for the openUri() method needs to be a string but is currently set as "undefined". Please ensure that the first parameter for mongoose.connect() or mongoose.createConnection() is a valid string. const express = r ...

using node.js to save query results as global variables

Help needed! I'm struggling to pass the results of my query statement to a global variable in order to dynamically configure my jsganntimproved chart. Any suggestions on what could be going wrong? In the snippet below, the console.log(taskItem) retur ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...

Tips for developing effective client/server applications

For some time now, I have been attempting to develop multiplayer applications for a website. My initial project was to create a simple chat system, but the performance was quite sluggish. The process involved sending messages via AJAX to a PHP application ...

In JavaScript, generate a new column when the text exceeds the height of a div

Is it possible to create a multicolumn layout in HTML that flows from left to right, rather than top to bottom? I am looking to define the height and width of each text column div, so that when the text overflows the box, a new column is automatically ge ...

Issue arising with data exchange between components using data service in Angular 5

Utilizing data service to share information between components has presented a challenge for me. References: Angular: Updating UI from child component to parent component Methods for Sharing Data Between Angular Components Despite attempting the logic o ...

Adjust the margin-top of the navigation bar with animation upon clicking the button

I have implemented a Cookie bar that is fixed at the top of my website. When the Close icon is clicked, the bar fades away. Due to the positioning of the div, I am also pushing down my .nav element by 64px. Inquiry: Is it feasible for the margin-top on ...

Different Choices for Jquery Selector with Small Adjustments

Currently working on building a discussion panel using asp.net and incorporating the jquery selector feature with two different classes. $("#plblDisAgreeProblem", "plblDisAgreeComment").click(function(){ var str = { problemID: $("#problemID") ...

Unable to assign the 'id' property within Datatable

Hello there, I am currently using a datatable and fetching data via AJAX. For each data entry, I add a row to my datatable. However, I keep encountering an error that reads: "Uncaught TypeError: Cannot set property 'id' of null in line code " ...

What is the best method to loop through this object with JavaScript?

Suppose I have the following data: let testData = { 'numGroup1': [[(1, 2, 3, 4, 5), (5, 6, 7, 8, 9)]], 'numGroup2': [[(10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]] }; What is the best approach to iterate through this data using Jav ...

A way to retrieve the value from a list item when clicked on a menu to facilitate dynamic routing in Vue.js

**I have currently created a separate component for each list item, but I'm looking to make this more dynamic as it's taking too long to load. Unfortunately, I'm unsure of how to go about this.** <nav class="navbar navbar-expand-lg ...

What could be causing JQuery Clip to malfunction?

I'm currently exploring the clip function in JQuery to see how it works. Despite my efforts, I'm facing difficulties in getting the function to operate correctly. My intention is to make the image shrink to nothing within a second. Below is a sni ...

What causes an exception to be thrown even after being caught in an async function?

Even if an exception is caught, the remaining code will still run. function problematic(){ //throw new Error('I am an exception') return Promise.reject("I am an exception") } ( async function (){ let msg = await problem ...

Tips for parsing a JSON object efficiently

Javascript var obj = { "name" : ["alex","bob","ajhoge"], "age" : [30,31,33] }; To display the value "alex," you can use: document.write(obj["name"][0]) But how can we filter through 'obj' to retrieve all data like this? html <ul ...

What is the best way to assign an onClick event in React while using document.createElement()?

I am using document.createElement to create an <input>. How can I assign the onClick property in React? var input = document.createElement("input"); input.onClick = {setCount()}; //??? Here is the React code snippet: <input type="s ...

Google-play-scraper encounters an unhandled promise rejection

I'm trying to use the google-play-scraper library with Node.js, but I keep encountering an error when passing a variable as the 'appId'. How can I resolve this issue? Example that works: var gplay = require('google-play-scraper') ...

How to trigger a function to run only once in React when the page is accessed or refreshed

I'm currently developing a search feature using Algolia search functionality. Users can input a search term from another site, be redirected to the search page, and have the search executed automatically. Once on the search page, users must utilize t ...

When jQuery AJAX GET SUCCESS is triggered too quickly

It seems like my "success" response is firing too quickly, so I had to make some adjustments from the initial code... $('.hs_cart button').click(function(){ $.get($(this).attr('url'), { success: function(){ refresh_ ...