Failing to send contact information using JSON in PHP

I attempted to transmit JSON data to PHP for email processing, but encountered an issue where the process veered into the 'else' condition during debugging. Here is the code snippet:

HTML

<form id="cbp-mc-form" class="cbp-mc-form" method="post">
  <div class="cbp-mc-column">
        <label for="name">Name (*)</label>
        <input type="text" minlength="2" name="name" required="true" placeholder="John Doe">
         <label for="phone">Phone Number</label>
         <input type="text" name="phone" placeholder="+54 11 999 999">
         <label for="email">Email Address (*)</label>
         <input type="text" name="email" required="true" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a7a1b7a092b6bdbfb3bbbcfcb7aaa6">[email protected]</a>">
      </div>
      <div class="cbp-mc-column">
           <label for="country">Country (*)</label>
           <select id="country" name="country" required>
                <option value="">Choose a country</option>
                <option value="AF">Afghanistan</option>
                <option value="AX">Åland Islands</option>
    <option value="AL">Albania</option>
    <option value="DZ">Algeria</option>
    <option value="AS">American Samoa</option>
    <option value="AD">Andorra</option>
    <option value="AO">Angola</option>
    <option value="AI">Anguilla</option>
    <option value="AQ">Antarctica</option>
    <option value="AG">Antigua and Barbuda</option>
    <option value="AR">Argentina</option>
    <option value="AM">Armenia</option>
    <option value="AW">Aruba</option>
    <option value="AU">Australia</option>
    <option value="AT">Austria</option>
    <option value="AZ">Azerbaijan</option>
     <option value="ES">Spain</option>
    <option value="YE">Yemen</option>
    <option value="ZM">Zambia</option>
    <option value="ZW">Zimbabwe</option>
            </select>
             <label>Scope of Work (*)</label>
             <select id="scope" name="scope" required>
                  <option value="">Choose scope</option>
                  <option value="UX / IA / Strategy">UX / IA / Strategy</option>
                  <option value="Design">Design</option>
                  <option value="Development">Development</option>
                  <option value="Other">Other</option>
             </select>
             <label>Estimated Budget (*)</label>
             <select id="budget" name="budget" required>
                    <option value="">Choose a budget</option>
                    <option value="Less than u$s10k">Less than u$s10k</option>
                    <option value="u$s10k-20k">u$s10k-20k</option>
                    <option value="u$s20k-50k">u$s20k-50k</option>
                    <option value=">u$s50k-100k">u$s50k-100k</option>
                    <option value="">More than +u$s100k</option>
              </select>
      </div>
     <div class="cbp-mc-row">
          <div id="g-recaptcha" class="g-recaptcha" data-sitekey="6LcjmAsTA12QOrP3RYXRjMLwM-bWXVEukSkvNh"></div>
             <label for="message">Message (*)</label>
             <textarea id="message" name="message" required></textarea>
          </div>                        
          <div class="cbp-mc-submit-wrap">
             <p>* Mandatory Fields</p>
             <input type="submit" id="submit_btn" class="cbp-mc-submit" value="Enviar">                            
          </div>    
 </form>

The JavaScript component:

$(document).ready(function() {

    $("#submit_btn").on('click',function(e) { 

        $.getScript("https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js", function() {

            $("#cbp-mc-form").validate({
                debug: true,                    
                rules: {
                    "name": {
                        required: true,
                        minlength: 2
                    },
                    "email": {
                        required: true,
                        email: true
                    },
                    "country": {
                        required: true                          
                    },
                    "scope": {
                        required: true
                    },
                    "budget": {
                        required: true
                    },
                    "message": {
                        required: true,
                         rangelength: [50,250]
                    }
                },
                messages: {
                    "name": {
                        required: "Please enter your name.",
                        minlength: "Your name must have 2 digits at least."
                    },
                    "country": {
                        required: "Choose your country."
                    },
                    "scope": {
                        required: "Specify the scope of your project."
                    },
                    "email": {
                        required: "Enter an email.",
                        email: "Enter a valid email format"
                    },
                    "budget": {
                        required: "Select a budget that best suits your needs."
                    },
                    "message": {
                        required: "Share your needs about the project.",
                        maxlength: "Character limitation is about 400"
                    }
                }   
        });

        console.log($("#cbp-mc-form").valid());
        if($("#cbp-mc-form").valid()) {

            post_data = {
                    'user_name': $('input[name=name]').val(), 
                    'user_email': $('input[name=email]').val(), 
                    'phone': $('input[name=phone]').val(), 
                    'country': $('select[name=country]').val(), 
                    'scope': $('select[name=scope]').val(), 
                    'budget': $('select[name=budget]').val(), 
                    'message': $('textarea[name=message]').val(),
                    'captcha': grecaptcha.getResponse()
            };

            $.ajax({
                    type: "POST",
                    url: "php/contact_me.php",
                    async: true,
                    data: post_data ,                   
                    dataType: 'json',
                    success: function (data) {
                        console.log("everything looks ok" + data);

                    },
                     error: function (xmlHttpRequest, textStatus, errorThrown) {
                        if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0) {
                              return;  // it's not really an error
                        } else {
                              console.log("You're Bot");    
                        }
                    }
            });


         }

        });
        e.preventDefault();
    });
});

While troubleshooting, I diligently logged all pertinent information in the console to pinpoint any issues, yet upon form submission, the unexpected message appeared: console.log("You're Bot"). What could be the underlying cause?

Additionally, I employed the 'preventDefault' statement to ensure the page doesn't refresh upon form submission.

Answer №1

One common mistake in javascript is forgetting to declare a variable with 'var' before using it. This could be the reason for the error you are experiencing.

Try this:

 var user_input = {
'UserData' : 2
}

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

Issue detected with Bundler: Configuration object is not valid. The initialization of Webpack used a configuration object that does not align with the API schema

I am currently struggling to make my bundler compile properly. When trying to get it working, I encountered this error message in my terminal along with my webpack.config.js file. Here is the issue reported by the terminal: Invalid configuration object. ...

Sending additional parameters along with the data obtained from an HTTP request to a method in AngularJS

Within my controller, I have a method that retrieves a JSON file from my API. $scope.get = function (code) { api.get(code) .then(onJsonPart, onError); }; By implementing the above code snippet, I am able to display t ...

How to smoothly scroll with jQuery animation without relying on $.browser and preventing double firing

Many inquiries have arisen about the cross-browser functionality of $('html, body').animate();, yet I seem unable to find a solution for this particular issue: I am eager to eliminate $.browser from my code, but I do not want the scroll event to ...

What is the reason for dirname not being a module attribute? (using the __ notation)

Currently, I am learning the fundamentals of Node.js. Based on the documentation, both __dirname and __filename are part of the module scope. As anticipated, when I use them like this: console.log(__dirname) console.log(__filename) They work correctly, d ...

What are the best practices for manually handling the json_encode function?

I have a set of data that needs to be displayed on a map. In order to achieve this, I need to format it into a JSON file according to Google Maps standards. Here's an example of the format: { "id": 1, "picture": "cité.jpg", "name": "Cité", "categor ...

Adjusting hyperlinks placement based on window size changes using jQuery

On resizing the screen, I am moving the sub-nav links to the '#MoreList' It works well initially, but when the window is expanded again, the links remain in the #MoreList instead of going back to their original positions if there is enough space ...

extracting array index from a Mongoose array

//index.js let countryNameList = { "name"=["Bangladesh","India","Australia"] } //Output Section let findCountryIndex = awaitDataModel.find({$indexOfArray:{CountryName:"Bangladesh"}}) console.log(findCountryIndex); //Expecting Output : 0 I am l ...

Sharing data between the main component and the sidebar in React-Router

Currently working with Meteor in combination with React-Router, and this is the code I'm dealing with: Routes.jsx: Meteor.startup(() => { render( <Router history={browserHistory}> <Route path='/' component={App}> ...

What sets array of middlewares apart from compose-middleware?

Someone recommended that I utilize the compose-middleware module in order to have an array of middlewares. After trying it out, I discovered that it works seamlessly with express.js: router.post('/editPassword', doAction ); var doAction = [ ...

Issue with Angular application failing to fetch data from JSON server

I've been attempting to retrieve data from a local server, but so far I'm not getting any results. The concept is to have a service handle the retrieval process and return an observable for any components in need of the data to subscribe to. dis ...

I aim to utilize a minimal number of variables that have been extracted using a JSON extractor in JMeter, and apply them in

Extracting data from an API in Jmeter can be quite complex, especially when dealing with multiple variables. In this particular case, we have extracted two variables using a JSON extractor. The first variable, named "name," contains data such as {abc,asd, ...

What is the correct way to implement include or require_once within an If else statement in PHP?

I have two files named if.php and index.php. I am trying to use if.php to store the if condition for an if statement. However, it does not seem to be working as expected. Is it possible to achieve this? Thank you. if.php <?php if(Three == 3) { //do ...

Is it possible for Prototype to enhance SVG components?

Having some issues developing an interactive SVG map with Prototype. Extending inline SVG elements seems to be causing problems. Take a look at my code snippet below (path data removed for brevity): <svg id="map" xmlns="http://www.w3.org/2000/svg" xmln ...

DRF: Error - Unable to serialize <Model: Model object> as JSON

Encountered a challenge with extracting object data from a request using django-rest-framework ModelViewset create(self, request) method. Below is the code snippet from my model.py class Heat(models.Model): # Relationship Fields animal = models. ...

Guide on extracting JSON data from jQuery containing an array in C#

Looking for a way to extract array data from JSON in C#? Here is an example of the AJAX code: $.ajax({ type: "GET", url: "/Weather/GetWeather", data: { "a": ["1,","2&"], "b" : 4 }, success: onSc ...

Guide for Showing Data from Json Mapper in Angular 5

As a newcomer to Angular5 with TypeScript, I am trying to figure out how to display data from my JSON. I have an API that was created using Java. I have created a JSON Mapper in my Angular code like this : The JSON generated from my Java application looks ...

Guide on making a button display an image, then switch back to the initial image when clicked again

Currently, I have this neat feature on my website where there's a button that toggles the image/background color - kind of like a dark mode switch. The background change is working fine, but I'm encountering some challenges with organizing the im ...

The ng-model remains unchanged when the <select> element is modified using JavaScript

I am currently working on creating a customized dropdown box with the help of JavaScript and anglersJS to connect the data with the select element. The user interaction involves clicking on a div element that is styled to act as the dropdown option. This d ...

Troubleshooting a JQuery AJAX Autocomplete problem involving PHP and MySQL

I am facing an issue with my autocomplete feature. It is functioning properly on one of my pages, but not on this particular page. Even though the correct number of entries is being retrieved, they all appear to be "blank" or are displayed in black text th ...

What is the step-by-step process for chaining ajax requests using $q.deffer?

I have a task that requires the browser to make N requests to the server, where the requests must be synchronous and start only after the previous request has completed. One way to achieve this is by writing a function with a for loop and recursively call ...