Leveraging AJAX to fetch an array or string for controller utilization in CakePHP 2

In my current scenario, I am dealing with multiple banner ads on a page and I need to track how many times each one is displayed. For example, let's consider banners with IDs 1, 2, 3, 4, and 5.

Every time the page refreshes, banners with IDs 1, 2, and 3 are loaded. To save these IDs in the database for view count, I need to extract this information and pass it to the controller.

My query revolves around utilizing jQuery AJAX to retrieve the ID numbers and sending them to the controller. Currently, I have defined the following JavaScript variable:

var adId = '1,2,3';

While I could iterate through ajax calls for each ID separately, I prefer a more efficient solution. Is there a way, perhaps using JSON or another method, to fetch this data and utilize it in the controller every time the page loads?

Answer №1

Uncertain about your intentions or the server-side language you are employing. One approach is transmitting data as an array in json form:

var adId = [1, 2, 3];

In JavaScript, this can be utilized like a standard array. For those utilizing PHP on the server side, json_decode() can be implemented to convert the string from json format into a functional array in PHP.

Answer №2

Here is a sample jQuery code snippet that you can use to send data to your controller action.

$.get("<?php echo $this->Html->url('controller' => 'ads', 'update_views'); ?>", { id: "1"} );

An example of how this should be implemented in your controller, such as ads_controller.php:

function update_views(){
  if isset($_GET['id']){
    $ad_id = $_GET['id'];
    $ad = $this->Ad->read($ad_id);
    $this->Ad->id = $ad_id;
    $this->Ad->saveField('views', $ad['views']+1);
  }
  return false; // To prevent returning a view.
}

I have not tested this code, but I hope it works for you. If I understood your requirements correctly, it should do the job. Best of luck!

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

Patience is key when letting AJAX calls complete their execution in jQuery functions

In each of my 3 functions, I have a synchronous AJAX call. Here is an example: function() { a(); b(); c(); } a() { ajaxGet(globals.servicePath + '/Demo.svc/GetDemoList/' + sessionStorage.SessionId,function(data, success) {}, '&apos ...

What to do when faced with an unexpected return in a requireJS application while running JSLint?

When setting up my application with `requireJS`, I have two key files: main.js is responsible for configuring everything, while app.js actually "runs" the application. This is how main.js is structured: /*jslint browser: true, indent : 2, nomen : true, ...

What is the best way to access nested JSON array data that includes varying key names and content?

In my current project, I am trying to extract data from a JSON array. Here is my approach: Below is the jQuery/JavaScript code I used to generate and retrieve data, particularly focusing on the nodes object which determines different layouts: var getPost ...

What is the process for combining two distinct geometries with different materials into a single entity in three.js?

I created a 2D square line diagram followed by another square diagram with a sample image in the center position. However, one of them is visible while the other is hidden. I used two different geometries and materials - one with a line-based material se ...

Using R to retrieve values from JSON lists

My knowledge in using R is limited and I need to create a script for a school project. I have a json file with nested lists, and my task is to extract values from two specific attributes. The challenge lies in the fact that these attributes are located i ...

Can you explain the sequence of steps involved in setting up a server in node.js?

I'm curious about the order in which instructions are executed in this code. Specifically, I want to know if http.createServer() or server.listen is executed first, and when the callback function inside createserver will execute. const http = require( ...

Mongoose Alert: Unable to Create Schema Instance

Below is the Schema file that I'm using: const mongoose = require("mongoose"); const ProblemSchema = new mongoose.Schema( { slug: { type: String, required: true, unique: true, }, title: { type: String, ...

Error: The function `res.status` is unsupported

I've been working on a function to allow uploading images to imgur through my express API (nodejs), but I'm running into an issue when calling a function that returns a promise: TypeError: res.status is not a function at uploadpicture.then T ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...

Adding or removing rows within an array in a hybrid Vue project - a step-by-step guide

Recently, I created a small web application to assist in organizing my project ideas. Check it out here: https://codepen.io/aibrindley/pen/ELXajM Now, I am working on enabling users to add items to the array directly from the interface. It would also be c ...

Guide on connecting a Kendo ComboBox to an Observable instance

I'm currently facing an issue with integrating a DropDownList with an Observable class. Below is the code snippet for the observable class: var viewModel = kendo.observable({ dsMember: new kendo.data.DataSource({ // dataS ...

Locate a specific sequence of characters within an array of objects using JavaScript

I am working with an array of objects, where each object contains a string value. My task is to search for a specific substring within the string. [ { "link": "https://www.sec.gov/Archives/edgar/data/1702510/000170251022000084/00 ...

Sending JSON information from the App Component to a different component within Angular 6

I am faced with a challenge involving two components: 1. App Component 2. Main Component Within app.component.ts: ngOnInit () { this.httpService.get('./assets/batch_json_data.json').subscribe(data => { this.batchJson = data ...

Prevent unauthorized users from accessing the expressjs application

Imagine you have an expressjs app set up like this: var express = require('express'); var http = require('http'); var httpApp = express(); httpApp.configure(function() { httpApp.use(express.static(__dirname + '/static/&apo ...

Three.js globe experiencing issues with splines arc functionality

I have been experimenting with mapping arcs around a three.js globe, following some examples. I am close to getting it to work but I am struggling with the calculations and the resulting projection appears to be incorrect. If anyone could review my code an ...

Persist data in vuex with commit objects

Currently, I am attempting to retrieve objects from an axios response using the $store.commit('fetchFunction', response.data) method. I aim to access this data globally in my SPA (vue-router) by using computed in App.vue (the root component). Her ...

Adding the value to the existing key's value

Here is my current code snippet: The following Python code is what I currently have: coll = con['X']['Y'] s = "meta http equiv" m = {'i': s} n = json.dumps(m) o = json.loads(n) coll.insert(o) This is the data that is being ...

What is preventing me from integrating angular-cookies into my application?

I'm struggling to resolve this issue where I can't seem to make it work. My aim is to integrate NgCookies (angular-cookies) into my application, but all I'm encountering are errors. This is what I currently have: JS files being included: ...

Creating a collapsible accordion feature with jQuery using a specific HTML layout: wanna learn how?

I am looking to create an accordion effect with the structure provided below. The goal is to have the corresponding article toggle when clicking on .booklist>li>a, allowing only one article to be open at a time. Can someone assist me with writing thi ...

Exploring the Battle of Efficiency: Stateless Components vs. Class Components in the Age of React Hooks - Determining the Superior Approach

Having delved into various online resources and discussions on platforms like Stack Overflow (link here), the consensus seems to lean towards utilizing stateless functions (functional components) whenever possible. Many of the life cycle methods found in ...