0

I am trying to send multiple data with jQuery.ajax. The combobox product1 and the textbox price are working. But when I try to send the text of quantity something goes wrong.

index.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM forms";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "<select class='form-control select2' id='product1' onChange='getPrice(this.value)' name='product1' style='width: 100%;'>";
     echo "<option selected disabled hidden value=''></option>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
                      echo "<option value='" . $row["id"]. "'>" . $row["naam"]. "</option>";
     }                   
echo "</select>";
} else {
     echo "0 results";
}

$conn->close();

?>
<html>
<body>
<!-- Your text input -->
<input id="quantity" type="text" placeholder="quantity">

<!-- Your text input -->
<input id="product_name" type="text" placeholder="product_name">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {

    // getting the selected id in combo
    var selectedItem = jQuery('#product1 option:selected').val();

    // Do an Ajax request to retrieve the product price
jQuery.ajax({
    url: 'get.php',
    method: 'POST',
data: 'id=' + selectedItem + ', quantity:document.getElementById('quantity').value,
    success: function(response){
        // and put the price in text field
        jQuery('#product_name').val(response);
        jQuery('#quantity').html(response);        },
    error: function (request, status, error) {
        alert(request.responseText);
    },
}); 
}
</script>
</body>
</html>

get.php

<?php

// Turn off all error reporting
error_reporting(0);

?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) 
    {
    die('Connection failed: ' . $conn->connect_error) ;
    } 
else 
    {
    $product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
    $quantity = filter_input(INPUT_POST, 'html', FILTER_SANITIZE_NUMBER_INT) ;

    $query = 'SELECT price * ' . $quantity . ' FROM forms WHERE id=' . $product1 . ' ';

    $res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) 
{
    $result = mysqli_fetch_assoc($res) ;
    echo $result['price'];
}else{
    echo "0 results";
}

    }

?>

Can someone help me with this?

13
  • 2
    What goes wrong? "something" goes wrong is not descriptive enough to be helpful. post what your error / log / errorlog is. Commented Feb 21, 2016 at 2:48
  • I dont get any error. I try to run a SQL query: SELECT price * ' . $quantity . ' FROM forms WHERE id=' . $product1 . ' but nothing is happening. Commented Feb 21, 2016 at 2:49
  • have you tried to check if your SQL query is forming correctly? by either debugging/ doing a print_r then exit. Commented Feb 21, 2016 at 2:50
  • Yes, I tried it in phpmyadmin and it is working there Commented Feb 21, 2016 at 2:52
  • 1
    No you don't understand, do you know FOR SURE if your $quantity and $product1 is being set correctly so that your SQL statement is correctly formed? Commented Feb 21, 2016 at 2:53

4 Answers 4

1

try this in index.php:

data: {'id': selectedItem, 'quantity' : jQuery('#quantity').val()},

and modify get.php.

$product1 = isset($_POST['id'])?$_POST['id']:'';
$quantity = isset($_POST['quantity'])?$_POST['quantity']:'';
$query = 'SELECT price * ' . $quantity . ' AS price FROM forms WHERE id=' . $product1 . ' ';
Sign up to request clarification or add additional context in comments.

Comments

0

Put

<input id="quantity" type="text" placeholder="quantity" value="<?php echo $quantity; ?>">
<input id="product_name" type="text" placeholder="product_name" value="<?php echo $product_name; ?>"> 

In get.php and set its values by echo'ing it into the inputs.

Write the data to a div in index.php with

$("#yourdiv").html(response);

3 Comments

Not working. I get Uncaught SyntaxError: Unexpected string (index):22 Uncaught ReferenceError: getPrice is not definedonchange @ (index):22 and Uncaught ReferenceError: getPrice is not defined @ (index):1 in my developer tool console
You are using jquery wrong. You cant split the response the way you do
I can rewrite your code for you in about 6 hours. So if you can wait... give me the full code you have now and ill fix it for you tonight (timezone over here ECT)
0

It's hard to tell what's going on there without any error messages, and I'm not sure I fully understand what you're trying to accomplish.

Are you talking about it not working when you un-comment the last line here?

success: function(response){
    // and put the price in text field
    jQuery('#product_name').val(response);
    // jQuery('#quantity').val(response);
}

That line says to populate the quantity field with all the data that comes back from PHP. Do you want to store the same value (response) in the product_name field and in the quantity field? If you want to SEND the quantity to the PHP script, you need to include it's value in the DATA portion:

data: 'id=' + selectedItem + ', qty=' + $('#quantity').val(),

I would suggest sending back a JSON object with the values you want, and then put those values into the appropriate fields.

$array["qty"] = $row[i]["qty"];
$array["cost"] = $row[i]["cost"];

echo json_encode($array);

When you get the data back from PHP you can do something like this...

resultInfo = JSON.stringify(response);
jQuery('#product_cost').val(resultInfo["cost"]);
jQuery('#quantity').val(resultInfo["qty"]);

In PHP, make sure it's reading the qty as a number so SQL isn't trying to multiply (cost * '2') instead of (cost * 2).

$qty = (int)$_POST("qty"); //capture it as an integer

Depending on how secure you need this to be, it's worth mentioning that you may want to look into sanitizing your input. I would suggest using PDO with prepared statments.

I hope something here may be able to help you.

1 Comment

The code is working without quantity. When I expend it with quantity and make calculations in sql (see get.php in my first post) nothing will happen. Also the things that worked before (like #product_name) are not working. When I delete quantity. I can see the price of one individual product. When I want to calculate the total price (price * quantity = totalprice) nothing is happening in my script. I think that I post quantity in the wrong way.
0

Modify your code a little to

data:{ 
   id:selectedItem, 
   quantity:document.getElementById('quantity').value 
}, 

1 Comment

No, I still dont get a result. Is it possible that i need to add something like var selectedItem = jQuery('#product1 option:selected').val(); for quantity. Or that jQuery('#quantity').html(response); in index.php or $quantity = filter_input(INPUT_POST, 'html', FILTER_SANITIZE_NUMBER_INT) ; in get.php is wrong?

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.