Zero displayed in AJAX response

Need some help with AJAX in WordPress. I'm encountering an issue where the response I get from AJAX is always showing as "0".

https://i.sstatic.net/9j4SM.png

function verifymsg()
{
var verifymobile = $('#verifymobile').val();
var otpmobile = $('#mobile').val(); 
alert(verifymobile);
alert(otpmobile);
   var data = {
        'action': 'verifyotp_ajax',
        'verifymobile': verifymobile,'otpmobile': otpmobile
    };
    $.post(ajaxurl, data, function(response) {
        alert(response);
        $('#send').css("display", "none");
        $('#verify').css("display", "block");
    });

return false; }

Here's the specific code for WordPress:

add_action('wp_ajax_sendotp_ajax', 'sendotp_ajax_callback');
add_action('wp_ajax_nopriv_sendotp_ajax', 'sendotp_ajax_callback');
function sendotp_ajax_callback() {   
$verifymobile=$_POST['verifymobile'];
$otpmobile=$_POST['otpmobile']
if($otpmobile=="success")
{
    echo "success";
}}}

Answer №1

If you want to eliminate zero at the end of an echo response, simply use either exit; or wp_die(); code.

add_action('wp_ajax_sendotp_ajax', 'sendotp_ajax_callback');
add_action('wp_ajax_nopriv_sendotp_ajax', 'sendotp_ajax_callback');
function sendotp_ajax_callback() {   
$verifymobile=$_POST['verifymobile'];
$otpmobile=$_POST['otpmobile']
if($otpmobile=="success")
{
    echo "success";exit;
}}}

To find more assistance, visit the link: Click here and refer to the section titled Error Return Values.

Answer №2

To halt the execution of a page after a certain condition is met, you have several options available such as using die(), exit(), or wp_die(). This will ensure that when the condition is true, only 'success' will be returned and the page execution will stop.

add_action('wp_ajax_sendotp_ajax', 'sendotp_ajax_callback');
add_action('wp_ajax_nopriv_sendotp_ajax', 'sendotp_ajax_callback');
function sendotp_ajax_callback() {   
$verifymobile=$_POST['verifymobile'];
$otpmobile=$_POST['otpmobile']
if($otpmobile=="success")
{
    echo "success";exit;
}}}

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

Tips for reducing unwanted messages on a form

My website features a basic registration form where users can sign up for a newsletter by entering their email address. I am concerned about potential spammers flooding my system with fake email addresses. Does anyone have any suggestions on how to preven ...

What is preventing me from making a call to localhost:5000 from localhost:3000 using axios in React?

I have a React application running on localhost:3000. Within this app, I am making a GET request using axios to http://localhost:5000/fblogin. const Login = () => { const options = { method: "GET", url: "http://localhost:5000/fblogin", ...

Unable to show the response from an HTML servlet using Ajax and qTip2

I am having an issue where I am trying to display text (or html) received from a servlet response in a qTip2 tooltip within a jsp page. Despite verifying that the servlet is being invoked and returning text using Firebug, I encountered an error when attemp ...

Next.js implementation of dynamic routing

Hello, I'm currently facing a challenge while working with dynamic routes in Next.js. The file in question is named [type].js, and it contains the following code: import React from 'react'; import AuthSection from 'components/AuthSectio ...

A guide on incorporating Google authentication into Vue.js with the use of TypeScript and the component-based syntax

Currently, I am in the process of integrating Google authentication into my Vue.js front end. The project was initialized using CLI with TypeScript and component style syntax enabled, alongside other configurations. Additionally, there is a backend web ser ...

Tips for assigning an ID to a span element within a for loop

I am facing a challenge where I need to assign IDs to span tags that do not have the id attribute. These IDs need to be assigned sequentially by incrementing through a for loop and passing my geneologicalSequenceNumber into each span tag. Can you guide me ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

Reflection effect on the ground in three.js

Is there a way to achieve the same effect without duplicating spheres? I attempted to replicate the functionality, but the reflections appear too large :/ var groundTexture = THREE.ImageUtils.loadTexture( "files/checkerboard.jpg" ); groundTexture.wrapS = ...

What steps are involved in enabling Server Side Rendering with Next.js?

For my exploration of Next.js, I started by setting up a new Next.js project and incorporating code to retrieve weather data: export default function Home() { const [data, setData] = useState(null); useEffect(() => { fetch("https://api.we ...

Using Javascript to swap background images, ensuring that the initial image is shown only once

I have a query regarding the background image rotation on my HTML page. I am currently using the code below to change the background image, but I want the first image to be displayed only once while the rest continue rotating. Can anyone provide guidance o ...

Querying a Mongoose database in express.js using the "like" command for strings

Currently, I am trying to query my Mongoose database with a search parameter where the title matches the "customTitle" extracted from the URL. The search function works perfectly fine when searching for all items using Article.find(err, foundArticles) =&g ...

An object is not defined in the following scenario

I currently have a custom function that includes the following code snippet: 1: var object = get_resource($scope, CbgenRestangular, $stateParams.scheme_id); 2: console.log(object) This function triggers the following code: get_resource = function ($sc ...

In JavaScript, the price can be calculated and displayed instantly when a number is entered into a form using the input type 'number'

Is there a way for me to automatically calculate the price and display it as soon as I enter a number into my form? Currently, the price is only displayed after I press submit. <script type="text/javascript"> function calculatePrice() { ...

Tips on transferring dynamically generated results to a user-friendly print window

After users complete a quiz, they receive their results. The client now wants to implement a "Print Results" feature that opens in a new window with customized CSS. I'm trying to figure out how to transfer the results to the new window using JavaScri ...

Is there a way to determine what is affecting the properties of an element?

I've been grappling with a chunk of lengthy HTML, styles, and javascript. My mission? To uncover whatever magic is changing the text within a specific element. <span class="panel-title"> I'm a Panel with All Options</span> Transform ...

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

The malfunctioning of my Jquery datepicker

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <script src="jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(document).r ...

What is the preferred method for implementing a dynamic select control with Ajax

I'm having an issue with AJAX and MySQL in PHP. Can anyone offer assistance? Within my form, I have a select control: <form action="index.php" method="post" name="pretraga" class="border"> <p>Location:</p> <div ...

Updating a property of a JavaScript class using a callback function inside the class method after an AJAX request

Here is the code snippet from my JavaScript file: var myApp = myApp || {}; myApp.TestClass = function () { this.testProperty = null; } myApp.TestClass.prototype = { constructor: this, testMethod: function () { var testClass = this; ...

Error message encountered when utilizing the Three.js JSONLoader: "'onLoad is not a function'."

I'm currently working on setting up a simple scene with Three.js to display an imported mesh rotating. I pieced together a couple of examples from the Three.js documentation and ended up with the code below: var scene, camera, renderer; var geometry, ...