Transmit a JSON object to the server using a JavaScript function

I am attempting to transmit a JSON object to a remote server but I am not receiving a success message. Can someone please help me identify what is incorrect in this code:

function sendSMS(){
    var input = '{"header":"****","****":*****,"****":"*****"}';
    var url = "https://**********&username=*****&password=*******";

    jQuery.ajax({
        type: "POST",
        crossDomain:true,
        url: url,
        data: JSON.stringify(input),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        success: function(){
           alert("success");
        }
    });
}
// html code
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
   <script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript" src="sendSMS.js"></script>
</head>

<body> 
<button onclick="sendSMS()">sendSMS</button>
</body>
</html>

Any assistance would be greatly appreciated.

Answer №1

To make your ajax call work correctly, simply update it to the following:

function sendSMS(){
var input = '{"header":"Ooredoo","msisdn":21620117297,"SMS":"Hello"}';
var url = "https://**********&username=*****&password=*******";

jQuery.ajax({
    type: "POST",
    crossDomain:true,
    url: url,
    data: JSON.parse(input),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: false,
    success: function(){
       alert("success");
    }
});
}

The key changes here are using JSON.parse instead of JSON.stringify to properly parse the JSON data into a JSON object. Additionally, make sure to add the missing " at the end of the payload, right after Hello.

If you have any further inquiries, feel free to ask :)

Furthermore, I suggest avoiding sending the username and password as querystring parameters. Instead, opt for a POST request with a secure payload. Lastly, consider implementing SSL for added security.

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

Utilizing Ajax with form_for in Rails 3

In my controller, I have a method called work_here: def work_here @company = Company.find(params[:id]) current_user.work_apply(current_user, @company) redirect_to company_path end On the view page: <%= render 'companies/work_form' if sig ...

Utilizing the map() function to iterate through a list of outcomes and assigning the resulting array as the state of a component in ReactJS

Currently, I am facing an issue with assigning an array value to the state in my react project. In order to do this, I have initialized my state as follows: constructor(props) { super(props); this.state = { category: [] } } My objec ...

Enhancing your scheduling capabilities with Kendo UI Web Scheduler - Dynamically managing resources dataSource

I've been attempting to dynamically change the resources dataSource in my Scheduler, but unfortunately, the changes I am making are not reflecting in the Scheduler interface. Here is how I have set up the scheduler: $("#scheduler").kendoScheduler ({ ...

obtain data from JSON using JavaScript

Greetings! I am dealing with a JSON output that looks like this: "{ \"max_output_watts\": 150, \"frame_length_inches\": \"62.20\", \"frame_width_inches\": \"31.81\" }" I am using it in a functi ...

The user uploads an image to the server, which is then assigned as the background-image for a div element

I am in search of a straightforward method to allow users to upload an image to my server and then use that uploaded image as the background-image for a div element. I need the image to be actually uploaded to the server rather than just displaying a local ...

Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this: "document.body.style.fontSize = 100/50/20" However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for ...

Adjusting the X-axis in Highstock: Tips and Tricks

Is there a way to adjust the X axis on this chart? My goal is to shift it so that it only covers half of the width, leaving the other half blank for future plotlines. Any suggestions on how to achieve this? Thanks! :) ...

The AJAX function fails to trigger the MVC controller method

I'm attempting to enable inline editing by cell, rather than by row, when double-clicking. Although the initial setup is working, it's not updating the record as expected - the "SaveCustomer" call to the controller isn't triggered. Can anyon ...

attempting to retrieve numerical variable beyond the function in jQuery

Trying to implement a star rating system and need to access the rating number for further actions. How can I make the number variable accessible outside of the click function? $(document).ready(function () { $(".li").mouseover(functio ...

Having difficulty interpreting the JSON response sent by Google

I've been having trouble parsing a Json response from this specific URL. I've tried using SBJsonParser, MTJSON, and another parser, but unfortunately, all three have returned NULL in my case. apiUrlStr = @"http://maps.google.com/maps?output=drag ...

Leverage node rework CSS directly within your browser for seamless website

Looking to utilize the reworkcss/css library in the browser. Downloaded version 2.0.0 from GitHub and installed necessary packages with npm install. Attempted using requireJS, which supports processing the CommonJS Module Format by requiring index.js, bu ...

Converting a timestamp from PHP in JSON format to date and time using JavaScript

Within the JSON file, there is a timestamp associated with each user login. An example of this timestamp is: timestamp: "1541404800" What steps should be taken to convert this timestamp into date and time format? ...

Tips for passing the element ID as an argument in the jQuery upvote plugin function

var updateVote = function(data) { $.ajax({ url: '/vote/', type: 'post', data: { id: data.id, up: data.upvoted, down: data.downvoted, ...

Incorporating a classList.toggle into a snippet of code

button, p, h1, h2, h3, h4, h5, a{ /* Define specific elements to use "fantasy" font */ font-family: Tahoma; } #main_body{ margin: 0px auto; background-color: #dedede; } #top_body{ /* Remove margin for simplicity */ } #t ...

Vue.js v-cloak lifecycle method

Currently, I am working on a project where I have styled v-cloak with display: none, and it is decorating the body. As a result, everything remains hidden until the Vue instance is ready. I have created a component that inserts a chart (using highcharts). ...

The "tsc" command in Typescript seems to be acting up. I've exhausted all possible solutions but

Hello there, I find myself struggling to run Typescript throughout the day while utilizing Visual Studio Code. My usual method involves installing TS globally: $ npm install -g typescript But every time I try to use it, I encounter the same error: bas ...

What is the best way to extract the first element of a JSON array in PostgreSQL?

Table Name: table_data_set, Column Name: info Data Format: { "al_uri":"https://al/ma/np_6101", "parameters":[ { "file_name":"QPR.AP6101_%Y%m%d", "input_format":"fixed", "output_format":"parquet", "delimiter ...

Error: Attempted to call $scope.map.control.getGMap function when clicking on the Map, but it is not defined

I'm currently working with Angular-Google-MAP and I'm trying to add a marker to the map. However, whenever I click on the map, I receive an error message saying $scope.map.control.getGMap is not a function. This error is occurring within the geoc ...

error encountered: invalid JSON format in response body while deploying Next.js application on Vercel

The application compiles successfully on local machines and functions properly on both the local production server and development server. The API utilized to retrieve data is also functioning without any issues. Here is the snippet of code that is causin ...

Is a Singleton really necessary for my situation?

I am currently developing a Firefox extension that requires keeping multiple windows synchronized with the same information. The toolbar in each window queries a remote server periodically, but since Firefox windows are isolated environments with their own ...