Javascript/Ajax not receiving ViewBag data properly

I've written the following script:

<script>
$("#sendMSG").click(function () {
    $.ajax({
        type: "POST",
        url: '@Url.Action("Action", "Controller")',
        dataType: "JSon",
        data: { "Email": '@ViewBag.Email' },

        success: function (data) { 
             document.getElementById("Output").innerHTML = data.Message;},
        error: console.log("It did not work"),
    });
});
</script>

When I examine the source frames, I see this: "Email": '[email protected]' },

It appears to be retrieving it, but when I call the controller below:

public JsonResult ThankYou(string Email)
{
}

it returns a null value. If you have any insights on why this might not be functioning correctly, or need more information/code, please feel free to ask and I will provide it.

Thank you

EDIT:

This is the original form code for submitting other information:

 [[Form_SmsPhone]]
  <form action="\Controller\Action" id="smsPhone" method="post">
  [[/Form_SmsPhone]]
    [[Block_Sms]]
    <div class="input-append">
        <input id="phonenumber" style="width: 115px;" name="phonenumber"       type="text">
        <button class="btn" type="submit" value="Send"   id="sendMsg">Send</button>
    </div>
    <p id ="Output"></p>
    [[/Block_Sms]]
  [[Form_End]]
    </form>
  [[/Form_End]]

Answer №1

The button you are using is of type submit.

<button class="btn" type="submit" value="Send"   id="sendMsg">Send</button>

When the button is clicked, it will by default perform a traditional HTTP POST to submit the form to your controller.

You have added an Ajax call in response to the click event, but you are not preventing the default form submission from occurring. This may be why you are encountering issues with a null email value being submitted to your controller.

To prevent the form from submitting, try returning false within your click event:

$("#sendMSG").click(function () {
    $.ajax({
        ...
    });
    return false;
});

This should stop the form from automatically submitting.

Edit:

Additionally, make sure that the names match for your button and the click event. If your button is named "sendMsg", then the click event should be hooked to "sendMsg" as well since case sensitivity matters.

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

Error encountered during AJAX call while attempting to save users: AttributeError - 'NoneType' object does not possess the attribute 'split'

Models.py I encountered a long series of errors when trying to save both my student (an extension of the User model) and my user in the code snippet below. Is there a better way to handle this issue? This problem seems to arise only during an ajax call, as ...

Canceling a request on timeout using Ajax/jQuery

Beginner - Inquiry - Issue at hand: In scenarios where there are lingering open connections not closed by XMLHttprequest, the goal is to terminate them. Within a javascript file handling Ajax calls, the objective is to initiate a timer for each call and ...

Is it possible for a jQuery ajaxSuccess function to detect an AJAX event in a separate JavaScript file? If it is, what steps am I missing?

I've been attempting to initiate a function following an ajax event. I have been informed that despite the ajax event occurring in a different file (on the same server, if that makes a difference) and that the file is javascript, not jquery, "Ajaxsucc ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...

Is it feasible in ES6 Javascript to access properties or methods of the superclass in a child class without the necessity of utilizing the "this" keyword?

Exploring Javascript ES6: Accessing Parent Class Properties in Child Class class Animal { constructor() { this.sound = 'roar' this.species = 'lion' } } class Lion extends Animal { constructor() { ...

When using ng-checked in Angular, the DOM may not display the element.input.checked property even when the

I am having issues with using ng-checked to automatically check a checkbox when a modal loads under certain conditions. Despite the item being checked, the condition if (item.checked) returns false. Below is the directive I am working with. app.directive ...

Steps for automatically toggling a button within a button-group when the page is loaded using jQuery in Bootstrap 3

Here is a button group setup: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-default"> <input type="radio" name="environment" id="staging" value="staging" />Staging </label> <label class= ...

Customize variable values on-the-fly in Laravel

I am trying to create a navbar in Laravel with Vue.js as a blade.php file. I want to include a variable like {{xyz}} in the navbar, and when I navigate to another page, be able to set text using Vue.js or something similar. Can someone assist me with this? ...

Tips for fixing the "Module not found" issue when executing a Node.js application

My Node.js application is encountering an issue when I try to run it using the npm start command. It appears to be failing to locate the entry point file, which results in a "Cannot find module" error. Here's the error message I'm seeing: > P ...

Ways to utilize/extract data from an enumeration

Hello there! I am currently diving into the world of React and Typescript, eager to expand my knowledge. Please bear with me if my explanations are not up to par. In my react app, I have a scenario where I created an enum that I want to utilize in two diff ...

"Troubangular: Troubleshooting unexpected behavior when trying to update ngFor after setting a property

Dealing with what seems like a straightforward component here. I'm fetching an array of objects from an API, storing them in a property, and then displaying them in a select list for the user to choose from. When the value changes, I filter the result ...

Is $timeout considered a questionable hack in Angular.js development practices?

Here's a question for you: I recently encountered a situation where I needed to edit the DOM on a Leaflet Map in order to manipulate the appearance of the legend. To workaround an issue where the map wasn't generating fast enough to access the n ...

nodejs callbacks and their return values

Hey guys, I'm having trouble resolving an issue with a JavaScript callback return. Here's the function in question: //Function to get user's contact list function get_contact_list(data) { //Retrieve user ID based on ...

What is preventing Bootstrap properties from being applied to HTML elements appended to the DOM through JavaScript?

Currently, I am immersed in a project that utilizes Bootstrap to generate various nested components styled in accordance with Bootstrap's class system. I triumphantly crafted a card component using Bootstrap, but encountered a challenge when attemptin ...

Tips for concurrently and asynchronously executing multiple AJAX requests

I am working with a javascript object named Agendamento which includes the following key parts: const Agendamento = { // ... storeResultados: async function (consulta) { //... $.ajax({ type: 'POST', ...

Error: [$controller:ctrlreg] - The controller registration has failed

I am currently exploring the world of AngularJs and attempting to display options from a json file. However, I keep encountering the following error message: "Error: [$controller:ctrlreg]" Below is the code snippet I am working with: var sj = angular. ...

How can I create a dynamic form with AJAX, PHP, JavaScript, and HTML?

If you come across a situation where you have the following files: <head></head> <body> <div id="my_personal_div"> </div> </body> And in your Javascript file: $.(document).ready(){ $.ajax({ url:/any ...

Attempting to transfer a Vue component from one component to another, without directly involving the App.vue file

Hello everyone, I recently created a component called Hamburger.vue in my components directory. I then attempted to import this hamburger component into my Header.vue file to avoid unnecessary code repetition. For reference, here is the link to the playg ...

Stopping the mouse from scrolling

I am facing an issue on my page where scrolling a textbox to the bottom causes the entire document to scroll as well. How can I prevent mouse scrolling on the document but still allow scrolling within the textbox when the mouse is over it? It's import ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...