Empty post error - php

I need to make my script detect, if post is empty so that it will post error.
Right now, when my post is empty, it posts all the results.
my code
$query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
$query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);
$arr = array();
$query->execute();
while( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
$arr[] = array( "id" => $row["id"], "title" => $row["title"]);
}
echo json_encode( $arr );
?>
and my script
$(document).ready(function(){
$(".search").click(function(){
$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#search").empty()
$.each(data, function(){
$("div#search").append("- <a href='#?id=" + this.id + "'>" + this.title + "</a><br>");
});
}, "json");
});
});

Add this:
if(empty( $keywords ) ) {
// Show some error
}
else{
// your search code here ...
}
but it's preferred to do the check in the JS too before posting

Related

Database insertion within a foreach loop while still calling in different functions in the sequence

I have a bit of a bug, and I can't tell where the error comes from.
I am building a cart system that will insert multiple data to a database from a cart on submit.
I'm using AJAX for this and I'm have errors, please I need help.
Here are my code snippets:
JavaScript Code
function addSale(payment_type, cash_tendered) {
var cust_name = $("#cust_name").val();
var amt_owed = $("#amt_owed").val();
$.confirm({
title: 'Checkout',
content: '' +
'<form action="" class="formName" role="form">' +
'<div class="form-group">' +
'<label>Payment Type</label>' +
'<select id="eType" class="name form-control">' +
'<option value="cash">Cash</option>' +
'<option value="card">Card</option>' +
'</select>' +
'</div>' +
'<div class="form-group">' +
'<label>Cash Tendered</label>' +
'<input type="number" id="eCash" placeholder="Cash Tendered" class="name form-control">' +
'</div>' +
'</form>',
buttons: {
cancel: function () {
//close
},
formSubmit: {
text: 'Checkout',
btnClass: 'btn-success',
action: function () {
payment_type = this.$content.find('#eType').val();
cash_tendered = this.$content.find('#eCash').val();
if (!payment_type || !cash_tendered) {
$.alert('Please fill all fields.');
return false;
}
$.confirm({
title: 'Do you want to continue?',
type: 'orange',
content: 'Click Ok to add sale',
buttons: {
cancel: function () {
},
proceed: {
text: 'Ok',
btnClass: 'btn btn-success',
action: function () {
var addUrl = "home/addsales";
addUrl += "/" + payment_type;
addUrl += "/" + cash_tendered;
addUrl += "/" + cust_name;
addUrl += "/" + amt_owed;
//
$.ajax({type: 'GET', url: addUrl, data: {},
success: function (result) {
$.alert({
content: result
});
$("#eType").val("");
$("#eCash").val("");
$("#cust_name").val("");
$("#amt_owed").val("");
location.reload();
},
error: function (xhr, status, error) {
$.alert({
content: 'Could not complete the process. ' + error
});
}
});
}
}
}
});
}
}
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$formSubmit.trigger('click'); // reference the button and click it
});
}
});
}
Here is the Home Controller Code:
private function addsales($payment_type = null, $cash_tendered = null, $cust_name = null, $amt_owed = null) {
if (isset($payment_type, $cash_tendered)) {
$email = $_SESSION[DbStrings::$EMAIL];
$payment_type = $this->test_input($payment_type);
$cash_tendered = $this->test_input($cash_tendered);
$insertedSale = $this->member->insertDailySale($email, $payment_type, $cash_tendered);
$cust_name = $this->test_input($cust_name);
$amt_owed = $this->test_input($amt_owed);
$insertedCredit = 1;
if (isset($cust_name, $amt_owed) && $amt_owed > 0) {
$insertedCredit = $this->member->insertCredit($email, $cust_name, $amt_owed);
}
if ($insertedSale && $insertedCredit) {
$_SESSION['temp_invoice'] = $_SESSION[DbStrings::$INVOICE];
$chars = "003232303232023232023456789";
srand((double) microtime() * 1000000);
$i = 0;
$pass = '';
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
$alpha = 'NM-' . $pass;
$_SESSION[DbStrings::$INVOICE] = $alpha;
echo "Your sale has been inserted succesfully";
} else {
echo "There was a problem inserting your sale. Please try again.";
}
} else {
echo 'Please fill all fields';
}
}
And Here is my Model Code that still fetches other functions:
public function insertDailySale($email, $payment_type, $cash_tendered) {
$invoice = $_SESSION[DbStrings::$INVOICE];
$this->db->from(DbStrings::$SALES_ORDER_TABLE_NAME);
$condition = array(DbStrings::$EMAIL => $email, DbStrings::$INVOICE => $invoice);
$this->db->where($condition);
$query = $this->db->get();
$checks = $query->result_array();
foreach ($checks as $queries) {
$productID = $queries[DbStrings::$PRODUCTID];
$quantity = $queries[DbStrings::$SALES_QUANTITY];
$amount = $queries[DbStrings::$SALES_AMOUNT];
$profit = $queries[DbStrings::$SALES_PROFIT];
$product_code = $queries[DbStrings::$PRODUCT_CODE];
$product_name = $queries[DbStrings::$PRODUCT_NAME];
$product_selling = $queries[DbStrings::$PRODUCT_SELLING];
$this->deductInventory($email, $product_code, $quantity);
$this->updateQuantitySold($email, $product_code, $quantity);
$cost_price = $this->product->getCostPrice($product_code);
$data[] = array(
DbStrings::$EMAIL => $email,
DbStrings::$INVOICE => $invoice,
DbStrings::$PRODUCTID => $productID,
DbStrings::$SALES_QUANTITY => $quantity,
DbStrings::$SALES_AMOUNT => $amount,
DbStrings::$SALES_PROFIT => $profit,
DbStrings::$PRODUCT_CODE => $product_code,
DbStrings::$PRODUCT_NAME => $product_name,
DbStrings::$PRODUCT_CP => $cost_price,
DbStrings::$PRODUCT_SP => $product_selling,
DbStrings::$PAYMENT_TYPE => $payment_type,
DbStrings::$CASH_TENDERED => $cash_tendered,
DbStrings::$DATE_CREATED => time()
);
$inserted = $this->db->insert_batch(DbStrings::$DAILYSALES_TABLE_NAME, $data);
}
return $inserted;
}
With the above, i get flagged this error:
There was a problem inserting your sale. Please try again.
Please I need help on this.
The error came from my database structure. Being an internal server error, it came from the DB.
I realized i deleted a column from my database table, and i was still sending data to the removed column.
Thanks guys for the attempt to help.

Get data value from php array with autocomplete jquery/ajax

I try to use the plugin from "devbridge autocomplete" : https://www.devbridge.com/sourcery/components/jquery-autocomplete/
I would like to get 3 values from my search.php page (and not just 1).
It works for "value" but not for "data1" and "data2" (result for each = null)
My jQuery code :
$('#search-adress').autocomplete({
serviceUrl: 'search.php',
dataType: 'json',
onSelect: function (value,data1,data2) {
alert('You selected: ' + value + ', ' + data1 + ', ' + data2);
}
});
My search page :
$term=$_GET['query'];
$query = mysql_query("select distinct adress,id,city from myadresstable where (adress like '%{$term}%') order by adress limit 10 ");
if (mysql_num_rows($query))
{
while($row = mysql_fetch_assoc($query))
{
$reply['suggestions'][] = ''.utf8_encode($row['nom_voie']).'';
$reply['data1'][] = ''.utf8_encode($row['id']).'';
$reply['data2'][] = ''.utf8_encode($row['city']).'';
}
echo json_encode($reply);
}
Thank you for helping me :)
You can just change a bit the php array this way:
$term=$_GET['query'];
$query = mysql_query("select distinct adress,id,city from myadresstable where (adress like '%{$term}%') order by adress limit 10 ");
if (mysql_num_rows($query))
{
$arr = array();
while($row = mysql_fetch_assoc($query))
{
$reply['suggestions'] = utf8_encode($row['nom_voie']);
$reply['data'] = utf8_encode($row['id']);
$reply['value'] = utf8_encode($row['city']);
$arr[] = $reply;
}
echo json_encode($arr);
}
And in your jquery code:
$(function(){
$('#autocomplete').autocomplete({
lookup: datos,
onSelect: function (suggestion) {
console.log(suggestion);
alert('You selected: ' + suggestion.value + ', ' + suggestion.data + ', ' + suggestion.nom_voie);
}
});
});
Sample fiddle: https://jsfiddle.net/robertrozas/n6oLLfmc/
Try selecting "Valdivia" to see the alert
I found the solution :)
The problem was the PHP Array. To get some data values with this autocomplete plugin you have to use array() :
PHP Code
$suggestions = array();
if (mysql_num_rows($query))
{
while($row = mysql_fetch_assoc($query))
{
$mydata1='$row['data1']';
$mydata2='$row['data2']';
$nom_voie=''.utf8_encode($row['nom_voie']).'';
$suggestions[] = array(
"value" => $nom_mydata1,
"data" => $nom_mydata2
);
}
}
echo json_encode(array('suggestions' => $suggestions));

AJAX/PHP pop up for validation

Anyone can help me. Please. I don't how to have a pop up every validation exist.
I used alert(data.message); but validation says undefined.
here is my PHP code for the function:
<?php
include('connect.php');
$mydata = $_POST["results"];
$inputs = [];
parse_str($mydata, $inputs);
extract($inputs);
$plate_no_full = "$plate_char-$plate_no";
$result1 = mysql_query("SELECT * FROM cars where plate_no ='" . $plate_no_full . "'");
$result2 = mysql_query("SELECT * FROM cars where chass_no ='" . $chassis_no . "'");
$result3 = mysql_query("SELECT * FROM cars where eng_no ='" . $engine_no . "'");
$rows1 =mysql_num_rows($result1);
$rows2 =mysql_num_rows($result2);
$rows3 =mysql_num_rows($result3);
$errors = [];
if (mysql_num_rows($result1) > 0) {
$errors[] = array(
'error_code' => 1,
'message' => 'That plate number was already taken'
);
}
if (mysql_num_rows($result2) > 0) {
$errors[] = array(
'error_code' => 2,
'message' => 'That chassis number was already taken'
);
}
if (mysql_num_rows($result3) > 0) {
$errors[] = array(
'error_code' => 3,
'message' => 'That engine number was already taken'
);
}
if(empty($errors)) {
mysql_query("INSERT INTO cars VALUES ('', '$plate_char-$plate_no', '$engine_no', '$chassis_no', '$car_year', '$car_brand', '$car_model', '$horse_power', '$torque','$transmission $transmission_no', '$drivetrain', '$length/$width/$height', '$seating', '$condition','$air_bag' , '$front_wheel/$rear_wheel' , '$front_susp/$rear_susp' , '$brake_front/$brake_rear' , '$eng_type', '$fuel_type' , '$acquisition_cost' , '$marg_cost', '$selling_price' , '')");
if(isset($_POST["txt1"])){
for($i=0;$i<=count($_POST["txt1"])-1;$i++){
mysql_query("INSERT INTO expenses VALUES ('','$plate_char-$plate_no', '". $_POST["txt1"][$i] ."','". $_POST["txt2"][$i] ."', '". $_POST["txt3"][$i] ."')");
}
}
$response = array(
'message' => 'Successfully Added'
);
echo json_encode($response);
} else {
$response = array(
'errors' => $errors
);
echo json_encode($response);
}
here is my ajax code:
$(document).ready(function() {
$('#submitme').on('submit', function(e) {
e.preventDefault();
var mytxt1 = [];
var mytxt2 = [];
var mytxt3 = [];
$(".expense_name").each(function () {
mytxt1.push($(this).val());
});
$(".expense_desc").each(function () {
mytxt2.push($(this).val());
});
$(".expense_cost").each(function () {
mytxt3.push($(this).val());
});
var perfTimes = $(this).serialize();
$.post("addfunction.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2, txt3: mytxt3 }, function(data) {
if(data.errors) { }
else {
alert(data.message);
window.localtion.href = data.redirect;
}
});
});
});
You need to add the datatype to your post request so jquery can parse the response, then you can handle the errors like you did:
$.post("addfunction.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2, txt3: mytxt3 }, function (data) {
if (data.errors) {
var alertErrors = "The following errors were found: ";
$.each(data.errors, function(index, error){
alertErrors += "\n" + error.message;//Add each error in a new line
});
alert(alertErrors);
}
else {
alert(data.message);
window.localtion.href = data.redirect;
}
}, "json");//<--datatype here
Also the data.redirect value is missing in your response:
$response = array(
'message' => 'Successfully Added',
'redirect' => ''//add here
);
echo json_encode($response);
Fixing the redirect you wrote "localtion" wrong:
window.location.href = data.redirect;
I found that I needed to parse the returned JSON as well. This is because $.post is just a preconfigured $.ajax call, which does not (I think) specify which dataType is being fetched.
Hence, your Client-side code cannot immediately access the response as an object.
The simplest option is just to parse the response using jQuery:
data = $.parseJSON(data);
Otherwise you could change your code to use the $.ajax function:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
Good luck!

Ajax search post error

I need help with two things.
First: if I hit empty submit button. It should show me a error.
Second: If there is 0 results, it will give an error.
$(document).ready(function(){
$(".search").click(function(){
$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#search").empty()
$.each(data, function(){
$("div#search").append("- <a href='#?id=" + this.id + "'>" + this.title + "</a><br>");
});
}, "json");
});
});
--
$query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
$error = 'error';
echo json_encode( $error );
} else {
$query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);
$arr = array();
$query->execute();
while( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
$arr[] = array( "id" => $row["id"], "title" => $row["title"]);
}
echo json_encode( $arr );
}
OK I have painstakingly recreated (jsfiddle does not let you copy/paste) this on my local machine. Your html/js code should look like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="search" class="keywords">
<input type="submit" name="submit" class="search">
<div id="search"></div>
<script>
$(document).ready(function(){
$(".search").click(function(){
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data){
$("div#search").empty()
$("div#search").append(data);
},
"json"
);
});
});
</script>
</body>
</html>
And for the PHP search.php page:
<?php
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
echo json_encode( "error" );
}
else {
// run mysql commands
// if resultset == empty
// echo json_encode( "error" );
echo json_encode( "actual data" );
}
?>
To parse json data in javascript do this:
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data) {
$("div#search").empty();
obj = JSON.parse(data);
$("div#search").append(obj.id + " " + obj.title);
},
"json"
);
try using $(this) instead of this

Passing data back from php to ajax

How can I pass data from a php of then rows back to ajax ?
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[]=$rec['pic_location'];
$name[]=$rec['name'];
$age[]=$rec['age'];
$gender[]=$rec['gender'];
}
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Ajax
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
dataType: "json",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first image url: " + arr[0][0] + ", second image url: " + arr[0][1]); // This code isnt working
alert("first image Name: " + arr[1][0] + ", second image name: " + arr[1][1]);
$(".theImage").attr("src", arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
My question is how can I display the values here ? The Alert message is giving me "Undefined" ?
You can do something along these lines.
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$res = mysql_query($query);
$pictures = array();
while ($row = mysql_fetch_array($res)) {
$picture = array(
"pic_location" => $row['pic_location'],
"name" => $row['name'],
"age" => $row['age'],
"gender" => $row['gender']
);
$pictures[] = $picture;
}
echo json_encode($pictures);
JS
...
$.ajax({
...
dataType: "json",
...
success: function(pictures){
$.each(pictures, function(idx, picture){
// picture.pic_location
// picture.name
// picture.age
// picture.gender
});
}
});
...
You can't put multiple echo statements for the AJAX response:
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Join your arrays and send a single response:
$arr = $url + $name + $age + $gender;
echo json_encode($arr);
You can easily do this using a single Array:
$pics = array();
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pics[$rec['id']]['url'] = $rec['pic_location'];
$pics[$rec['id']]['name']=$rec['name'];
$pics[$rec['id']]['age']=$rec['age'];
$pics[$rec['id']]['gender']=$rec['gender'];
}
echo json_encode($pics);

Categories