send named arrays to PHP via ajax - javascript

I need to submit a dynamically created field set via ajax call to a php to insert the data to DB. The list is for product items for a specific supplier. I need to make a ajax call , but dont know how to submit the named arrays in data field.
My HTML:
<div class='col-md-2 '><input name="item_number[]" id="item_number" class="form-control" placeholder='item number' /></div>
<div class='col-md-4 '><input name="description[]" id="description" class="form-control" placeholder='description' /></div>
<div class='col-md-1 '><input name="quantity[]" id="quantity" class="form-control" placeholder='Quantity' /></div>
<div class='col-md-2 '><input name="unit_price[]" id="unit_price" class="form-control" placeholder='Unit Price' /></div>
<div class='col-md-2 '><input name="sales_price[]" id="sales_price" class="form-control" placeholder='Sales Price' /></div>
<div><button name="add_item" id="add_item" class="btn btn-primary">+</button></div>
How can i get the value set posted to my PHP file and then insert them via a for loop
My PHP file is as below:
$supplier_selection = $_POST['supplier_id'];
$item_id = $_POST['item_id'];
$array_description = $_POST['description'];
$array_quantity = $_POST['quantity'];
$array_unit_price = $_POST['unit_price'];
$array_sale_price = $_POST['sale_price'];
foreach ($item_id as $key => $value) {
$check_item_id = "SELECT item_id from products where item_id='" . $mysqli->real_escape_string($item_id [$key]) . "'LIMIT 1";
$resultset = $mysqli->query($check_item_id);
if ($resultset->num_rows == 0) {
//perform insert to table
$insert_product = "INSERT INTO `products` (`id`, `item_id`, `supplier_id`, `description`, `quantity`, `purchase_price`, `retail_price`) "
. "VALUES (NULL, '" . $mysqli->real_escape_string(item_id) . "','$supplier_selection', '" . $mysqli->real_escape_string($array_description[$key]) . "', '" . $mysqli->real_escape_string($array_quantity[$key]) . "', '" . $mysqli->real_escape_string($array_unit_price[$key]) . "', '" . $mysqli->real_escape_string($array_sale_price[$key]) . "')";
$insert_item = $mysqli->query($insert_product);
if (!$insert_item) {
echo $mysqli->error;
echo "<script>";
echo "alert('Error inserting!')";
echo "</script>";
} else {
echo "successfully inserted" . $mysqli->real_escape_string($item_id[$key]) . "";
echo "<script>";
echo "alert('Items Added successfully')";
echo "</script>";
}
}
}

I think you use jQuery and $.ajax so you can just serialize the form you need and it will gather all data from the form in proper format:
$('#form_id').serialize()
You can insert it into the data param into $.ajax call
$.ajax({
url: '/your/url/here',
data: $('#form_id').serialize()
});
In the php code it is very stupid to make DB queries in the loop.
I see you are getting data from the HTML form by POST request so there will not be millions of items to loops through.
Here is the more efficient code you may use, kinda 2 times less amoutn of DB queries:
<?php
$supplier_selection = $_POST[ 'supplier_id' ];
$item_id = $_POST[ 'item_id' ];
$array_description = $_POST[ 'description' ];
$array_quantity = $_POST[ 'quantity' ];
$array_unit_price = $_POST[ 'unit_price' ];
$array_sale_price = $_POST[ 'sale_price' ];
//get all item IDs received
$all_keys = array_keys( $item_id );
//get all items in DB with item_id in received array
$not_to_insert_sql = "SELECT item_id from products where item_id IN (" . implode( ',', $all_keys ) . ")";
$not_to_insert = $mysqli->query( $not_to_insert_sql );
//need to get only IDs
for ( $i = 0, $c = count( $not_to_insert ); $i < $c; ++$i ) {
$not_to_insert[] = $not_to_insert[ $i ][ 'item_id' ];
}
//let's get difference between what's in the array and what is already in DB
$to_insert = array_diff( $all_keys, $not_to_insert );
// let's loop only what we need to insert
for ( $i = 0, $c = count( $to_insert ); $i < $c; ++$i ) {
//perform insert to table
$insert_product = "INSERT INTO `products` (`id`, `item_id`, `supplier_id`, `description`, `quantity`, `purchase_price`, `retail_price`) "
. "VALUES (NULL, '" . $mysqli->real_escape_string( item_id ) . "','$supplier_selection', '" . $mysqli->real_escape_string( $array_description[ $key ] ) . "', '" . $mysqli->real_escape_string( $array_quantity[ $key ] ) . "', '" . $mysqli->real_escape_string( $array_unit_price[ $key ] ) . "', '" . $mysqli->real_escape_string( $array_sale_price[ $key ] ) . "')";
$insert_item = $mysqli->query( $insert_product );
if ( ! $insert_item ) {
echo $mysqli->error;
echo "<script>";
echo "alert('Error inserting!')";
echo "</script>";
}
else {
echo "successfully inserted" . $mysqli->real_escape_string( $item_id[ $key ] ) . "";
echo "<script>";
echo "alert('Items Added successfully')";
echo "</script>";
}
}

Related

how to generate this code mysql_fetch_array in codeigniter

how do I write mysql_fetch_array code in codeigniter
<?php
$result = mysql_query("select * from tb_mhs");
$jsArray = "var dtMhs = new Array();\n";
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['nim'] . '">' . $row['nim'] . '</option>';
$jsArray .= "dtMhs['" . $row['nim'] . "'] = {nama:'" . addslashes($row['nama']) .
"',jrsn:'".addslashes($row['jurusan'])."'};\n";
}
?>
Form Input :
<td><input type="text" name="nm" id="nm"/></td>
<td><input type="text" name="jrsn" id="jrsn"/></td>
Javascript :
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(nim) {
document.getElementById('nm').value = dtMhs[nim].nama;
document.getElementById('jrsn').value = dtMhs[nim].jrsn;
};
</script>
If you want to return result as a array from the database, you can use something like this
// in application/config/autoload.php, make database available globally
$autoload['libraries'] = array('database');
// fetch the results from the database
$query = $this->db->get('tb_mhs'); // produces select * from tb_mhs
// get the result as a array
$result = $query->result_array();
// to do the other operations you were doing you can use a loop
foreach ($result as $key => $item) {
// do stuff
}

cannot get my seemingly simple js submit form function to work on wordpress

I have been following a few tutorials online for how to do this, and I do not know where I missed the mark... when I press my submit button, it does nothing but reload the page. I do not see any errors in loading my js though in the console of chrome so I think that might be my issue. But still unsure.
Basically, people can provide a new billing_address on their dashboard, and the billing address is associated with a user and sku.
Here is my form with three items (user, sku, address);
$loop = new WP_Query( $args );
echo '<form id="addressform" method = "post">';
echo '<br><select id="sku" name="sku" required >';
echo '<option value="empty">-- Select Coin--</option>';
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<option value=' . $product->get_sku() . '>' . $product->get_sku() . ' </option>';
endwhile;
echo '</select>';
echo '<input type="text" placeholder="Insert new address here" id="address" name="address" size="40" required />';
echo '<input type="hidden" id="userid" name="userid" value="' . $userid . '">';
echo '<input type="submit" id="submit" name="submit" value="Submit">';
echo '</form>';
echo '<div class="alert alert-danger display-error" style="display: none"></div>';
here is my javascript file known as address_submit.js
jQuery(document).ready(function($) {
jQuery('form#addressform').on('submit', function(e){{
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: submitaddress_ajax_obj.ajaxurl,
data: {
'userid' : jQuery('form#addressform #userid').val(),
'sku' : jQuery('form#addressform #sku').val(),
'address' : jQuery('form#addressform #address').val(),
'action' : 'submitaddress'
},
success : function(data){
if (data.code == "200"){
alert("Success: " +data.msg);
} else {
jQuery(".display-error").html("<ul>"+data.msg+"</ul>");
jQuery(".display-error").css("display","block");
}
}
});
e.preventDefault();
});
});
and lastly, I knew I needed to add it to my functions.php for my child theme so I created a second file (address_verifier.php) and included it like this in my themes functions.php :
require_once( __DIR__ . '/include/address_verifier.php');
And lastly, here is what is in the address_verifier.php
function submitaddress_ajax_enqueue() {
// Enqueue javascript on the frontend.
wp_register_script('submitaddress-ajax-script', get_stylesheet_directory_uri() . '/js/address_submit.js', array('jquery') );
wp_enqueue_script('submitaddress-ajax-script');
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script('submitaddress-ajax-script','submitaddress_ajax_obj',array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),'loadingmessage' => __('Submitting Address...') ));
}
add_action( 'wp_enqueue_scripts', 'submitaddress_ajax_enqueue' );
add_action( 'wp_ajax_submitaddress', 'submitaddress' );
add_action( 'wp_ajax_nopriv_submitaddress', 'submitaddress' );
function submitaddress() {
global $woocommerce,$wpdb,$product;
$errorMSG = [];
//check if data is present
$user = $_POST['userid'];
//check sku selected
if (empty($_POST['sku'])) {
$errorMSG .= "<li>Please select a product.</li>";
} else {
$sku = $_POST['sku'];
}
//check address input
if (empty($_POST['address'])) {
$errorMSG .= "<li>Please enter an address.</li>";
} else {
$address = $_POST['address'];
}
if(empty($errorMSG)){
$updateaddress = $wpdb->query( $wpdb->prepare("REPLACE INTO ".$wpdb->prefix."newaddress (user, sku, address) VALUES (%d, %s, %s)", $user, $sku, $address ) );
$msg = "<strong> <i class='fa fa-check' aria-hidden='true'></i> Your <font color='red'>" . $sku . " </font>address has been updated. </strong>";
echo json_encode(['code'=>200, 'msg'=>$msg]);
die;
}
echo json_encode(['code'=>404, 'msg'=>$errorMSG]);
die();
}
move e.preventDefault(); to the top of the function.

Undefined index after json_decode

I have a problem when I'm trying to get the contents of a JavaScript Array and pass its value to a PHP Array Variable.
What I'm doing is that, when a user clicks a button, the value of the item clicked will be added to the javascript array and every time the javascript array updates, the PHP variable will also update and so the contents of the div displaying the contents of the PHP array. I'm not using forms for this matter but buttons
However, when I try to use the json_decode function to get the values of a JavaScript array, it's giving me a Message: undefined index: data error
I'm a beginner in JavaScript, jQuery and AJAX so please bear with me
This is my code:
<script>
// ARRAY VARIABLE WHERE ITEM VALUES WILL BE STORED
var food_item = new Array();
// FUNCTION TO BE TRIGGERED WHEN USER CLICKED THE BUTTON, GET THE ITEM'S VALUE AND ADD IT TO ARRAY
function addToTray(data){
food_item.push(document.getElementById(data).value);
dataString = food_item; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "main",
data: {data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
}
</script>
<body>
...
// LINE OF CODE RESPONSIBLE FOR FETCHING JAVASCRIPT ARRAY VALUES
$this->session->userdata['food_tray'] = json_decode($_POST['data']);
// DIV TO BE UPDATED
<div class="col-md-3 food-tray" id="food-items" style="margin-top: 7%">
<!--FOOD TRAY-->
<div class="panel-heading">
<h3 class="ft-header">Food Tray</h3>
</div>
<div class="panel-body">
<?php
$count_fi = count($this->session->userdata('food_tray'));
echo "<p>Your Items (" . $count_fi . ")</p>";
if($count_fi == 0){
echo "<p class='no-avail-list'>NO ITEMS ADDED IN FOOD TRAY</p>";
}else{
echo "<table class='table borderless'>";
for($i = 0; $i < $count_fi; $i++){
echo "<tr>";
echo "<td>" . $this->session->userdata['food_tray'][$i] . "</td>";
echo "<td>P 200.00</td>";
echo "<td><form method='post'><input type='number' name='qty' min='1' max='100' value='1'/></form></td>";
echo "</tr>";
}
echo "</table>";
echo "<a href='' class='btn btn-success' data-toggle='modal' data-target='#myModal'>
Add Friend</a>";
echo "<a href='".base_url()."index.php/CheckOut' class='btn btn-warning'>Proceed to Checkout</a>";
}
?>
</div>
</div>
...
<?php
foreach($query->result() as $row){
echo "<div class='col-lg-7'>";
echo "<div class='thumbnail'>";
$file_name = strtolower(preg_replace('/[^A-Za-z0-9\-.]/', '', $row->name));
/*if(file_exists(FCPATH . '/assets/images/main/food/' . $file_name . '.jpg')){
echo "<img src='".base_url()."/assets/images/main/food/".$file_name.".jpg' alt='' width='320px' height='100px'>";
}else{
echo "<img src='http://placehold.it/320x150' alt=''>";
}*/
echo "<img src='http://placehold.it/320x150' alt=''>";
echo "<div class='caption'>";
echo "<h5 class='pull-right'>&#x20B1 " . $row->price . "</h5>";
echo "<h5><a href='#'>" . $row->name . "</a></h5>";
echo "<h5>Calorie Count : " . ($row->calorie_count == NULL ? "Not Available" : $row->calorie_count) . "</h5>";
// BUTTON FOR `addToTray()` FUNCTION
echo "<button class='btn btn-primary' id='".$row->id."' value='".$row->name."' style='width:100%' onclick='addToTray(".$row->id.")'>Add to Tray</button>";
// var_dump($row->name);
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
</body>
Anyone who knows how to solve this problem? Any help would be appreciated.
create your session as
$array = array ('food_tray' => json_decode($javascriptarray));
$this->session->set_userdata($array);
check if your javascript libraries are loaded in sources tab.

Oop check if database table is empty

I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D

Generating more MYSQL database results when a dropdown list is selected

hope you can help
I want to have a drop down list that searches my mysql database and shows the first and last names of the users. You can then select any of the names and it will generate the rest of the membership details (i.e. date signed up, last logged in etc).
I have got the dropdown list working fine, but my problem comes with the next step of generating the rest of the details. With my below code it just shows the details of the last user who signed up and does not change when I change the name in the drop down menu.
I'm pretty sure I need Javascript to help get this working but as I am a beginner to PHP/MYSQL any advise toward the right direction for me would be great. Thanks
This is the code which searches my database and puts the first and last name in to a drop down list
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
echo '<select name="name" style="width: 400px">';
while ($row = mysqli_fetch_assoc($query)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo'<option>' . $firstname . " " . $lastname . '</option>';
}
echo '</select> <p>';
Again the above code works fine, but the below code is what I am having difficulty with
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
echo "ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "<p>";
}
if you don't want to use AJAX to dynamically load the content, you need a form to submit the data, your problem is that after your first loop, $firstname is the last user loaded into the , to make your code work, you need a form.
just put the select in a form and add a button
<form action="mypage.php" method="get">
<select name="name" style="width: 400px">
<?php
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
while ($row = mysqli_fetch_assoc($query)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo'<option>' . $firstname . " " . $lastname . '</option>';
}
?>
</select>
<input type="submit" value="Load User Data">
</form>
then in mypage.php you need to check if the form is submitted, and show the user details.
<?php
if(isset($_GET["name"])) {
//this form is posted, show user details
//$firstname = $_GET["name"]; <--- SQL Injection enabled here!!
$firstname = mysqli_real_escape_string($_GET["name"]); // please try to avoid SQL injection!
//your code continues here
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
echo "ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "<p>";
}
}
last note, if you don't want the username to appear in the querystring, change form action to post, and get variable using $_POST["name"]
EDIT: if you want the form to autopost using javascript then add this to ur select definition:
<select name="name" style="width: 400px" onchange="this.form.submit()">
but bear in mind that a lot of users block javascript, thus this will not work.
The best way would be to use AJAX to get the data of the other script. However, another (far less elegant and efficient) way of doing it is while you're looping through the names to put into the select. You can also be using the names to get the info for that name and put it into an array (but don't echo it) until you need it.
Use this code from where user will select the name
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js">
<script type="text/javascript">
$(document).ready(function()
{
$(".listdata").change(function()
{
var dataString = 'listdata='+ $(this).val();
$.ajax
({
type: "POST",
url: "alldata",
data: dataString,
cache: false,
success: function(html)
{
$(".alldata").html(html);
}
});
});
});
</script>
<?php
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
echo '<select name="name" style="width: 400px" class="listdata">';
while ($row = mysqli_fetch_assoc($query)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo'<option value="'.$firstname.'">' . $firstname . " " . $lastname . '</option>';
}
echo '</select> <p>';
?>
<div class="alldata">
<!--here your all data will come-->
</div>
<br/><br/>
Crate one more and give the name alldata.php
And use the below code on that page
<?php
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
echo "ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "<p>";
}
?>
Just to complete your options, here you have a full but basic AJAX implementation (using jQuery):
File select.php (javascript part at the bottom of the file):
<?php
// Notice that you'll need to get the $dbc from somewhere, maybe require 'db.php'?
// Retrieve list of people... (notice I've added id column!)
$sql = "SELECT id, first_name, last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
$people = [];
while ($row = mysqli_fetch_assoc($query)){
$people[$row['id']] = $row['first_name'] . " " . $row['last_name'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>List of people</title>
<style type="text/css">
.error {
color: red;
box-shadow: 0px 0px 15px 0px rgba(247, 17, 40, 0.44);
}
#person-info {
padding: 10px;
margin-top: 1em;
}
</style>
</head>
<body>
<h2>People list</h2>
<label for="person">Please select one person</label>
<select name="person" id="people-selection">
<option value="-1"></option>
<?php foreach ($people as $person_id => $person_name): ?>
<option value="<?php echo $person_id ?>"><?php echo $person_name ?></option>
<?php endforeach; ?>
</select>
<div id="person-info"><!-- here we will put person info using AJAX request --></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("#people-selection").on('change', function(e) {
if ($(this).val() != -1) { // If we did select some value
$.ajax({
type: "POST",
url : "/get_people_info.php",
data: { id: $(this).val() },
})
.done(function(data) {
$("#person-info")
.removeClass("error") // we don't need the error class here, it's a success response
.html(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
$("#person-info")
.addClass("error") // in order to add some UI for the user
.html("Something went wrong!<br><blockquote>" + errorThrown + "</blockquote>");
});
}
else {
$("#person-info")
.removeClass("error")
.html("");
}
})
});
</script>
</body>
</html>
And then get_people_info.php
<?php
if ($_SERVER['REQUEST_METHOD'] !== "POST") {
header('HTTP/1.0 400 Bad request');
die("Only POST request accedpted!");
}
if (!isset($_POST['id'])) {
header('HTTP/1.0 400 Bad request');
die("id parameter is mandatory!");
}
$id = (int) $_POST['id'];
// Notice that you'll need to get the $dbc from somewhere, maybe require 'db.php'?
$sql = "SELECT * FROM registration_tbl WHERE id = ". $id .";";
$query = mysqli_query($dbc, $sql);
if ($row = mysqli_fetch_array($query)){
echo "<p>ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "</p>";
}
else {
echo "Person not found!";
}
Let me give you some further reading (you said you were new to PHP, I asume the whole web development):
jQuery Learning center
PHP: The right way

Categories