AJAX doesn't work? No error messages

Hello,
I am trying to insert form data into the db using AJAX
Form execution gives no error messages, yet no data is inserted into the DB

Here is the code for the form and the AJAX :

<body>
    <!-- menu for account pages-->
	<?php include_once 'account_pages.php';  ?>
		<h1>Insert Your Trades To The DataBase For Deep Analysis</h1>
   <!-- form for inserting trade data -->
	<form id="post_form" method="post" action="process_form_data.php">
		<table>
			<tr>
				<td class="name">Ticket</td>
				<td class="name">Open time</td>
				<td class="name">Type</td>
				<td class="name">Size</td>
				<td class="name">Item</td>
			</tr>
			<tr>
				<td><input id="ticket" type="text" placeholder="Ticket"></td>
				<td><input id="o_time" type="text" placeholder="yyyy.mm.dd hh:mm:ss" name="start_time">
				    </td>
			    
				<td><select id="type" name="type">
				      <option value="Deposit">Deposit</option>
					  <option value="Buy Limit">Buy Limit</option>
					  <option value="Sell Limit">Sell Limit</option>
					  <option value="Buy Stop">Buy Stop</option>
					  <option value="Sell Stop">Sell Stop</option>
					  <option value="Buy">Buy</option>
					  <option value="Sell">Sell</option>
					</select>
				</td>
				<td><input id="size" type="text" placeholder="size"></td>
				<td><input id="item" type="text" placeholder="Item"></td>
			</tr>
			<tr>
			<td colspan="5">.<td>
			</tr>
			<tr>
				<td class="name">Open Price</td>
				<td class="name">Stop Loss</td>
				<td class="name">Take Profit</td>
				<td class="name">Close time</td>
				<td class="name">Close Price</td>
			</tr>
			<tr>
				<td><input id="o_price" type="text" placeholder="Open Price"></td>
				<td><input id="stop_loss" type="text" placeholder="Stop Loss"></td>
				<td><input id="take_profit" type="text" placeholder="Take Profit"></td>
				
				
				<td>
					<input id="c_time" type="text" placeholder="yyyy.mm.dd hh:mm:ss" name="start_date">
				</td>
				<td><input id="c_price" type="text" placeholder="Close Price"></td>
			</tr>
			<tr>
			<td colspan="5">.<td>
			</tr>
			<tr>
				<td class="name">Commission</td>
				<td class="name">Taxes</td>
				<td class="name">Swap</td>
				<td class="name">Profit</td>
				<td rowspan="2">
					<button id="insert_data" type = "submit" value="submit">Click<br>to Insert<br>To DB</button>
				</td>
			</tr>
			<tr>
				<td><input id="comission" type="text" placeholder="Comission"></td>
				<td><input id="taxes" type="text" placeholder="Taxes"></td>
				<td><input id="swap" type="text" placeholder="Swap"></td>
				<td><input id="profit" type="text" placeholder="Profit"></td>
			</tr>
			
		</table>
		
	</form>	
		<button id="button" type = "submit" value="submit">I'm Done! Show Me My Results</button>

	<script>
// Code for inserting form data with AJAX
   document.getElementById('post_form').addEventListener('submit', postData);
  
   function postData(e){
	   //Stop form from performing its submit
        e.preventDefault();
	   // Get all form data
		var ticket = document.getElementById('ticket').value;
		 if (ticket === "")
        {
            alert("Ticket number must be filled.");
            return false;
        }
		var open_time = document.getElementById('o_time').value;
		if (o_time === "")
        {
            alert("Open_time number must be filled.");
            return false;
        }
		var type = document.getElementById('type').value;
		if (type === "")
        {
            alert("type must be filled.");
            return false;
        }
		var size = document.getElementById('size').value;
		if (size === "")
        {
            alert("size must be filled.");
            return false;
        }
		var item = document.getElementById('item').value;
		if (item === "")
        {
            alert("item must be filled.");
            return false;
        }
		var O_price = document.getElementById('o_price').value;
		if (o_price === "")
        {
            alert("Open_price must be filled.");
            return false;
        }
		var stop_loss = document.getElementById('stop_loss').value;
		var take_profit = document.getElementById('take_profit').value;
		var c_price = document.getElementById('c_price').value;
		if (c_price === "")
        {
            alert("Close_price must be filled.");
            return false;
        }
		var c_price = document.getElementById('c_price').value;
		if (c_price === "")
        {
            alert("Close_pric must be filled.");
            return false;
        }
		var comission = document.getElementById('comission').value;
		var taxes = document.getElementById('taxes').value;
		var swap = document.getElementById('swap').value;
		var profit = document.getElementById('profit').value;
		if (profit === "")
        {
            alert("Ticket number must be filled.");
            return false;
        }

		var params ='ticket'+ticket+'&o_time'+o_time+'&type'+type+'&size'+size+'&item'+item+'&o_price'+o_price+
			'&stop_loss'+stop_loss+'&take_profit'+take_profit+'&c_price'+c_price+'&comission'+comission+
			'&taxes'+taxes+'&swap'+swap+'&profit'+profit;
		//var params = {ticket: ticket, open_time: open_time}

		var xhr = new XMLHttpRequest();
		xhr.open('POST', 'process_form_data.php', true);
		xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
		xhr.send(params);
   } //End function postData

  
	 
	
  </script>
	
	

 </body>
</html>

And Here is the code in process_form.php

<?php
session_start();
 require "includes/db_connect.inc.php";
 if(isset($_SESSION['username'])){
$username = $_SESSION['username'];
 }

if(!empty($_POST['ticket'])){
	$ticket = $_POST['ticket'];
}

if(!empty($_POST['o_time'])){
	$o_time = $_POST['o_time'];
}

if(!empty($_POST['type'])){
	$type = $_POST['type'];
}

if(!empty($_POST['size'])){
	$size = $_POST['size'];
}

if(!empty($_POST['item'])){
	$item = $_POST['item'];
}

if(!empty($_POST['op_price'])){
	$o_price = $_POST['open_price'];
}

if(!empty($_POST['stop_loss'])){
	$stop_loss = $_POST['stop_loss'];
}else{
      $stop_loss = 0;
}

if(!empty($_POST['take_profit'])){
	$take_profit = $_POST['take_profit'];
}else{
      $take_profit = 0;
}

if(!empty($_POST['c_time'])){
	$c_time = $_POST['c_time'];
}

if(!empty($_POST['cc_price'])){
	$c_price = $_POST['cc_price'];
}

if(!empty($_POST['comission'])){
	$commission = $_POST['commission'];
}else{
      $commission = 0;
}

if(!empty($_POST['taxes'])){
	$taxes = $_POST['taxes'];
}else{
      $taxes = 0;
}

if(!empty($_POST['swap'])){
	$swap = $_POST['swap'];
}else{
      $swap = 0;
}

if(!empty($_POST['profit'])){
	$profit = $_POST['profit'];
}
		
function  add_row(){
	global $db;
try 
{
	 $sql = "INSERT INTO `data`
			(username, ticket, o_time, type, size, item, o_price, s_l, t_p, c_time, c_price, profit)
			VALUES
			(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";		

	$stmt=$db->prepare($sql);
	$stmt->bindParam(':username', $username, PDO::PARAM_STR);
	$stmt->bindParam(':ticket', $ticket, PDO::PARAM_STR);
	$stmt->bindParam(':o_time', $o_time, PDO::PARAM_STR);
	$stmt->bindParam(':type', $type, PDO::PARAM_STR);
	$stmt->bindParam(':size', $size, PDO::PARAM_STR);
	$stmt->bindParam(':item', $item, PDO::PARAM_STR);
	$stmt->bindParam(':o_price', $o_price, PDO::PARAM_STR);
	$stmt->bindParam(':s_l', $s_l, PDO::PARAM_STR);
	$stmt->bindParam(':t_p', $t_p, PDO::PARAM_STR);
	$stmt->bindParam(':c_time', $c_time, PDO::PARAM_STR);
	$stmt->bindParam(':c_price', $c_price, PDO::PARAM_STR);
	$stmt->bindParam(':profit', $profit, PDO::PARAM_STR);
					 
	$stmt->execute();

} // End try

catch(Exception $e) 
{
	 return false;        
}

 }//End function

$result = add_row();


if($result == false)
{
	$_SESSION['test'] = false;
	echo $_SESSION['test'];
}
else
{
	$_SESSION['test'] = success;
	echo $_SESSION['test'];
}

?>

Here is the header in chrome dev tool
image
image

What do I miss here ?

Hi @erezvol, looks like you missed the = between the names and values… you might also want to encode those values BTW.

That said, you don’t even need to assemble the parameters like that; you can just pass a form data object from your form like so:

var form = document.getElementById('post_form')
var data = new FormData(form)
var xhr = new XMLHttpRequest()

xhr.open(form.method, form.action)
xhr.send(data);

PS:

It seems like you’re just swallowing any exceptions where you are inserting the data in your PHP script. I’d suggest to either not catch or re-raise at least PDO exceptions, so that the client knows something went wrong – failed DB insertions are clearly not 200 OK here. :-)

I will make a few suggestions.
Input elements have a defaultValue property as well as a value property. So I give all required input elements a className for example “mandatory” or “Needed” or whatever.
Then I use let form = document.GetElementById(‘post_form’); to get the form element. Then
elements = form.getElementsByClassName(‘mandatory’) gives a htmlCollection of all the mandatory input elements.
Iterate the elements by:
for(const el of elements) {}
you can check each element’s defaultValue and value, first to detect any missing values,
create a list of missing elements or apply a class, changing the background colour or whatever.
After there are no missing values I create a new formData object and then as I iterate the elements I append( el.id, el.value) to the formData object.
The formData object contents will be in the $_POST array in the php script.
Tomorrow, when I work out how to paste code snippets in here again, I will post the form submission and checking code.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.