Tips on transferring values from script to controller in PHP using Laravel (for beginners)

  1. I am trying to update the value in a textbox using a script and then save it in my database through my controller. Although the value in the textbox changes, the ajax call does not work as expected. I apologize for any mistakes, as I am still new to this process.

//script

$(document).ready(function() {
    $('#colorselector_1').colorselector({
        callback : function(value,color) {
            var colorit = $("#colorColor").val(color);
               $.ajax({
                type: 'POST',
                url: '/addItemColor',
                data: {'color':colorit},
              });             
        }
    });
});

//controller

  public function addItemColor(){
    $color = Input::get("color");
    $cake= cakeModel::find($_SESSION['cakeModelID']);
    $cake->colorlayer1=$color;
    $cake->save();
    return Redirect::to('home'); //temporary
 }

//html

<section id="colorselectors">

    <select id="colorselector_1" >
      <option value="1" data-color="#A0522D">sienna</option>
      <option value="47" data-color="#CD5C5C" selected="selected">indianred</option>
      <option value="87" data-color="#FF4500">orangered</option>
      <option value="17" data-color="#008B8B">darkcyan</option>
      <option value="18" data-color="#B8860B">darkgoldenrod</option>
      <option value="68" data-color="#32CD32">limegreen</option>
      <option value="42" data-color="#FFD700">gold</option>
      <option value="77" data-color="#48D1CC">mediumturquoise</option>
      <option value="107" data-color="#87CEEB">skyblue</option>
      <option value="46" data-color="#FF69B4">hotpink</option>
      <option value="47" data-color="#CD5C5C">indianred</option>
      <option value="64" data-color="#87CEFA">lightskyblue</option>
      <option value="13" data-color="#6495ED">cornflowerblue</option>
      <option value="15" data-color="#DC143C">crimson</option>
      <option value="24" data-color="#FF8C00">darkorange</option>
      <option value="78" data-color="#C71585">mediumvioletred</option>
      <option value="123" data-color="#000000">black</option>
    </select>
    <input class="boxi" type="text" id="colorColor"/>

</section>

Answer №1

Give this a shot:

$.ajax({
    type: 'POST',
    url: '/addItemSize',
    data: {'size':size},
    beforeSend: function(req) {
            return req.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
    }
})

Ensure you include the CSRF token for security.

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

What methods can Ajax utilize to make asynchronous requests and receive synchronous responses?

While using jQuery ajax to send a request to a web service, I came across an interesting bug: var AjaxResult; login = function () { AjaxResult = ""; $.ajax({ type: "POST", url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlanne ...

Getting Django post_save signal to work with AJAX query

After utilizing AJAX request to create an order, I also have a post_save signal that should trigger once the order has been saved. However, it seems like this signal is not being received during the AJAX request process. Is there a way to ensure that the ...

Creating an anonymous component in Vue.js involves enclosing the received slots (vnodes) within a wrapper component

Is there a way to wrap two specified named slots, slotOne and slotTwo, which are located in the child component at this.$scopedSlots.slotOne and this.$scopedSlots.slotTwo respectively? I would like to then conditionally render these slots (vnodes) as shown ...

Angular 4 is unable to attach to 'formGroup' as it is not recognized as a valid property of 'form'

As a beginner with Angular 4, I decided to explore model driven forms in Angular 4. However, I keep encountering this frustrating error. Template parse errors: Can't bind to 'formGroup' since it isn't a known property of 'form ...

Sort the inner array within an outer array

const dataArray = [ { id: 1, title: "stuffed chicken is tasty as anything", picture: "./img/chicken.jpg", tags: ["oooo", "tasty", "stuffed"] }, { id: 2, title: "noodles with shrimp and salad", ...

Should each of them be opened in a new connection if web and worker processes are separated?

In my current NodeJS web app project, there are two processes in play - a web process and a worker process. These processes communicate via AMQP. To start the application, I run two scripts: one for the web process called server.js, and another for the wor ...

How to send multiple variables to a PHP script using $.ajax in JavaScript

Here is the script I am using: var wall_user_id = "<?php echo $_SESSION['user_id'];?>"; $.ajax({ type: "POST", url: "insert.php", data: "user_id=" + wall_user_id, success: fun ...

Troubleshooting why Vue.js isn't updating the DOM with two-way binding

I'm currently utilizing Vue.js for implementing two-way binding. One issue I am facing is with an edit button that should convert a text field into an input field upon clicking. However, the DOM does not update immediately as expected. For instance: ...

What is the most effective method for displaying an error code when a JavaScript error occurs?

I'm currently dealing with a library that is throwing errors: throw new Error('The connection timed out waiting for a response') This library has the potential to throw errors for various reasons, making it challenging for users to handle ...

The JavaScript code is failing to retrieve any data from the API

import React, { Component } from 'react'; export class FetchData extends Component { static displayName = FetchData.name; constructor(props) { super(props); this.state = { users: [], loading: true }; } componentDidMount() { ...

Is it possible to execute a specified quantity of Promises simultaneously in Nodejs?

Currently, I am working on developing a web scraping application that utilizes a REST API to gather information from multiple entities on the server. The core functionality of this application can be summarized as follows: let buffer = [] for(entity in ent ...

Is there a way to insert copied links onto separate lines?

I have a list of links to Google search results. I have a checker that allows me to mark the links and copy them. My code is functioning properly, but I want each link to appear on a new line. ... Can someone please help me? I've attempted to add "< ...

`Finding the nodejs API route for displaying images from a database`

How can I successfully display an image from the database without getting a string of question marks instead? Click here to see the issue >>> When attempting to directly call the API using the provided link, the following result is returned: {&qu ...

Calculating the sum of all textboxes with jQuery

I'm encountering an issue when trying to add the values of textboxes on blur call. Specifically, after entering a number in one of the textboxes, it throws NaN when attempting to sum up the values from other textboxes. Below is the code snippet causi ...

When it comes to HTML and Javascript drawing, getting the positioning just right can be a challenge

I'm currently developing a control website for a drawing robot as part of a school project. However, I've been facing some challenges with the functionality of the drawing feature. Though I admit that the site lacks attention to detail, my main ...

Is NodeJS Asynchronous: Has the callback been called twice?

I'm currently working with the Async module in Node.JS to manage my asynchronous calls. However, I've encountered an issue stating "Callback already called." Could someone assist me with resolving this problem? async.each(data['results&apos ...

What is the best way to create a mirrored effect for either a card or text using CSS

Can anyone assist me with this CSS issue? When I hover over to view the movie details, the entire word flips along with it. Is there a way to make only the word flip initially, and then have it return to normal when hovered? The HTML code is included belo ...

Choosing an array from the MongoDB database

{ "_id": "4f609932615a935c18r000000", "participants": [ { "user_name": "john1", "role": "user", "created_at": { "sec": 1331730738, "usec": 810000 }, { "user_name": "john2", "role": ...

The icon on my page is not displaying, and the responsive menu is also not appearing

After tweaking the @media {} settings, I noticed that the icon displays properly when reduced, but disappears completely when fully covered with {}. Additionally, my responsive menu is not visible as expected. `@import url('https://fonts.googleap ...

Unexpected syntax error encountered when shutting down the route, unable to recover

const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.get('/split/name', (req, res) => ...