Retrieving Information from Ajax Response Following a Successful Insert Query in Codeigniter

I am trying to use ajax method to insert form data into a database and then redirect it to the next page. I have successfully passed the data in ajax and inserted it into the database table. However, I am facing an issue with getting the generated reference ID in the response. I need this reference ID to control other form entries on the next page. How can I achieve this?

Below is my form part (having two or three inputs for reference) with Ajax code:

<form id="visaForm" name="visaForm" action="https://www.domainurl.com/india-visa/personal-details" method="post">
  <input type="hidden" id="country" name="country" value="DZA"> 
            <input type="hidden" id="reference_number" name="reference_number" value="">
            <input type="hidden" id="visa_type_id" name="visa_type_id" value="1">
 <input id="next" class="btn primary-btn" type="button" value="Save &amp; Continue">
</form>

<script>
$('#next').on('click',function(){
var $form = $('#visaForm');
    var serializedData = $form.serialize();
    $.ajax({
            type:'POST',
            url:"https://www.domainurl.com/india-visa/add-applicants",
            data: "gofor=save_data&"+serializedData,
            success:function(response){
                responsepre = response.split('~');
                document.getElementById("reference_number").value= responsepre[0];
                $('#visaForm').submit();
            }
        });
}); 

</script>

This is my Controller Method:

public function add_applicants()
{
 $this->load->model('visa/Process_model');
 $this->Process_model->insertappdata(); 
}

This is my Model:

function insertappdata()
{
   $query=$this->db->query("select * from appstbl ORDER BY id DESC LIMIT 1");
   $data = $query->result_array();
   $str = $data[0]['appid'];
   $int = preg_replace('/[^0-9]/', '',$str);
   $pure_str = str_replace($int, "", $str);
   $appid = $pure_str.($int+147);

   $data = array(
    'phoneno' => $this->input->post('mobile'),
    'whatsappno' => $this->input->post('whatsappnumber'),
    'email' => $this->input->post('email_id'),
    'portofarrival' => $this->input->post('port_of_arrival'),       
    'appid'=>$appid,        
     );               
   $this->db->insert('appstbl', $data);
}

I would like to pass the inserted "Appid" into Myview so that it can be used on the next Controller Method using the Form Action URL.

Answer №1

Once the insertion is complete, you can retrieve the ID of the last inserted item using insert_id().

For example:

Model:

   $this->db->insert('appstbl', $data);
   $insert_id = $this->db->insert_id();
   return $insert_id;

Controller:

$insert_id = $this->Process_model->insertappdata(); 
echo json_encode($insert_id); // sending the insert id back via AJAX

Update: I now understand what was meant by using $appid

Model:

$this->db->insert('appstbl', $data);
       return $appid;

Controller:

$appid = $this->Process_model->insertappdata(); 
echo json_encode($appid); // sending the insert id back via AJAX

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 is the best way to integrate custom JavaScript files into a Vue project?

I recently downloaded an HTML template from a website and now I am looking to convert the entire template into a Vue CLI project. The template includes jQuery and other custom JavaScript files. While I was able to use npm packages for jQuery and Bootstrap, ...

Extract the email address from the HTML source code obtained through a GET AJAX request

An interesting scenario arises when the following code is executed from www.example.com. It fetches the complete html source code of www.example.com/example.html and displays it in an alert message. function process(){ url = "http://www.example.com/ex ...

Using jQuery AJAX enforces the use of HTTPS

Here is the current setup: Using jquery version 2.1.1 Employing nodejs (not a crucial factor) Making requests over https The issue at hand: When using $.getJSON() and $.get(), the URL requested appears as "". Despite confirming the correctness of the UR ...

What could be causing a template value in my AngularJS/Ionic Framework code to not be replaced properly?

Recently, I've been exploring the world of Ionic Framework with Angular by my side. However, I've hit a bit of a roadblock. My goal is to set up tabs at the bottom of my application using a model definition. Here's what I've tried so ...

Tips on integrating googleapis with apps script

My goal: I am trying to implement the Google Calendar's API acl.list() in a Google Script using the UrlFetchApp.fetch() function. Issue: The Google script itself has an OAuth token when it runs. However, the problem arises when the UrlFetchApp.fetc ...

Why is the Express validator failing to work with the posted value?

I have come across an issue with my current code. Everything is working fine, but I need to access req.body.type in the createValidationFor function. However, when I try to access it, the validation stops working and I can't figure out why. router.po ...

What could be causing the Babel installation to fail within Electron? Is Babel necessary for my project or can it be avoided?

Having trouble using the npm package https://www.npmjs.com/package/swipe-detect and encountering the following error message: export default function(target, callback, threshold=150) { ^^^^^^ SyntaxError: Unexpected token export at Module._compile (i ...

Sending a json array from PHP

I spent several hours searching for solutions to my problem but couldn't find an answer. I'm trying to perform a search on the same page using jQuery, AJAX, and PHP. Unfortunately, the array from PHP is still returning undefined. Here is the P ...

Troubleshooting Angular JS Module Injection Issues

Lately, I've been exploring the wonders of angular JS and it has truly impressed me. However, one concept that still eludes my full understanding is injection. Despite this, I have successfully employed this technique across numerous pages in my proje ...

How to Easily Add GitHub NPM Packages to Your SAPUI5 Web IDE

Looking to integrate an NPM package from Github into SAPUI5 using the WebIde Framework. Package Link: https://github.com/commenthol/date-holidays/blob/master/README.md#usage Primary Issue: Need a file with the library for importing and copying into the W ...

Unable to send an HTTP request using intent

I'm currently facing an issue where an intent triggers an HTTP request, but I keep encountering errors. Whenever the intent is triggered, the following code is executed: const https = require('https'); https.get('*************' ...

Tips on adjusting the Leaflet Map's zoom level to display all markers in React Leaflet

I am currently working on a project with React Leaflet map that requires changing the center and zoom based on a set of markers. The goal is to adjust the zoom level so that all the markers are visible on the map. To achieve this change in view, I am util ...

Tips for updating nested data in mongoose with 2 unique identifiers?

Is there anyone out there with experience in making a Node push function work on nested objects beyond just one level? I'm looking to delve deeper into a second id within the DB model. // Functional code for updating a user at one level with one id ...

Critical bug discovered in fundamental Vue.js component by Internet Explorer

My Vue.js-powered application is performing flawlessly in all web browsers, except for one... Upon attempting to launch it on Internet Explorer, a frustrating error appears: An anticipated identifier in vue.min.js, line 6 character 4872 Locating the spe ...

Table header containing the weekdays for a jQuery calendar display

I need some assistance in creating a basic monthly calendar using a table. Check out this demo: www.jsfiddle.net/pzdw0s2n/1/ ...

Remove input fields that were generated upon clicking a button

I'm facing an issue with my code that allows me to add inputs using @click="addInput()". However, I am struggling to delete specific inputs using @click="deleteInput(). When I try to delete an input with this.inputs.splice(index, 1), on ...

Instructions for generating multiple components in React when an array is not at your disposal

In the process of developing a Tic-Tac-Toe game, I am in need of creating 9 empty squares. Currently, I have a ul element and 9 li elements representing each square in the game. The issue is that there is no array available for looping through and generati ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

Repairing a broken link to the search engine results page (SERP) of an instant JSON search script

I have developed a search script inspired by Google Instant search, which shows relevant results as the user types. The script is written in JSON and utilizes JavaScript to create a URL for the result based on user input. However, there seems to be an issu ...

Optimizing MySQL performance by indexing the columns for maximum and minimum values in combination with

I have a table called '1m_candles' that can be created with the following structure: CREATE TABLE `1m_candles` (`exchange_name` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL, `market_name` varchar(20) COLLATE utf8mb4_unicode_ci ...