Receive various JSON replies from PHP

I am currently developing an app using PhoneGap which involves a script to read a ticket code. The script performs two queries: one to update the ticket status in the database if it exists, and another to write a log in a separate table. This functionality is working perfectly.

Now, I need to implement a feature where the script will return different responses (Valid or Invalid) in JSON format. However, I am facing challenges in reading the data and displaying the appropriate responses based on the result.

Below is the code snippet from index.html:

$(function() {
  $("#savedata").click(function() {
    var fcode = $("#code").val();
    var fuuid = $("#uuid").val();
    $("#code").val(" ");
    $("#uuid").val(" ");
     $.ajax({type: "POST", 
        url: "http://phonegap.localhost/test/www/db/update.php",
                  data: ({code: fcode, uuid: fuuid}),
                  cache: false,
                  dataType: "text",
                  success: Send
                });    
    });
    function Send(data){    
      document.getElementById('entrada').innerHTML = ("Done!");
    }
  });

And here is the code for update.php:

<?php
require_once('conndb.php');

$code= $_POST['code'];
$uuid = $_POST['uuid'];
$data=array();

$sql = "SELECT code FROM ticket WHERE code='$code'";
$result = mysql_query($sql);

if(mysql_num_rows($result) >0){ 
    $sql="UPDATE ticket SET redeem_status= 1 WHERE code = '$code'";
    $resultado=mysql_query($sql);
    $sql2="INSERT INTO log(id, codigo, hora, uuid, valido) VALUES(NULL, '$code', CURRENT_TIMESTAMP, '$uuid', 1)";
    $resultado2=mysql_query($sql2);
    $val['status'] = 1;
    echo json_encode($val);
}else{
    $sql2="INSERT INTO log (id, codigo, hora, uuid, valido) VALUES (NULL, '$code', CURRENT_TIMESTAMP, '$uuid', 0)";
    $resultado2=mysql_query($sql2);
    $val['status'] = 0;
    echo json_encode($val);
}
?>

Answer №1

Your JavaScript code is expecting TEXT data, but your PHP script is sending JSON instead. To resolve this, update the dataType to json and adjust the Send function accordingly.

Below is a simple solution:

$(function() {
  $("#savedata").click(function() {
    var fcode = $("#code").val();
    var fuuid = $("#uuid").val();
    $("#code").val("");
    $("#uuid").val("");
     $.ajax({
        type: "POST", 
        url: "http://example.com/update.php",
        data: {code: fcode, uuid: fuuid},
        cache: false,
        dataType: "json",
        success: Send
      });    
    });
    function Send(data){    
      if (data.status === 0){
         document.getElementById('entrada').innerHTML = "Error!";
      }
      else{
         document.getElementById('entrada').innerHTML = "Done!";
      } 
    }
  });

Answer №2

To implement this feature, all you need to do is develop a new PHP page that retrieves data from your database and converts it into JSON format. Afterward, within your PhoneGap application, you can assign an action to a button using jQuery to trigger an Ajax request to this specific page. Upon a successful response, you can utilize a function to display the received data on your smartphone screen.

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

Unlocking a Static HTML Website in a Private S3 Bucket using PHP

I have recently set up a private bucket on AWS S3, containing 4 folders labeled A, B, C, and D. Inside these folders, I have uploaded an index.html file along with JS scripts and images to create a static HTML website. On my own website (www.test.com), I ...

The Ajax request encountered a failure exclusively when running on the localhost server

There seems to be an issue with my ajax login call: $.ajax({ url: url_to_ajax, success: function ( data ) { switch (data) { case "-2": input1.addClass("has-error"); break; cas ...

Strip all non-alphabetic characters from a PHP string

Is there a way to eliminate all characters from a string except for letters? I need this feature for the first name input field. ...

jquery accordion not functioning properly following partial ajax page refresh

Initially, I'm using a jQuery accordion that works perfectly. However, I encounter an issue when implementing some Ajax commands to reload part of the page, specifically the inner body section. After the page reloads, the accordion breaks because the ...

Creating interactive JSON objects through the use of JavaScript and AngularJS

When using AngularJS to build a dynamic JSON from server data, I encountered an issue where my current declaration only works if the server data contains one item in the object array. How can I modify this to handle multiple items dynamically? $scope.it ...

The server's request is being processed through jQuery's ajax functionality

Recently, I've started working with jQuery and AJAX. Essentially, the webpage sends an HTTP post request, and the server-side DLL responds by writing a JSON-formatted response back to the page. I'm trying to understand how to handle this response ...

The slider customization on Joomla is functioning perfectly on my local machine, but it seems to be encountering some issues on

Having recently started working on a Joomla website for the first time, I encountered some challenges when trying to add a slider module. Despite successfully implementing the slider on my local machine, I faced issues when transferring the code to the liv ...

How to convert the Unicode characters in Python for the string 'u05d9u05d7u05e4u05d9u05dd'?

Received a Json object from a URL with values formatted like this: title:'\u05d9\u05d7\u05e4\u05d9\u05dd' Attempting to convert these values into readable text, but struggling with them being interpreted as literal strin ...

After I refresh the state in my React form, the data within my child components starts exhibiting odd behavior

My weather app in React seems to be facing a strange issue. When I select a new city and reload the data, my child components display a mix of old and new data multiple times before finally showing the correct information. What could be causing this proble ...

Unable to determine the data type of the JSON object during the

I'm having trouble reading an Object type of json... Here is the json I'm working with: body: { "111": { "name": "name1", "status": 10000 }, "222": { "name": "name2", "status": 20000 }, "333": ...

Error encountered in Django due to repeated AJAX calls causing a closed socket issue: [WinError 10053] The established connection was abruptly terminated by the software running on your host machine

Trying to integrate live search functionality using the Select2 jQuery plugin in my Django 1.11.4 project has led to some server-related issues. Upon entering text into the search box, the server seems unable to handle the volume of requests and ends up sh ...

Mastering Dependency Injection for League Flysystem Integration

The goal is to develop a unique Reader class that functions as a wrapper for the League Flysystem documentation The purpose of the Reader is to provide a convenient way of reading all files in a directory, regardless of their physical form (local file or ...

`Need to clean parameters for safe use in JavaScript code?`

I am working with the php code below: <?php $redirect_lp = $_GET['lp']; ?> <script> setTimeout(function(){ window.location.href = "<?php echo $redirect_lp; ?>"; }, 10) </script> How can I properly sanitiz ...

Utilizing C# to Decode Nested HTML Elements from JSON

I recently came across a very helpful JQuery function that allows me to serialize nested elements. However, I am facing an issue when trying to deserialize it using c#. Upon running the code, I encountered the error message: No parameterless constructor ...

What is the best way to send data to PHP while moving objects between different div elements?

I have a situation where I have two parent divs containing dynamic children divs, and I want to enable POST requests to PHP when items are dragged from one side to the other (and vice versa). Here is the Javascript code I am using: function allowDrop( ...

The Ajax search feature seems to be malfunctioning as it does not exhibit any functionality and fails to

I have successfully added search functionality to my webpage. However, I am encountering a problem where the data is not displaying and only showing a blank page. I checked the console for errors but found none. Below is the code for the search functional ...

Decomposing the Retrofit response.body()

I am having difficulties with implementing Retrofit and understanding how to interpret the response body. I believe that there might be an issue with mapping my JSON data to POJO because the output is not what I expected when I print it out in the log. He ...

Using Laravel allows for the implementation of a personalized validation message

I created a custom rule in Laravel 5.5 and configured a custom translation for it in the lang validation file. Here's how I set it up: 'custom' => [ 'validate' => [ 'correct_password' => 'The :a ...

Is it possible to handle an item within a JSON as a string?

Currently, I'm tackling a Java project that involves handling JSON data structured like this: { "objectList" : [{...}, {...}, ...], "metadata" : {...} } My goal is to extract the object list and metadata as JSON strings. In essence, I ...

Distinguishing between native and custom error objects: a comprehensive guide

When working with errors in my node app, I find it challenging to handle both custom and native errors seamlessly. Errors are not just ordinary JavaScript objects, which adds complexity to error handling. To manage custom errors, I am experimenting with t ...