Accessing the phone number input from a form in Rails and verifying its presence in the database. Implementing distinct ajax responses based on the existence of the value

Looking for a way to verify phone numbers? The process involves users entering a phone number, submitting the form, and cross-referencing it with a database of phone number records to determine if it's valid. My goal is to provide different AJAX responses based on whether the input exists in the database or not.

Currently, I have set up the AJAX response messaging system. However, when I enter a phone number that is already in the database (e.g., 07780319014), I receive the "phone-number-not-found" response.

See below for the code implementation:

app/views/phones/index.html.erb

<%= form_for :phone, url: phones_path, remote: true, html: { id: 'phone-number-form'}  do |f| %>
  <div id="phone-number-found"></div>
  <div id="phone-number-not-found"></div>
  <div id="phone-number-error"></div>
  <%= f.text_field :phone_number %>
  <%= submit_tag("Check") %>
<% end %>

app/controllers/phones_controller.rb

class PhonesController < ApplicationController
  def create
    @phone_number = Phone.where('phone_number = ?', params[:phone_number])
    if @phone_number.exists?
      render 'phone-found'

    elsif @phone_number.blank?
      render 'phone-not-found'

    else
      render 'errors'
    end
  end

  private

  def phone_params
    params.require(:phone).permit(
      :phone_number
    )
  end
end

app/views/phones/phone-found.js.erb

$('#phone-number-found').html('Working!');
$('#phone-number-not-found').html('');
$('#phone-number-error').html('');

app/view/phones/phone-not-found.js.erb

$('#phone-number-found').html('');
$('#phone-number-not-found').html('Working!');
$('#phone-number-error').html('');

app/view/phones/error.js.erb

$('#phone-number-found').html('');
$('#phone-number-not-found').html('');
$('#phone-number-error').html('Working!');

config/routes.rb

resources :phones, path: '4g-promo'

I would greatly appreciate any help in troubleshooting this issue. Thank you!

Answer №1

It seems like you're extracting parameters incorrectly.

The incorrect method is as follows:

@phone_number = Phone.where('phone_number = ?', params[:phone_number])

To do it correctly, use the following syntax:

@phone_number = Phone.where('phone_number = ?', params[:phone][:phone_number])

Answer №2

All form data should be located within the params[:phone] hash.

If you are looking for an exact match, you can use:

@phone_number = Phone.where(phone_number: params[:phone][:phone_number])

This will result in an ActiveRecord::Relation being returned, which could be an empty array or an array of matches. Alternatively, you can use:

@phone_number = Phone.find_by(phone_number: params[:phone][:phone_number]

This will return either the specified record or nil.

Considering that end users may input their phone numbers in various formats including spacing and dashes, an exact match is not always guaranteed.

In addition, it is recommended to utilize phone_params instead of params[:phone] in the previously mentioned examples.

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

Hover Effect with CSS Selector - JavaScript or jQuery Implementation

I have a similar code snippet: <article class="leading-0"> <h2> <a href="link">link title</a> </h2> <ul class="actions"> <li class="print-icon"> <a ...><img...>& ...

Picture emerges from the lineup

My dilemma involves repositioning an image within a row > col-md-6. To address this, I devised two classes - .pos1 and .pos2 .pos1 { position: relative; } .pos2 { position: absolute; right: 0px; } However, when applying these classes, the ...

Adding input values to a jQuery Ajax POST request

I am currently attempting to send form values to a remote API using AJAX. The necessary information I require from the HTML form element includes the author, string, false, and true. At the moment, I have hard-coded some values but... function sendData ...

Extracting Menu Information from Weedmaps

I've been attempting to extract menu data from dispensaries listed on weedmaps.com, but I'm struggling to understand how the website is structured and where the relevant information is located for scraping. My goal is simple: I want to retrieve ...

JavaScript shortening a string while joining it

I'm facing a challenge with string truncation in my laravel and JS(jquery) app. Initially, I suspected it was an issue with the backend (as indicated in my question here: Laravel Truncating Strings). However, after thorough debugging, I discovered tha ...

jQuery and CSS3 for importing and customizing text files

I successfully customized the file input utilizing jQuery and CSS3. However, there is one aspect I couldn't quite figure out. After the user selects an image or file, I want to display the selected file's text at the very bottom of the text like ...

Tips on concealing and deactivating the fullscreen option in flowplayer

Could someone please assist me in resolving this issue? I've been attempting to hide the fullscreen button from the flowplayer, but so far, I haven't found a solution. Below is my JavaScript code: <script> $f("player", "flowplayer/flowpla ...

modify the tr element within a jQuery context

I am attempting to convert a "yes" to a select dropdown that allows users to choose between yes and no. The HTML structure is as follows: <tr> <td>text</td> <td>no (needs to be changed via JS)</td> <td><a href="#"&g ...

Error message "Unexpected token" occurs when attempting to use JSON.parse on an array generated in PHP

My attempt to AJAX a JSON array is hitting a snag - when I utilize JSON.parse, an error pops up: Uncaught SyntaxError: Unexpected token Take a look at my PHP snippet: $infoJson = array('info' => array()); while($row = mysqli_fetch_array($que ...

Associating a JSON function with a specific URL path pattern

As I develop a Spring MVC application that includes a controller with 'RequestMapping'-annotated methods, among them a JSON method, I encounter an issue regarding serving static content. The current setup has the static content stored in webapps/ ...

Seeking specific parameter in a JSON array using JavaScript: A guide

Currently, I am working on a project that involves retrieving Facebook news feed data using the graph API. Upon receiving the JSON object, I display it on the page. The "Likes" section is presented as an array of JSON objects like this: data.likes: { ...

My custom Wordpress plugin experiencing issues with the Ajax function not being triggered

I'm currently working on a plugin that includes a button to export a list to an Excel file. At the moment, the plugin index displays the list in a table format with the export button at the top. Below is the code snippet: Even when I try removing th ...

What are some strategies for dividing a webpage evenly between an image and a text-containing div?

I am currently working on emulating a layout that I came across on another website ( if you scroll down past the video and profiles). The layout involves splitting the page 50/50 with a picture that is responsive and maintains its size when the page is res ...

Troubleshooting Issues with Loading Styles and JavaScript for Wordpress Plugin in Admin Area

Can someone please help me with troubleshooting my stylesheet and scripts that are not working properly? I have included styles in the stylesheet and an alert in my script file, but for some reason they are not functioning as expected. (I have confirmed ...

Maintain saved states upon page load/refresh using jQuery Cookies

I'm currently working on enhancing the accessibility features of a website. To achieve this, I have integrated three toggle buttons - one for adjusting font size, another one for highlighting links, and the third one for inverting colors. My objective ...

Add elements to a ul element using JavaScript and make the changes permanent

Managing a dashboard website with multiple div elements can be quite tedious, especially when daily updates are required. Manually editing the HTML code is inefficient and time-consuming. Each div contains a ul element where new li items need to be added ...

Utilizing JavaScript to eliminate objects from a collection and showcase a refreshed arrangement

On a simple webpage using bootstrap and js/jquery, data is fetched via ajax to create entries displayed to the viewer. The process involves: - making a request - parsing XML to create an array of objects with all the data - sorting by one property - cr ...

I am having trouble getting my custom CSS file to be applied to my website on Github pages

I attempted to upload a custom CSS file to apply on The raw CSS file is located at: https://raw.githubusercontent.com/themomoravi/SoundOff-Website/master/styles.css I used the following as my href since it directly links to the raw CSS file: href="http ...

How can you attach an event handler to an HTML button without disrupting its default behavior?

I am working on enhancing a contact form to include a feature where the submit button becomes disabled for five seconds after it is clicked. This is to prevent accidental repeat submissions from occurring. However, I am facing an issue where disabling the ...

Displaying a facebox modal window following an asynchronous request

Within the head tags of my HTML page, I have included the necessary code to load the Facebox plugin: <!-- Code for the Facebox plugin setup --> <link href="<?php echo base_url();?>styles/facebox/src/facebox.css" media="screen" rel="styleshe ...