Assistance needed with sending JSON data to a PHP server using the POST method

I am attempting to transfer JSON data from an HTML form to a PHP server using the POST method. The issue I am encountering is that my code always ends up in the fail block within the callback function. Despite this, the Firebug console (ctrl+shift+J) does not display any errors.

<script> 
function ADDLISITEM(form)
{ 
var options = form.txtInput.value;
options = JSON.stringify(options);
var url = "conn_mysql.php"
var request = null;
request = new XMLHttpRequest();
request.open("POST", url, true);
request.onreadystatechange = function(){
    if (request.readyState == 4) {
            if (request.status == 200) {
                alert(request.responseText);
        } else {
            alert(request.status); 
        }
    }
}
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+'));
}
</script>

conn_mysql.php

<?php  
    $json = $_POST['options'];
    $options = json_decode($json);
    $username = "user";  
    $password = "********";  
    $hostname = "localhost";  
    $dbh = mysql_connect($hostname, $username, $password) or die("Unable to 
    connect to MySQL");  
    $selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
    $query1 = "INSERT INTO user_spec (options) VALUES ('$options')";
    mysql_query($query1);
    //if(!mysql_query($query1, $dbh))
    //{die('error:' .mysql_error());} echo'success';
    $query = "SELECT * FROM user_spec";  
    $result=mysql_query($query);     
    $outArray = array(); 
     if ($result)
     { 
       while ($row = mysql_fetch_assoc($result)) $outArray[] = $row; 
     } 
      echo json_encode($outArray);
?> 

Answer №1

The request is returning a "fail" response because the onreadystatechange function is being triggered multiple times with varying readyStates. Here's an updated version with better indentation:

request.onreadystatechange = function(){
    if (request.readyState == 4) {
        if (request.status == 200) {
            alert('http.responseText');
        } else {
            alert('fail'); // error occurs here
        }
    }
}

Make sure to only check the status when readyState reaches 4.

Additionally, when passing parameters in a URL, it's recommended to use encodeURIComponent for proper encoding. When using POST as the method, replace instances of %20 with + as per the specification and pass data as a parameter to the send function instead of concatenating it to the URL:

var url = "conn_sql.php";
…
request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+'));

UPDATE: To handle the received string in PHP, utilize json_decode, like so:

<?php
    $json = $_POST['options'];
    $options = json_decode($json);
    // now $options holds a PHP object
?>

(Refer to How to decode a JSON String)

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

Stop the change event from occurring on a textarea when the user clicks on an external cancel button

In a particular scenario, there is a textarea with an autosave feature triggered by the change event. When the textarea is focused on, Save and Cancel buttons appear at the bottom, providing users with options in case they prefer not to simply click outsid ...

Creating an array of objects data is a breeze with Vue.js

I have an array of data containing selected items, and I need to extract the IDs from this array into a new array so that I can send only the IDs to the back-end. Sample Code method toggleSelection(rows) { console.log('this.multipleSelection : &a ...

Is there a way to display a condition in Blade using jQuery through AJAX?

I am attempting to create a conditional statement using AJAX in my code that will display a button when the user is an 'admin'. While it is simple in Blade, I am encountering issues when trying to print it from jQuery. -- JavaScript Code -- cod ...

Having difficulty toggling a <div> element with jQuery

I am attempting to implement a button that toggles the visibility of a div containing replies to comments. My goal is to have the ability to hide and display the replies by clicking the button. The "show all replies" button should only appear if there are ...

PHP's for loop may not iterate through the entire array

I am currently using PHP/7.2.0beta3 and I have a requirement to develop a custom function in PHP that can reverse an array. For example, if the array is (1,2,3), the desired outcome should be (3,2,1). My initial approach was to utilize the array_pop funct ...

Confirm user permissions

I am currently working on developing a time registration system for my school project team. Most of the system is functioning properly, except I am facing challenges with implementing user rights validation. The validation process depends on the value in ...

Guide to securely encrypting passwords when transferring from an Android device to a PHP server

As a beginner in programming, I am currently working on a small application running on an Android device that requires user-based information from my PHP web server. My strategy involves using JSON for communication between the phone and the server. The p ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants > ...

Retrieving Browser Component from User Agent String

Currently struggling with extracting the name of the browser being used by a visitor during data collection. I tried using the code below, but it seems like $browser returns empty after execution. $userAgent = mysql_real_escape_string($_SERVER["HTTP_USE ...

Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side: export const getData = async (): Promise<any> => { const response = await fetch(`/data`, { method: 'GET', headers: CONTENT_TYPE_ ...

Searching for the position of different size values according to their specific value

information = { boxNoTo: 1, boxNoFrom: 1, size: 'M', } items = [{ size: 'M', },{ size: 'M', },{ size: 'S,M,L,XS', boxNoTo: 1, boxNoFrom: 1, country: 'CA', name: 'Josh' }] This is what I have don ...

Next.js Error: Unable to access the 'collection' property, as it is undefined

I have recently started using next.js and I am interested in creating a Facebook clone by following YouTube tutorials. However, I keep encountering the error message "Cannot read properties of undefined (reading 'collection')". To troubleshoot, I ...

Vue component lifecycle hook to fetch data from Firebase

Looking for a solution with Vue 2 component that utilizes Vuefire to connect declaratively with a Firebase real-time database: import { db } from '../firebase/db' export default { data: () => ({ cats: [] }), firebase: { ...

Images from JSON cannot be loaded in ReactJS

It seems that importing image URLs from a JSON file is not working as expected, resulting in certain issues. However, when importing them using the syntax {require("hardcoded URL")}, it works fine. But if variables are used as shown in the image below or l ...

What steps can I take to ensure that when the user clicks the logout button, they are redirected to the home component?

Struggling to find a way to direct the user back to the Home component after logging out. The API functionality has been tested and is working properly. I'm unsure how to properly implement the logout method in the current context to allow for succes ...

Updating data with Zend Framework 2 using the TableGateway Object

public function updateData($table, $conditions = array(), $data_array = array()){ print_r($data_array); $adapter = $this->tableGateway->getAdapter(); $projectTable; if($table != null){ $projectTable = new TableGateway($tab ...

Display some text after a delay of 3 seconds using setTimeOut function in ReactJS

When using React JS, I encountered an issue where I am able to display text in the console after 2 seconds, but it is not appearing in the DOM. const items = document.getElementById("items"); const errorDisplay = () => { setTimeout(function () { item ...

javascript code not functioning properly

Something simple! In my asp.net-MVC project, I have a button and an external JavaScript file called mydata.js. This file contains a function called checkJS(). function checkJs() { debugger; alert("your output!!!"); } Here is my code: <div id="m ...

Error encountered while using JavaScript for waiting in Selenium

When using selenium and phantomjs to submit a form and then navigate back to the previous page, sometimes I encounter a timeout error as shown below: TimeoutError: Waiting for element to be located By(xpath,//div[@id='ContactFormBody']/div/br) W ...

Modify the conditions of a CSS file in Bootstrap using JavaScript

My project requires internationalization support for right-to-left languages like Arabic and Hebrew, so I need to modify some Bootstrap classes (such as col) to float right instead of left. I am using create-react-app with babel/webpack and react-bootstra ...