1

What I am trying to do is update my MySQL database from the result of an ajax call to a remote website and then use those results to update my own database.

After building the JSON object by looping the result set using the PUSH method I console.log the result and get this :

[]
0: {id: "3340", orderID: "1518883", status: "Shipped", shipdate: "March 12, 2020", shipfrom: "USA", …}
1: {id: "1441", orderID: "1518884", status: "Scheduled", shipdate: "March 19, 2020", shipfrom: "USA", …}
2: {id: "3345", orderID: "1518895", status: "Shipped", shipdate: "March 12, 2020", shipfrom: "IA", …}
3: {id: "3342", orderID: "1518886", status: "Shipped", shipdate: "March 11, 2020", shipfrom: "TX", …}
4: {id: "3346", orderID: "1518896", status: "Shipped", shipdate: "March 12, 2020", shipfrom: "MN", …}
5: {id: "3343", orderID: "1518892", status: "Finishing", shipdate: "March 16, 2020", shipfrom: "IA", …}
6: {id: "3344", orderID: "1518893", status: "Shipped", shipdate: "March 12, 2020", shipfrom: "IA", …}
7: {id: "60", orderID: "1518887", status: "Shipped", shipdate: "March 12, 2020", shipfrom: "IA", …}
8: {id: "2149", orderID: "1518888", status: "Shipped", shipdate: "March 12, 2020", shipfrom: "NV", …}
9: {id: "2149", orderID: "1518894", status: "Shipped", shipdate: "March 12, 2020", shipfrom: "NV", …}
length: 10
__proto__: Array(0)

When I ajax it to PHP and var_dump it I get Array(0){}. I have tried many ways from other peoples questions on this site with similar problems and this is the best result I have got, most results with other methods result in null or nothing at all.

I suspect it is all in the way I am constructing the JSON by using variables. Here is the code I am using in js. When I paste the console result to lint I get errors. I have tried sending test data to the php and get a result so I am fairly certain it is in the way I am preparing the JSON data.

$('#btnUpdate').on('click',
    function() {

        var jsonData = new Array();
        var oTable = $("#example").DataTable(); 
        oTable.rows().every(function (index, element) {

           // get tracking data
           var tableData = this.data(); 
            var gNum="https://tracking.xyz.com/api/?key=b39f008e318efd2bb988d724a161b61c6909677f&order="+tableData[4];


        $.ajax({
              url: gNum,
              dataType: 'json',
            }).done(function(data) {
                var data = JSON.stringify(data)
                var mydata=(JSON.parse(data));
                console.log(mydata);
                    if(mydata.order_info){
                        if(mydata.order_info.tracking){
                            jsObject = {
                            "id": tableData[1],
                            "orderID" : tableData[2],
                            "status": mydata.order_info.status,
                            "shipdate": mydata.order_info.ship_date,
                            "shipfrom": mydata.order_info.ship_from,
                            "track" : mydata.order_info.tracking.number,
                            "carrier": mydata.order_info.tracking.carrier
                            }
                        }else{
                            jsObject = {
                            "id": tableData[1],
                            "orderID" : tableData[2],
                            "status": mydata.order_info.status,
                            "shipdate": mydata.order_info.ship_date,
                            "shipfrom": mydata.order_info.ship_from,
                            "track" : "",
                            "carrier": ""
                            };  
                        };
                        JSON.stringify(jsObject);

                    jsonData.push(jsObject);    
                 }else{
                    alert('not found');
                };
            });

        });
        console.log(jsonData)
        //var testData = new Array();
//var record1 = {"var1":"9","var2":"16","var3":"16"};
//var record2 = {"var4":"8","var5":"15","var6":"15"};
//testData.push(record1);
//testData.push(record2);

        // send data to server to update records
$.ajax({
    type: 'POST',
    url: 'statusUpdate.php/',                      
    data: {'data': JSON.stringify(jsonData)},
    ContentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    success: function(data) {
      alert(data);
    }
});

PHP Code

<?php

$json= $_POST['data'];

$array = json_decode( $json, true );
var_dump($array);
//exit;
// getting no usable result so code below is not processed


foreach ($array as $key => $jsons) { // This will search in the 2 jsons
     foreach($jsons as $key => $value) {
        if($key == 'id') $id = $value;
        if($key == 'orderID') $orderID = $value;
        if($key == 'status') $status = $value;
        if($key == 'shipdate') $shipdate = $value;
        if($key == 'shipfrom') $shipfrom = $value;
        if($key == 'track') $track = $value;
        if($key == 'carrier') $carrier = $value;
    $sql = "UPDATE Orders SET OrderStatus=" .$status. " shippedDate=" .$shipdate. " ShippedFrom =" .$shipfrom. " TrackingNumber = " .$track. " shippedVia =" .$carrier. " WHERE customer_id = " .$id. " AND OrderNumber = " . $orderID ;
    //if (!mysqli_query($con,$sql)) {
    //  echo("Error description: " . mysqli_error($con));
    //}
    }
}
echo $id;

//database connection close
mysqli_close($con); 

?>

Update

When I send hard coded test data the response is good so this is definitely an issue with the data collected from the previous ajax. I read somewhere that the result of an ajax call is a reference to the data result and not the actual result itself. I don't know if that is true but for certain I cannot pass the data in an array either made as JSON or as a single JavaScript array.

I have tried both ways and the data is always empty on the server side except when I use the test data which is hard coded and not the result of an ajax request. I think I need to approach this problem in a whole other way, probably using curl on the server PHP side.

        var testData = new Array();
var record1 = {"var1":"9","var2":"16","var3":"16"};
var record2 = {"var4":"8","var5":"15","var6":"15"};
testData.push(record1);
testData.push(record2);

        // send data to server to update records
$.ajax({
    type: 'POST',
    url: 'statusUpdate.php',                      
    //dataType: 'json',
    data: {'data' : testData},
    //ContentType: 'application/json',
    success: function(data) {
      console.log(data);
    }
});

RESPONSE
array(2) {
  [0]=>
  array(3) {
    ["var1"]=>
    string(1) "9"
    ["var2"]=>
    string(2) "16"
    ["var3"]=>
    string(2) "16"
  }
  [1]=>
  array(3) {
    ["var4"]=>
    string(1) "8"
    ["var5"]=>
    string(2) "15"
    ["var6"]=>
    string(2) "15"
  }
}


halfer
  • 19,824
  • 17
  • 99
  • 186
  • Have you tried amending your code to get rid of the errors in Lint? – Hektor Mar 14 '20 at 17:15
  • I really don't understand what the error is referring to and even if I was able to fix the result that still doesn't tell me why the error is being generated in my code. ```Error: Parse error on line 1: []0: { id: "3340", o --^ Expecting 'EOF', '}', ',', ']', got 'NUMBER'``` Can –  Mar 14 '20 at 17:21
  • updated question with result from LINT –  Mar 14 '20 at 17:27
  • 1
    remove all those mentions of what you start with, and then how you transfrom it, etc. because that's all irrelevant to your problem: show the [mcve]: only the code that sends your data as JSON to PHP, and only the code that accepts that POST on the PHP side. As for the error at the end of your post: of course, that's invalid JSON. Do not build it yourself, use [JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)/JSON.parse in JS, and [json_encode](https://www.php.net/manual/en/function.json-encode.php)/json_decode in PHP. – Mike 'Pomax' Kamermans Mar 14 '20 at 17:42
  • Mike I have done as you suggested is that better ? –  Mar 14 '20 at 18:08

3 Answers3

0

In your Ajax request, you should use FormData() example:

 $.ajax({
        url: 'url',
        method: 'post',
        data: new FormData($('#form-id')[0]),
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {
            console.log(response)

        }

    });
  • What about dataType? – Michael Nelles Mar 14 '20 at 18:27
  • Tried using dataType="json" many times before. Result from var_dump is empty take it out and at least I get Array(0){ } .. even if that is also empty –  Mar 14 '20 at 18:44
  • I am not using forms. My data is from ajax results and a datatables.net table –  Mar 14 '20 at 18:45
  • You can send JSON body, added the dataType: 'json' in your request, like example – Railson Luna Mar 14 '20 at 19:00
  • data: new FormData($('#form-id')[0]), ?? I do not understand how that can work in my case since there are no forms or form elements on my page –  Mar 14 '20 at 19:10
0

Try this:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
        console.log('sasd');
        function myFunction () {
            console.log('sasd');

            $.ajax({
                url: 'http://localhost:8081/',
                method: 'POST',
                dataType: 'json',
                data: {
                    "id": 'id',
                    "orderID" : "orderID",
                    "status": "status",
                    "shipdate": "shipdate",
                    "shipfrom": "shipfrom",
                    "track" : "",
                    "carrier": ""
                },
                success: function (response) {
                    console.log(response)

                }

            });
        }

    </script>

    <title>Title</title>
</head>
    <body>
        <button onclick="myFunction()">Click me</button>
    <?php
        var_dump($_REQUEST);
    ?>
    </body>
</html>
  • you do know that the data is an array right? There are 10 array indices of id as I posted at the beginning of my question, if you look at the code I posted you will see that from the console output I posted. Having said that, running your code resulted in an empty return. –  Mar 14 '20 at 20:25
  • For see the return in my code, open you network request by your browser – Railson Luna Mar 14 '20 at 20:27
0

Looks like what is happening is that the first ajax call which populates the JSON array is not complete and with the way I have this written, the script is already calling my PHP script before the JSON array is even populated by the 1st ajax call. So this is an asynchronous issue that can only be solved by me re-writing my code to use promises and callbacks before sending the data to the server.

Reference here > https://stackoverflow.com/questions/8847829/what-is-difference-between-success-and-done-method-of-ajax