2

I am writing a web page which reads data from an html table to be used on a MySQL query using PHP. This is a continuation of this question. I got AJAX send the data I need to use on to the PHP file with the code to update the information it sent. However, two errors have occured.

  1. I get a message saying Error:Error: jQuery21405680291895882033_1487801210725 was not called

  2. The data I send has a ":1" at the end of it, giving me an error.

How can I fix these two mistakes? Thank you so much!

JS code:

function getTableData(){
            var array = [];
            var headers = [];
            $('#tablaListado th').each(function(index, item) {
                headers[index] = $(item).html();
            });
            $('#tablaListado tr').has('td').each(function() {
                var arrayItem = {};
                $('td', $(this)).each(function(index, item) {
                    if($(this).find("textarea").length){
                        var costo = $(this).find('textarea').val();
                        arrayItem[headers[index]] = costo;
                    }else{
                        arrayItem[headers[index]] = $(item).html();
                    }
                });
                array.push(arrayItem);
            });

            actualizarCostos(array);
        }

        function actualizarCostos(array){
            if(array.constructor === Array){
                for(var i = 0; i < array.length ; i++){
                    console.log(array[i]);
                    console.log(JSON.stringify(array[i]));
                    $.ajax({
                        url: "http://www.page.com/Update.php",
                        contentType: "application/json; charset=utf-8",
                        dataType: "jsonp",
                        jsonp: false,
                        jsonpCallback: jsonCallback,
                        cache: true,
                        data:{ "table_data": JSON.stringify(array[i])},
                        success: function (data) {
                            console.log(data);
                        },
                        error: function(xhr,status,err){
                             alert("DEBUG: status"+status+" \nError:"+err);
                         }, 
                        traditional: true
                    });
                }
            }else{
                alert("Input must be array");
            }
        }

        function jsonCallback(data, status){
            console.log(data + " " + status);
        }

PHP portion:

//Added on top of the page
header('Access-Control-Allow-Origin: *');
...
function updateCosts($json){
            conectar();
            $array = json_decode($json, true);
            echo "<script>console.log('$array');</script>";
            $costo = $array["Costo"];
            $sku = $array["SKU"];
            $instruccion = "UPDATE articulos SET art_cost='$costo' WHERE art_SKU = '$sku'";

            return ejecutarInstruccion($instruccion);
}

if(isset($_GET['table_data'])){
           foreach($_GET['table_data'] as $index => $item)
           {
                  // do something here 
                  echo "<script>console.log('$item');</script>";
                  updateCosts($item);
           }

           // Response back - if needed
           echo json_encode(array('status'=>true, 'msg'=>'Some Message'));
}

Edit:

I forgot to mention that I have tried changing 'jsonp' as 'json' on this code but I get an error saying the PHP file doesn't allow foreign data, even though I tried using header('Access-Control-Allow-Origin: *') on said file.

Community
  • 1
  • 1
Julio Garcia
  • 393
  • 2
  • 7
  • 22

2 Answers2

2

Your page is returning JSON, not JSONP. They aren't interchangeable. Remove the jsonp and jsonpCallback properties from the $.ajax() call, and change dataType to json:

$.ajax({
    url: "http://www.page.com/Update.php",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    cache: true,
    data: { 
        table_data: JSON.stringify(array[i])
    },
    success: function (data) {
        console.log(data);
    },
    error: function(xhr,status,err){
        alert("DEBUG: status" + status + " \nError:" + err);
    }, 
    traditional: true
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you for reminding me, I have edited the post with the information as to why I can't use `'json'` – Julio Garcia Feb 23 '17 at 16:10
  • I that case you need to add the `Access-Control-Allow-Origin` header to the response from your PHP page, so that the browser explicitly knows that it should not block this request due to the Same Origin Policy. As I touched on above, JSONP is entirely different from JSON. To use that would mean changing the response format of your PHP code entirely. – Rory McCrossan Feb 23 '17 at 16:10
  • I added it on the top of the PHP file, does it go on the if statement instead? – Julio Garcia Feb 23 '17 at 16:11
  • I only have a passing knowledge of PHP so can't give you a definitive answer, but that sounds like it should be working. Check the received headers in the network tab of the console after you make the request – Rory McCrossan Feb 23 '17 at 16:12
  • I did that and I get the following error: `Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.` – Julio Garcia Feb 23 '17 at 16:16
  • You need to add `Content-Type` to the `Access-Control-Allow-Headers` header – Rory McCrossan Feb 23 '17 at 16:20
  • Thanks, that did the trick :) I cannot get the PHP file to do the `echo ' – Julio Garcia Feb 23 '17 at 16:24
1

I'd suggest you have the following AJAX:

function actualizarCostos(array){
        if(array.constructor === Array){
            for(var i = 0; i < array.length ; i++){
                console.log(array[i]);
                console.log(JSON.stringify(array[i]));
            }
            $.ajax({
                url: "http://www.page.com/Update.php",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data:{ "table_data": JSON.stringify(array)},
                success: function (data) {
                    console.log(data);
                },
                error: function(xhr,status,err){
                    alert("DEBUG: status"+status+" \nError:"+err);
                }
            });
        }else{
            alert("Input must be array");
        }
    }

Then do the For-Loop on the PHP side of the server. Maybe each variable in array has a hidden parameter to know its own index, or JSON is doing something strange like displaying the number of elements in the array (in this case 1 because you're iterating over each one)

SsJVasto
  • 486
  • 2
  • 13
  • If I iterate through each one wouldn't that give me a `:1` and `:2`? – Julio Garcia Feb 23 '17 at 16:25
  • `or JSON is doing something strange like displaying the number of elements in the array` that would give `:1` on each item, or a `:23` on a 23-item list... I'm not 100% on that, it's hard to say without debugging... – SsJVasto Feb 23 '17 at 16:50