0

I have a table with three fields. Two are dropdown and one is input field. I have to compare value of input field and stock quantity based on dropdown field.

How to do with ajax?

function compareData() {

    var quantity = document.getElementsByName('quantity[]');
    var stockName = document.getElementsByName('stockName[]');
    var oldQnt = [];

    $.ajax({
        url: 'php_action/fetchStockas.php',
        type: 'post',
        async: true,
        data: { stock: stockName },
        dataType: 'json',
        success: function(data) {
            oldQnt.push(data);

        }

    });
    for (var x = 0; x < quantity.length; x++) {
        alert(quantity[x].value);
        // alert(oldQnt[x].value);

    }
}

PHP code:

<?php 
    require_once 'core.php'; 

    $stock=$_POST['stockNmame']; 

    $sql = "SELECT st_id, st_item_name, st_price, st_quantity FROM stock WHERE st_item_name='$stock'"; 
    $result = $connect->query($sql); 
    $output = array('data' => array()); 
    if($result->num_rows > 0) { 
        while($row = $result->fetch_array()) { 
            $stockId = $row[0]; 
            $stockName=$row[1]; 
            $stockPrice=$row[2]; 
            $stockQuantity=$row[3]; 
            $output['data'][] = array( $stockName, $stockPrice, $stockQuantity, ); 
        } 
    } 
    $connect->close(); 
    echo json_encode($output);
KungWaz
  • 1,918
  • 3
  • 36
  • 61
Sani Kamal
  • 1,208
  • 16
  • 26
  • It's not clear what you're asking, or what you want to do, however I'm pretty sure you just need to place your `for` loop (where you'll do the comparison to the received data) inside the `success` handler so that it executes *after* the AJAX request completes – Rory McCrossan Jan 30 '18 at 09:35
  • Yeah, if you want what you commented out to work.. (assuming the server side script is working correctly) then place the for loop inside the ajax sucess function. – Eladian Jan 30 '18 at 09:38
  • 1
    The first "a" in `ajax` stands for "asynchronous", so your `success` callback will run after the `for` loop. Try to put your `for` loop in the `success` callback, like the others said. – Passerby Jan 30 '18 at 09:39
  • If you add the relevant part of the HTML it would make it easier to understand what you are trying to achieve. – KungWaz Jan 30 '18 at 10:05
  • Keep in mind that your php code in vunerable for SQL injection, and can easily be hacked, See: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php . I recommend you switch to mysqli or pdo with prepared statements. – Arend Jan 31 '18 at 12:40

1 Answers1

0

I have tried to figure out what you want to achieve, but still not clear if you want to get all options from the drop downs or only the selected option. I have created a code snippet which uses both of them, and explains the difference. The return data you get on success in the AJAX request I have mocked, but you need to add that yourself.

var mockData = {
    stockName: null,
    stockPrice: 0,
    stockQuantity: 0
}

function setMockData() {
    mockData = {
        stockName: $('#stockNameMock').val(),
        stockPrice: parseInt($('#stockPriceMock').val(), 10) || 0,
        stockQuantity: parseInt($('#stockQuantityMock').val(), 10) || 0
    }
}

function compareData() {
    var siteName = $('#siteName').val(), // Get the selected site name
        stockName = $('#stockName').val(), // Get the selected stock name
        quantity = parseInt($('#quantity').val(), 10) || 0; // Get the selected quantity
    
    setMockData(); // Set mock data

    $.ajax({
        url: '/echo/json/', // Replaced for mocking
        type: 'post',
        async: true,
        data: {
            json: JSON.stringify(mockData) // Added for mocking
        },
        dataType: 'json',
        success: function(data) {
            if(data.stockName === stockName) {
                if(data.stockQuantity < quantity) {
                    $('#statusMessage').text('Stock quatity to low');
                } else {
                    $('#statusMessage').text('-');
                }
            } else {
                $('#statusMessage').text('Stock name mismatch');
            }
        }

    });
}

$('#submit').on('click', compareData);

setMockData();
#statusMessage {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>MOCK DATA</h2>
Stock name: <input id="stockNameMock" type="text" value="stock1" /><br/>
Stock price: <input id="stockPriceMock" type="number" value="10" /><br/>
Stock quantity: <input id="stockQuantityMock" type="number" value="5" /><br/>

<h2>INPUT</h2>
Site Name:
<select name="siteName" id="siteName">
    <option value="site1">site1</option>
    <option value="site2">site2</option>
    <option value="site3">site3</option>
</select><br/>
Stock name:
<select name="stockName" id="stockName">
    <option value="stock1">stock1</option>
    <option value="stock2">stock2</option>
    <option value="stock3">stock3</option>
</select><br/>
Quantity:
<input type="number" name="quantity" id="quantity" value="0" /><br/>
<button type="button" id="submit">Submit</button>
<br/>
<br/>
<div>Status: <span id="statusMessage">-</span></div>

You can experiment with this code here: https://jsfiddle.net/knfnaouy/2/

It seems like the mocking is not working here on SO, so look at the fiddle.

KungWaz
  • 1,918
  • 3
  • 36
  • 61
  • Actually my first dropdown is site_name the second is Stock Name and the third is a input field name quantity. I have to comapre quantity with stock_quantity based on stock_name. And then show pop up is that your provide quantity is less or grater than Stock_quantity. I provide my php code below... – Sani Kamal Jan 30 '18 at 12:21
  • query($sql); $output = array('data' => array()); if($result->num_rows > 0) { while($row = $result->fetch_array()) { $stockId = $row[0]; $stockName=$row[1]; $stockPrice=$row[2]; $stockQuantity=$row[3]; $output['data'][] = array( $stockName, $stockPrice, $stockQuantity, ); } } $connect->close(); echo json_encode($output); – Sani Kamal Jan 30 '18 at 12:23
  • To start with, you have a typo in "StockNmame" in the PHP code, does that solve it? – KungWaz Jan 31 '18 at 11:55
  • I have updated my code snippet to show how it could work, but I think you only have a typo for how you read the stock name to get your SQL to work. – KungWaz Jan 31 '18 at 12:27