3

I have mysql database. On my page, when I click on a button I retrive data from database. All data are displayed on page. I get one row with id, one row with name and one row with number (in input field). So one example is that I get:

51

Table

200


52

Head

320


53

Glass

456


Because all value number (3rd row) are in input fields they can be changed. I created submit button so I can submit changed values. Here is my js code:

$(document).ready(function () {
        $("#submit2").click(function () {
        event.preventDefault();
        $('form#list_prices_form input[type=number]').each(function () {
        default = $("#default").val();
        var value = $(this).val();
        var id = $(this).attr("name");
        console.log(id);
        console.log(value);
        });

        $.ajax({
                    type: "POST",
                    url: "save.php",
                    data: {default: default, value: value, id: id},
                    success: function (response) {
                        default = $("#default").val();
                    $.ajax({
                        type: "POST",
                        url: "retrive.php",
                        data: {default: default},
                        success: function (response) {
                            $('#list').html(response);
                        }  
                    });
                    }
                });
                return false;
        });
        });

So in console I get all necessary fields. They show correct id and value for each field. But it shows error in console:Uncaught ReferenceError: value is not defined

And php code:

        $default = $_POST['default'];
        $value = $_REQUEST['value'];
        $id = $_REQUEST['id'];

        $result = $conn->query("SELECT * FROM tbl_name WHERE default = '$default'";
            $query = "UPDATE tbl_name SET (value_row) VALUES(?) WHERE id='$id'";
            $statement = $conn->prepare($query);
            $statement->bind_param('i', $value);
            if ($statement->execute()) {
                echo 'Changed';
               //print 'Success! ID of last inserted record is : ' . $statement->insert_id . '<br />';
            } else {
                die('Error : (' . $conn->errno . ') ' . $conn->error);
            }
            $statement->close();
3
  • i can see that you are creating a multiple number boxes but while doing Ajax you are just passing single row. Why is that? Commented Dec 27, 2015 at 13:09
  • Hm...I assigned each function for each .value class so I passed every row? Commented Dec 27, 2015 at 13:11
  • oh..sorry...I haven't seen .each. Instead of multiple ajax I would suggest to pass an array. And at server side read that array and have for loop to iterate over incoming array. Commented Dec 27, 2015 at 13:14

2 Answers 2

1

The first issue seems to be your <input> doesn't have a name. Therefore a browser won't submit that element. This is as per the W3 spec for successful controls.

Instead of setting the id try setting the name attribute as well.

For example

echo "$x: <input class='value' id='$id' name='$ID' value='$y' />";

Note you're much better submitting these variables via POST rather than GET. Doing so means that the data in the URI is much less likely to be logged by any middleware. Thus your JQuery AJAX would look like:

$.ajax(
  type: 'post',
  url: "update.php",
  data: {id: id, value: value},
  success: function(responseData) {
    console.log("Result" + responseData);
  }
});

Now, since you're posting JSON and not form-encoded data, you'll need to read in JSON from the PHP script:

$json = file_get_contents('php://input');
$obj = json_decode($json);
var_dump($obj); // show what data is in there for your debugging.

It will look a little like:

$obj->id; // the id POST'ed
$obj->value; // the value POST'ed

It may also be beneficial to reduce the number of POST requests you're making by aggregating the fields to send before POSTing.

e.g.

var values = [];
$(".value").each(function () {
  var getId = $('.value').prop('id');
  var id = $(getId).val();
  var getValue = $('.value').prop('value');
  var value = $(getValue).val();
  values.push({id: id, value: value});
});

$.ajax(
  type: 'get',
  url: "update.php",
  data: values,
  success: function(responseData) {
    console.log("Result" + responseData);
  }
});

If you do so then your PHP code will then need to look something like this:

$postData = file_get_contents('php://input');
$postJson = json_decode($postData);
$results = [];
foreach($postJson as $row) {
  // $row->id  and $row->value
  $sql = "UPDATE table SET y='{$row->value}' WHERE ID = '{$row->id}'";

  if ($conn->query($sql) === TRUE){
    $results[$row->id] = 'updated';
  } else {
    $results[$row->id] = 'error';
  }
}
$conn->close();
echo json_encode($results); // Return a list of ID => success/error

Note: All of the above is entirely untested given your database etc. etc

More importantly this code does not address any injection vulnerabilities. You should escape AND validate your input data before running ANY database operations

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, Thanks for your answer, but nothing happens after submit click. I pushed all variables in array and than I added your piece of php code in my update.php. But same thing again....no errors in console but row doesn't update...
and I found error in php Invalid argument supplied for foreach()
0

Your jQuery should be like this:

$(document).ready(function(){
    $('#submit').click(function(e) {
        e.preventDefault();
        $(".value").each(function(){
            var id = $(this).attr('id');
            var value = $(this).attr('value');
            $.ajax({
                type: 'get',
                url: "update.php",
                data: {id: id, value: value},
                success: function(){

                }
            });
        });
    });
});

8 Comments

@KondukterCRO I've recreated the issue partially with the updated jQuery snippet, and it's working fine for me. What is the issue you're facing now?
Still nothing happens. Page doesn't reload but values aren't updated.
@KondukterCRO First of all , install firebug addon in your browser to see whether you're passing the values correctly or not. Second, table is a MySQL reserved keyword, so you'll have to escape it with backticks, like this: $sql = "UPDATE `table` SET y='$value' WHERE ID = '$id'";. And third, please update your question with your table table so that I could recreate the issue precisely.
Thanks for effort. I updated my question so you can see what I get.
@KondukterCRO I meant update your question with your table contents i.e whatever you have in table table, because only after seeing the table I can recreate the issue precisely.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.