Jump to content

Cleaning PHP variables before implementing them in a Javascript code


bambinou1980

Recommended Posts

Hello,

 

I am a bit lost on this one, still new PHP....

 

I am trying to follow this tutorial here using the PHP/mysqli method:

https://css-tricks.com/dynamic-dropdowns/

 

 

I am having a real problem, everything is connected and seems to be passing data to the "get" request as I see it in the console but my database data has spaces and it looks like the GET method only takes the first word.

 

ie:

 

This

<script>  $("#products").change(function() {  $("#product_prices").load("getter.php?choice=" + $("#products").val());});</script>  

 

 

Results in this in the console:

Uncaught Error: Syntax error, unrecognized expression: Bases 30cm (320gr)ga.error @ jquery.min.js:2ga.tokenize @ jquery.min.js:2ga @ jquery.min.js:2n.fn.extend.find @ jquery.min.js:2(anonymous function) @ jquery.min.js:4n.Callbacks.j @ jquery.min.js:2n.Callbacks.k.fireWith @ jquery.min.js:2x @ jquery.min.js:4n.ajaxTransport.k.cors.a.crossDomain.send.b @ jquery.min.js:4jquery.min.js:4 XHR finished loading: GET "http://site.com/admin/crud/orders/getter.php?choice=Pizza".

 
 
But the data that should be pulled from the database is: 
Pizza Bases 30cm (230gr)  
 
 
(with bracket and spaces)
 
But the GET is only taking the first word "pizza"
 
Any idea why please?
 
Here is the full code:
 
Index.php
 
<?php 
ob_start();
session_start();
$admin_permission = $_SESSION['admin_permission'];
if(($admin_permission) == 1){
//Session admin ID equal 1
}else{
header('Location: http://' . $_SERVER['HTTP_HOST'] . '/index.php');
exit();
}
?>
<?php include($_SERVER["DOCUMENT_ROOT"] . "/admin/includes/admin-header.php"); ?>




<!--Content-->

<div class="container-fluid">
	<div class="row">
		<div class="col-md-12">
			<div class="row">
				<div class="col-md-3">
				</div>
				<div class="col-md-6">
					<h3>
						Create an Order
					</h3>
					
					
					<?php


			// detect form submission
			if (isset($_POST['submit'])) {
				// set default values using ternary operator
				//   boolean_test ? value_if_true : value_if_false
				//It means if $_POST['username'] isset "set it to" $_POST['username'] "or set it to" to "empty"
				$name = isset($_POST['name']) ? $_POST['name'] : "";
				$surname = isset($_POST['surname']) ? $_POST['surname'] : "";
				$company = isset($_POST['company']) ? $_POST['company'] : "";
			    $address = isset($_POST['address']) ? $_POST['address'] : "";
				$phone = isset($_POST['phone']) ? $_POST['phone'] : "";
				$email = isset($_POST['email']) ? $_POST['email'] : "";
				$vat = isset($_POST['vat']) ? $_POST['vat'] : "";
				
				
					// Escape all strings
	            $name = mysqli_real_escape_string($connection, $name);
				$surname = mysqli_real_escape_string($connection, $surname);
				$company = mysqli_real_escape_string($connection, $company);
				$address = mysqli_real_escape_string($connection, $address);
				$phone = mysqli_real_escape_string($connection, $phone);
				$email = mysqli_real_escape_string($connection, $email);
				$vat = mysqli_real_escape_string($connection, $vat);
	            // 2. Perform database query
	            $query  = "INSERT INTO customers (cust_name,cust_surname,cust_company,cust_address,cust_phone,cust_email,cust_vat) 
				VALUES ('{$name}','{$surname}','{$company}','{$address}','{$phone}','{$email}','{$vat}')";
	            $result = mysqli_query($connection, $query);
				
				

			    if ($result) {
				// Success
                 header("Location: list-customers.php"); 
			    } else {
				// Failure
				// $message = "Subject creation failed";
				die("Database query failed. " . mysqli_error($connection));
				header("Location: index.php"); 
			    } 
				
			} else {
				$name = "";
				$surname = "";
				$company = "";
				$address = "";
				$phone = "";
				$email = "";
				$vat = "";
			}
?>
			
<?php  
$random_number = rand(999 ,99999999999 );
/* $str will now be a string with the value "Glue This Into A String Please" */

?>				
					   <form role="form" method="post" action="index.php">
					   
					   
					   	<div class="form-group">
							<label for="order_id">
								Order ID
							</label>
							<input type="text" name="cust_order_id" class="form-control" value="<?php echo "FP" .$random_number; ?>" readonly="readonly" />
						</div>
					   
					   
					
						<div class="form-group">
							<label for="name_id">
								Company *
							</label>	
						<select name="cust_company" class="form-control" id="cust_company_id">
                        <?php 
						$query_field1 = "SELECT * FROM customers ORDER BY cust_company desc";
                        $result_field1 = mysqli_query($connection, $query_field1) or die (mysqli_error());
                        while($row_field1 = mysqli_fetch_array($result_field1)){
						$cust_name = htmlspecialchars($row_field1['cust_name']);
						$cust_surname =  htmlspecialchars($row_field1['cust_surname']);
						$cust_company =  htmlspecialchars($row_field1['cust_company']);
                        $cust_address = htmlspecialchars($row_field1['cust_address']);
                        $cust_phone =  htmlspecialchars($row_field1['cust_phone']);
                        $cust_email =  htmlspecialchars($row_field1['cust_email']);
                        $cust_vat =  htmlspecialchars($row_field1['cust_vat']);
						?>
					    <option value="<?php echo $cust_company; ?>" data-name="<?php echo $cust_name; ?>" data-surname="<?php echo $cust_surname; ?>" data-address="<?php echo $cust_address; ?>" data-phone="<?php echo $cust_phone; ?>" data-email="<?php echo $cust_email; ?>" data-vat="<?php echo $cust_vat; ?>"><?php echo $cust_company; ?></option>
                        <?php } ?>
					    </select>
                    	</div>
						
						<div class="form-group">
							<label for="address_id">
								Address *
							</label>
							<textarea name="cust_address" placeholder="Company's Address" rows="4" cols="50" class="form-control" readonly="readonly" ></textarea>
						</div>
						
						 <div class="form-group">
							<label for="name_id">
								Name *
							</label>
							<input type="text" name="cust_name" placeholder="Customer Name" class="form-control" value="" readonly="readonly" />
						</div>
                        
                        <div class="form-group">
							<label for="surname_id">
								Surname *
							</label>
							<input type="text" name="cust_surname" placeholder="Customer Surname" class="form-control" value=""  readonly="readonly" />
						</div>
						
						<div class="form-group">
							<label for="phone_id">
								Phone
							</label>
							<input type="text" name="cust_phone" placeholder="Customer Phone" class="form-control" value=""  readonly="readonly" />
						</div>
						
						<div class="form-group">
							<label for="email_id">
								Email
							</label>
							<input type="email" name="cust_email" placeholder="Customer Email" class="form-control" value=""  readonly="readonly" />
						</div>
						
						<div class="form-group">
							<label for="vat_id">
								V.A.T Number(ie:MT20343324)
							</label>
							<input type="text" name="cust_vat" placeholder="V.A.T Number"  class="form-control" value="" readonly="readonly" />
						</div>
                        
 
                        <div class="form-group">
							<label for="due_date_id">
							Due Date *
							</label>
							<div class="form-inline well">
                           	<div class="input-append date" id="dp3" data-date="12-02-2012" data-date-format="dd-mm-yyyy">
                              <input name="due_date" class="form-control" size="25" type="text" id="dp1" value="12-02-2012">
                               	<span class="add-on"><i class="icon-th"></i></span>
								</div>
                            </div>
                        </div>
						

						<script>
						$('#dp1').datepicker({
			          	format: 'dd-mm-yyyy'
			            });
						</script>

					
						<?php 
						//Query all the prices 
						$query_field2 = "SELECT * FROM products ORDER BY name desc";
                        $result_field2 = mysqli_query($connection, $query_field2) or die (mysqli_error());
						$number1 = 0;
                        $number2 = 0;
						$quantity = 0;
						
                        while($row_field2 = mysqli_fetch_array($result_field2)){
						$name = htmlspecialchars($row_field2['name']);
						$price1 = htmlspecialchars($row_field2['price1']);
						$price2 = htmlspecialchars($row_field2['price2']);
						$price3 = htmlspecialchars($row_field2['price3']);
						
						?>
						<div class="form-inline well">
						<label for="product1_id">Choose Product <?php echo ++$number1; ?></label>
						<div class="form-group">

						<!--Product name Select-->
						<select name="<?php echo "action".++$number2; ?>" class="form-control" id="products">
						<?php 
						$query_field3 = "SELECT * FROM products ORDER BY name desc";
                        $result_field3 = mysqli_query($connection, $query_field3) or die (mysqli_error());
                        while($row_field3 = mysqli_fetch_array($result_field3)){
						$product_name = htmlspecialchars($row_field3['name']);
						$product_price1 =  htmlspecialchars($row_field3['price1']);
						$product_price2 =  htmlspecialchars($row_field3['price2']);
                        $product_price3 = htmlspecialchars($row_field3['price3']);
						?>
						<option value="<?php echo $product_name; ?>" data-product_price1="<?php echo $product_price1; ?>" data-product_price2="<?php echo $product_price2; ?>" data-product_price3="<?php echo $product_price3; ?>"><?php echo $product_name; ?></option>
                        <?php } ?>
					    </select>

						<!--Price Select-->
                        <select name="<?php echo "action".++$number2; ?>" class="form-control" id="product_prices">

						<option>Select the price</option>
						
					
						</select>

						<label for="product1_id">Qty</label>
						<input name="<?php echo "quantity".++$quantity; ?>" type="text" class="form-control" maxlength="4" size="4" id="<?php echo "quantity".$quantity; ?>">
						  </div>
						  </div>
						  						  <?php } ?>
                        <div class="form-inline well text-center">
						<button type="submit" name="submit" class="btn btn-success btn-lg">
							Create Order
						</button>
						</div>
						</div> 
					</form>
                    
				</div>

			</div>
		</div>
	</div>
</div>

<script>  
$("#products").change(function() {
  $("#product_prices").load("getter.php?choice=" + $("#products").val());
});
</script>  
<script>   
   $('#cust_company_id').change(function() {
    selectedOption = $('option:selected', this);
    $('textarea[name=cust_address]').val( selectedOption.data('address') );
	$('input[name=cust_name]').val( selectedOption.data('name') );
	$('input[name=cust_surname]').val( selectedOption.data('surname') );
    $('input[name=cust_phone]').val( selectedOption.data('phone') );
    $('input[name=cust_email]').val( selectedOption.data('email') );
    $('input[name=cust_vat]').val( selectedOption.data('vat') );
}); 
</script>   
     

                    
         
        
<!--Content-->
<?php
  // 5. Close database connection
 if(isset($connection)){ mysqli_close($connection);}
 ob_flush();
?>
<?php include($_SERVER["DOCUMENT_ROOT"] . "/admin/includes/admin-footer.php"); ?>

And here is the Getter.php

<?php

    $choice = mysqli_real_escape_string($connection, $_GET['choice']);
	$query = "SELECT price1 FROM products WHERE name='$choice'";
	$result = mysqli_query($connection, $query);
		
	while ($row = mysqli_fetch_array($result)) {
   		echo "<option>" . $row['price1'] . "</option>";
	}
	
	
	
	
?>

I am also just found out that only the first dropdown menu is initiating the getter.php search and not the others....still trying to figure out why.

 

 

 

Link to comment
Share on other sites

One thing is your Ternary operator.

//change this
$name = isset($_POST['name']) ? $_POST['name'] : "";

//to this
$name = (isset($_POST['name'])) ? $_POST['name'] : "";

I wasn't able to see where you were passing PHP var to Javascript, however you can try this, it would be cleaner then trying to assign JQuery selector value.

var name = <?php echo htmlspecialchars(json_encode($name), ENT_NOQUOTES); ?>;
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.