Troubles encountered when using AJAX to send a JSON Array to a PHP script

Hey there, I'm just starting to explore the world of ajax and json. So I decided to test out some sample code before diving into my project. However, I've hit a roadblock when trying to send information to my PHP file. Even though I've carefully formatted the input in JSON and ensured that the Ajax command is correctly set up, FireBug is telling me that the values of the input being sent to PHP are undefined. This is puzzling because it did work with a single input. I also attempted a workaround by using json.stringify in my HTML code and then decoding it in the PHP file, but no luck for the single input scenario. If anyone has any insights or suggestions on how to tackle this issue, I would greatly appreciate the help.

HTML:

var sendInput = [
                {"fruit":"apple", "amount":"5"},
                {"fruit":"pear", "amount":"15"}];
   var sent = $.ajax({
        type: "POST",
        data: sendInput,
        dataType: "JSON",
        url: "AjaxTest.php",
        success: function(data) {
            window.alert(data);
                window.alert("Works");
        },
        error: function() {
            window.alert("Failed");
        }
    });

PHP: Nothing special at the moment, it simply echoes any value in $_POST.

Answer №1

When using $.ajax, the data attribute should be a string or a plain object, not an array. If you intend to send an array, consider structuring it like this:

var sendData = {"myData":[
            {"item":"book", "quantity":"3"},
            {"item":"pen", "quantity":"10"}]}; 

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

Main page featuring User Control employing AutoCompleteExtender

Purpose of Application: My website project consists of a master page, a sub master page, and various content pages. I have developed user controls to present information on the main master page. These controls are registered directly on the main master p ...

Python - JSON TypeError: the given key 'tuple' is not a string

I have a collection of data in the form of a dictionary. The keys in this dictionary are tuples: data = {'example': {('key1', 1): 1, ('key2', 2): 1, ('key3', 3): 1}} My goal is to save this data in JSON format by w ...

Utilize the Jackson library in Java to import a JSON URL and parse its contents

I am currently attempting to read and parse a JSON link using Java in order to utilize it for various purposes. However, I am encountering errors that are leaving me uncertain on how to proceed. Below is the snippet of code I am working with: package weat ...

Using AJAX and jQuery to refresh a specific div when a specific button is clicked

I have a function that uses AJAX to update votes when clicked. Here is the code: $(function() { $(".vote").click(function() { var id = $(this).attr("id"); var name = $(this).attr("name"); var dat ...

Do you think my approach is foolproof against XSS attacks?

My website has a chat feature and I am wondering if it is protected against XSS attacks. Here is how my method works: To display incoming messages from an AJAX request, I utilize the following jQuery code: $("#message").prepend(req.msg); Although I am a ...

Leverage AJAX data to dynamically generate an input field within a Laravel application

. Hey everyone, I'm currently working on implementing ajax for a search functionality. The goal is to display links to the search results' pages along with checkboxes next to each result, allowing users to select orders for printing. Although I ...

Fetch information that was transmitted through an ajax post submission

How can I retrieve JSON formatted data sent using an ajax post request if the keys and number of objects are unknown when using $_POST["name"];? I am currently working on a website that functions as a simple online store where customers can choose items m ...

Incorporate a new element into your webpage using an AJAX call in Symfony 3, all without

I am currently working on implementing Symfony forms within a modal using AJAX to prevent page reloading every time an add/remove or update action is submitted. However, I am not very familiar with AJAX and unsure how to proceed. Can anyone provide guidanc ...

What is the best way to extract parameters from a JSON object?

Here is the complete code: $.post('test.php', { id: id },function (data) { console.log(data); var Server = data.response.server; var Photo = data.response.photo; console.log(Server); console.log(Photo); }); When I receive data I get JSON data ...

Guidelines on managing two sets of JSON data sent via AJAX to a PHP script

Embarking on my journey into the realm of JSON/AJAX for the first time. Essentially, I am tasked with sending 2 sets of data to a PHP file. One set will be saved in a MySQL table, while the other is utilized by the PHP script. My Javascript generates 2 s ...

How can I modify the # symbol with .htaccess?

When someone accesses the following URL: www.facebook.com/index.php#sk=inbox The .htaccess file will redirect it to the server as: www.facebook.com/index.php?sk=inbox This allows me to retrieve the value of sk using PHP like this: *echo $_GET[&a ...

When using json.dumps, it appends the attribute '"__pydantic_initialised__": true' to the object

I have been experimenting with fastapi and working with data from json files. One issue I encountered is that when I use app.put to add an object, json.dumps automatically adds the attribute "__pydantic_initialised__": true to the newly created o ...

Is there a way for me to adjust my for loop so that it showcases my dynamic divs in a bootstrap col-md-6 grid layout?

Currently, the JSON data is appended to a wrapper, but the output shows 10 sections with 10 rows instead of having all divs nested inside one section tag and separated into 5 rows. I can see the dynamically created elements when inspecting the page, but th ...

What is the best way to save a dictionary with tuple keys into a .txt file?

Is it possible to save a dictionary containing tuples as keys into a .txt file? The program works fine with integer keys, but encounters an error when using tuple keys. dict = {(1, 1): 11, (2, 2): 22, (3, 3): 33, (4, 4): 44, (5, 5): 55, (6, 6): 66, (7, 7) ...

Spring controller experienced a 404 not found error when making a jQuery AJAX call

I am new to Spring and I have generated a JSON as shown below: [ { "customer" : "16", "project" : "19", "phase" : "47", "approver" : "5", "date1" : "", "date2" : "", "date3" : "", "date4" : "", "date5" : "", "da ...

Can you provide guidance on the correct syntax for sending a JSON post request to StubHub?

{ "listing":{ "deliveryOption":"option", "event":{ "date":"date", "name":"name of event", "venue":"venue" }, "externalListingId":"000000000", "inhandDate":"inhand date", "pricePerTicke ...

Guide to presenting JSON data with ajax

I am trying to dynamically display data based on the selected value from a drop-down list using Ajax's GET method. The idea is to modify the URL by appending the selected item in order to retrieve relevant data from the server: Here is an example of ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...

Having issues when dynamically adding options to a multiselect dropdown

I'm working on dynamically adding options to a multiselect using AJAX: <select size='2' name="CraftCode" id=@ccrf class="form-control js-select manualentrydd" ></select> $.ajax({ type: "GET", url: "GetCraftCodes", data: ...

Update the input value following a successful action

How can I update the value of an input field after a successful ajax call? I have tried the following approach but it doesn't seem to be working. The result from the alert is 80000 Here is the HTML input code: <input class="form-control" type=" ...