Convert JSON data to a PHP variable

When I try to pass some JSON data to a PHP file, the variables in the PHP code end up empty. I suspect it's due to a small syntax error, but I can't pinpoint the exact cause. Any assistance would be highly appreciated.

JAVASCRIPT

if(score >= 100)
{
    console.log("HERE WE GO");
    $.ajax({
        type: "POST",
        url: "FAKENAME.php",
        data: { "data": "{ \"id\": " + id + ", \"quiz\": \"" + getDateTime() + "\"}" },

    }).done(function (data) {
        console.log(JSON.stringify(data) + "This is the data on .done");
        //alert( data );
    })
    .fail(function () {
        console.log("error");
        //alert( "error" );
    })
    .always(function (data) {
        console.log("finished");
        console.log(JSON.stringify(data));
        //alert( "finished" );
    });
}

PHP

$data = json_decode($_POST['data']);
$sql = $conn->prepare("SELECT * FROM FAKEDATABASETABLENAME WHERE id = :id");//no error
$sql->bindParam(':id', $data->id);
//$sql->bindParam(':quiz', $data->quiz);
$sql->execute(); //syntax error

if(!empty($data->id))
{
    $qry = $conn->prepare("UPDATE FAKEDATABASETABLENAME SET Quiz = '2018-06-27 14:44:49' WHERE id = 000007"); //no error and result
    $qry->bindParam(':id', $data->id);
    $qry->bindParam(':quiz', $data->quiz);
    $qry->execute();
}
else
{
    $mailto = "FAKEEMAIL.com" ; //Recipent of the email
    $from = "From: PHP_DEBUG";
    $subject = "PHP_DEBUG";
    $data = json_decode($_POST['data']);
    $content = "id is: " . $data->id. " plaese note.   quiz is: " . $data->quiz. " please note.";
    mail($mailto, $subject, $content, $from);

}

Answer №1

if(total >= 100)
{
    const inputData = JSON.stringify({id: userId, testTime: getCurrentTime()})
    $.ajax({
       type: "POST",
       url: "FAKENAME.php",
       dataType: "json",
       data: {payload: inputData}
    }).done(function (response) {
       console.log(JSON.stringify(response) + "Here is the response data from .done");
    }).fail(function () {
       console.error("An error occurred");
       //alert( "error" );
    }).always(function (response) {
       console.log("Request complete");
       console.log(JSON.stringify(response));
       //alert( "finished" );
    });
}

You can optimize your code as shown below:

Answer №2

let user = {
        username: $("#input-username").val(),
        email:$("#input-email").val(),
        password:$("#input-password").val()
    }

    $('#output').html('processing..');

    $.ajax({
        url: '/api/UserRegister',
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        success: function (response) {
            $('#output').html(response.message);
        },
        data: JSON.stringify(user)
    });

Remember to include the complete URL of your PHP page and ensure you check print_r($_POST) for debugging.

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

Every time I use Get for ajax calls, I keep getting hit with a frustrating

Initially, I was making a call to a [web method] using the POST method. However, since I need to receive data back, I attempted to switch to using the GET method instead. The previous implementation using POST was successful. Unfortunately, using GET resu ...

Positioning an element in the center of another using JQuery

Greetings! I am currently working with some elements that look like this: <div id="one">content</div> <div id="two">content</div> These elements are followed by another set of elements (without any parent, placed directly after th ...

Managing data updates in web applications with "has many" relationships

I've encountered a recurring issue in my web application development projects and I'm looking for some advice on how to handle it more efficiently. Currently, when editing data with multiple relationships in an app that uses MySQL as the database ...

Save files using file_put_contents and monitor the progress

When writing code to download a file and return the status (downloaded bytes), I utilize the file_put_contents method which works effectively. function downloadLink($link,$destination) { $ctx = stream_context_create(); stream_context_set_params($c ...

Returning to a page that has been scrolled down and contains dynamic content loaded via ajax

Currently, my page utilizes ajax to load dynamic content. However, I have noticed a discrepancy in how Firefox and Internet Explorer handle the scrolling position when navigating back using the browser's back button. Firefox retains the scrolled posit ...

choose timestamp that is earlier than

Is there a way to retrieve items from a database that are more than 12 hours old? I'm using a timestamp column to keep track of time, but I only require information based on hours and not year, month, or day. I've tried the following query, but ...

AJAX (Vanilla JavaScript): Sending Image through HTTP Request

I am a beginner with ajax and prefer not to use frameworks. I attempted to use PHP to determine if a file is set and display either true or false, but it didn't work as expected. I'm unsure of where I went wrong. Below is my HTML and JS code: & ...

Unable to display results in YII query Builder

I am facing an issue with using two different syntaxes of the Yii query builder. The first syntax works perfectly but I cannot use variables inside the SQL. $connection = Yii::app()->db; $sql='SELECT id_activo, nom_activo, valor_activo, cod_amena ...

Stop Ajax requests when there are blank spaces in Typeahead.js

I've been experimenting with typeahead.js and utilizing the BloodHound remote feature to load data. Everything is functioning properly, except that when I input only spaces in the textbox, typeahead still makes an ajax call. I'm wondering if th ...

Showing small previews of images using php

I'm struggling with getting linked images to display. The code I have is currently located in a .php file. Its purpose is to retrieve all images from the directory where the file resides and show them using a "for" loop. However, at the moment, it onl ...

What is the best way to locate the final text node within the <p> element?

Looking at the code below, my goal is to identify and retrieve the text node that serves as the last child element. <p class="western" style="margin-bottom: 0.14in"> <font color="#000000"> <font face="Arial, serif"> <font ...

Processing files with Ajax in Telerik RadAsyncUpload

When utilizing radasyncupload on my asp.net page, I encounter an issue with storing the uploaded files to a database as byte arrays. After uploading the files, I aim to trigger an Ajax call upon clicking a button in order to transfer the files from the t ...

Incorrect measurement of text size

My attempt at creating a basic font size changer was working perfectly until I integrated it with the bootstrap framework. Strangely, when I try to increase the font size, it actually decreases instead. var baseFontSize; (function () { "use strict"; ...

What is the convention for using one-letter function names in jQuery and JSON?

Could someone please clarify the functionality of this code snippet? One aspect that I find frustrating about this function is its use of a single-lettered name. How can I determine the purpose of this function and what triggers it to run? function ...

Is there a way to activate a Superfish jQuery Menu with a click instead of a hover?

After doing some research on the internet, I came across an implementation of Superfish menu by Joel Birch that functions based on onclick instead of hover. I found a link on Github by Karl Swedberg which seems to be what I need. https://gist.github.com/ ...

Exploring the wonders of jQuery Ajax within Yii

I am developing a custom shop application and I have a query. In my project, the implementation of Ajax in Yii involves: <?php echo CHtml::ajaxLink( '', array("cart/add/id/$item->id"), array( ' ...

change the css back to its original state when a key is pressed

Is there a way to retrieve the original CSS of an element that changes on hover without rewriting it all? Below is my code: $(document).keydown(function(e) { if (e.keyCode == 27) { $(NBSmegamenu).css('display', 'none');} ...

Adjust the transparency of CSS elements using a jQuery selector

I am developing a grid of brand thumbnails with interactive icons. When one of the icons is hovered, I want all the icons to change opacity and become visible. Here is the current HTML structure: <div id="brands-wrapper"> <img class="brands" ...

Retrieve just a fragment of the feedback by utilizing the .load directive

Hello there, I've been using Wordpress and I have a shortcode with a bunch of code to arrange my blogs in a specific layout. In addition, I've integrated the isotope plugin as well as the infinite scroll plugin. The infinite scroll feature utili ...

Prevent header from being displayed in XML response in Symfony 2

I am currently working on generating an xml document using Symfony. The generation process is successful and I am returning the document using a Twig template named sitemap.xml.twig as shown below: <?xml version="1.0" encoding="UTF-8"?> <urlset x ...