Check mysql DB on input using JS - javascript

&I have a qty field for goods receiving. I want to check the receipts table against the orders table and make sure that value being entered does not exceed the total order value. I have this code in my field:
<div class="pure-control-group">
<label for="rec_qty">Qty Received:</label>
<input type="text" name="rec_qty" id="rec_qty" onChange="receiptTotal()"></input>
</div>
Javascript Code:
function receiptTotal(){
$.ajax({
type: "GET",
url: "receipts.php?do=checkrec&id="+row.pur_ID,
//dataType: 'json',
success : function(data) {
// Here I want to do the comparisons of the two fields.
// If data.rec_qty + form.rec_qty > pur_qty then throw error.
}
});
}
Finally PHP Code:
if($_GET['do'] == "checkrec") {
$rec = [];
//First get the receipts total for this ID
$getRows = $db->query(sprintf("SELECT sum(rec_qty) as total_qty, pr.pur_qty from receipts inner join purchases pr on rec_purID = pr.pur_ID WHERE rec_purID = '$groupid' GROUP BY pur_ID")) or SQLError();
while($rec = $getRows->fetch_assoc()) {
$result[] = $rec;
}
echo json_encode($result);
}
I am a complete novice just incase anyone was wondering. I would really appreciate the help!

At first I thought you were asking how to do it in your database, but now I see you are already getting the data from your server and returning it. So I'll answer now, hopefully its what you meant.
function receiptTotal(){
$.ajax({
type: "GET",
url: "receipts.php?do=checkrec&id="+row.pur_ID,
//dataType: 'json',
success : function(data) {
var rec_qty = $('#rec_qty').val();
if((data.rec_qty+rec_qty) > data.pur_qty){
alert('Value is too high!!'); // or whatever error you want
}
}
});
}
I will say this though.....you are basically firing a server request along with a database request, every time the field changes. Which is extremely inefficient. You should just load the data once, and then refer to it locally for the check. But I'll let you figure that out on your own :)

Related

Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.
The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.
Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.
What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)
What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
url: "save.php",
method: "POST",
data: { name: name.value, email: email.value, telephone: telephone.value },
success: $("List").load(" List")
});
}
Thank you in advanced and if I need include further info don't hesitate to ask.
From this comment
as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam
I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)
I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.
Thanks!
(Won't let me mark as answered until 2 days)
I would first create an AJAX call inside a function which runs when the page loads to populate the list.
window.onload = populatelist();
function populatelist() {
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'populate'},
success: function(data) { $("#list").html("data"); }
});
}
Note: #list refers to <div id="list> and your list should be inside this.
I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
success: function() { populatelist(); }
});
}
list.php should look like this:
<?php
if($_POST['function'] == "populate") {
// your code to get the content from the database and put it in a list
}
if($_POST['function'] == "update") {
// your code to update the database
}
?>
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:
PHP:
function doLoadMails(){
//initialize empty variable
$mails;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("");
}
//some select, insert, whatever
$sql = "SELECT ... ... ... ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row, j is counter for rows
$j =0;
while($row_a = $result->fetch_assoc()) {
//for each row, fill array
$mails[$j][0] = $row_a["name"] ;
$mails[$j][1] = $row_a["mail"] ;
$mails[$j][2] = $row_a["language"] ;
$j++;
}
}
//if $mails has results (we added something into it)
if(isset($mails)){
echo json_encode($mails);/return json*/ }
else{
//some error message you can handle in JS
echo"[null]";}
}
and then in JS
function doLoadMails() {
$.ajax({
data: { /*pass parameters*/ },
type: "post",
url: "dataFunnel.php",
success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
console.log(data); //you can check what you get
if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
}
});
Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.
In your solution, you will probably need to echo the return code of the INSERT request.

How can I pass the multiple Id to PHP with the help of AJAX and display the images which are select by the user?

I have more than 100 users in my database and all are displaying with a check box.
When user click on check box then Id value will pass to PHP with the help of AJAX and it will display the image of the user.
Above statement is working perfectly because I am passing the single id to PHP.
Now the issue is How can I pass the multiple Id to PHP with the help of AJAX and display the images which are select by the user?
If I checked the single Id then it will display the single image, if I select 2 check box then it will display the two images and up to Three.
I think I have to use SESSION and ARRAY.
Would you help me in this?
<input type="checkbox" value="<?php echo $id;?>" name="display_id" id="display_id" />
AJAX
$(document).ready(function() {
$("[type=checkbox]").click(function() {
var user_id = $(this).val();
$.ajax({
type: "POST",
url: "process", //
data: 'id=' + user_id,
success: function(msg) {
$("#display_id").html("<img src='images/profile/" + msg + "' alt='' />");
},
error: function() {
alert("failure");
}
});
});
});
process
$_SESSION['id_user']=$_POST['id'];
$sql_compare="SELECT * FROM register WHERE Id=".$_SESSION['id_user'];
$compare_query=$conn->query($sql_compare);
if ($compare_query->num_rows > 0) {
while($userdata12=$compare_query->fetch_assoc()){
$compare_pic=$userdata12['profile_pic'];
}
}
echo $compare_pic;
exit();
First you should do this,
arr = [];
$("[type='checkbox']:checked").each(function(){
arr.push($(this).val());
});
Then you should do this,
var params = {
users : arr
};
Then your ajax will be,
$.ajax({
type: "POST",
url: "process", //
data:params,
.
.
.
.
Now check whether all checked user ids are getting on server side. if yes,
Then fetch all data and return it as response back to ajax.
EDIT 1
$sql_compare="SELECT * FROM register WHERE Id IN (".implode(',',$_SESSION['id_user']).")";

How can I refresh a PHP file with itself using Ajax?

Alright guys I'm trying to make a filter system for posts using ajax and a select box. I am able to get the value from the select box no problem. But my issue is that when I try to include the selected value in my PHP file it doesn't do anything. I have a file called public_wall.php. This file contains PHP, Javascript, and HTML. How can I refresh this div whenever a user selects a different filter option? Basically I need the selected value to be passed onto my public_wall.php file and then I want to plug it into the PHP function that fetches the posts thats's in the same file and then I want to refresh that same file to display the filtered results. Here is my Javascript code.
$("#postRatings").on("click", function(e) {
selectedRatingFilter = $("#postRatings option:selected").val();
var dataString = "timeFilter="+selectedRatingFilter;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response){
hideSpinner();
jQuery('#postsPagingDiv').remove();
jQuery('#wsc_midbox').html(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
jQuery('#paging_in_process').val(0);
}
});
});
When the dataType is set to "json" nothing happens. But when it is set to html it prints some javascript code. Please help. The PHP file is too large to include here, but it basically contains PHP, HTML, and Javascript and some PHP functions that do sql queries. What is the best way to achieve a filter mechanism for my setup?
And on the public_wall.php file I want to get the value like so:
$ratingFilter = isset($_REQUEST['timeFilter']) ? intval($_REQUEST['timeFilter']) : 0;
And then plug it into the PHP function that fetches the posts which is in the public_wall.php file also so that I can filter the posts based on the selected value. And then finally I want to refresh the public_wall.php file with the new results. I hope that makes sense. Please help.
This is the output when I set my dataType to "html"
<script>
function refreshPosts() {/* only posts comments likes and count updated. */
var posts = jQuery("#all_post_id").val();
var arrays = posts.split(',');
var dataString = "postids="+posts;
jQuery.ajax({
type: "POST",
url: site_url+"includes/update_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
var x = response;
//############ skip posts whose comments are being read by users
var ExemptedPostsIDs = jQuery("#exemptedPostsID").val();
var ExemptedArray = ExemptedPostsIDs.split(',');
ExemptedArray = ExemptedArray.sort();
//////////////
for (i=0; i<arrays.length; i++) {
var val = 'row'+arrays[i];
if(x[val]) {
if(!inArray(arrays[i], ExemptedArray))
jQuery("#ajax_wall_"+arrays[i]).html(x[val]);
} else {
jQuery('#PostBoxID'+arrays[i]).parent().fadeOut(500);
}
}
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function refreshWall() {/* loads new posts real time */
var posts = jQuery("#all_post_id").val();
var pageUsing = jQuery('#pageUsing').val();
var dataString = "update_posts=1&postids="+posts+'&pagex='+pageUsing;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
if(response.all_post_id) {
jQuery('#wsc_midbox').prepend(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
}
}
});
}
</script>
I suggest you keep the form with select element and any JavaScript on the outer frame.
Via ajax, only load the results to a seperate DIVision below that.
When you put an Ajax response to a div, any JavaScript inside it will not be executed.
For the best throughput with Ajax, you should consider loading a json response via Ajax and create HTML elements on the client side. That way it becomes much easier to pull additional variables to front-end JS from server side along with the same request/response.
But that becomes bit difficult when you have a template engine in the back-end. You can still send the HTML content in a json value, so you can easily pass the "all_post_id" as well..

Using ajax request variable to populate a dropdown

My limits in javascript are preventing me to solve a problem I am facing at present.
I am doing an ajax request for retrieving some database values.
I receive the data I need alright, but
I am unable to use that value "cityareax" to either populate an existing dropdown or to create a new one.
Here is the code:
<script type="text/javascript">
function autocomp_city() {
var min_length = 2; // min caracters to display the autocomplete
var keyword = $("#city_namex").val();
if (keyword.length >= min_length) {
$.ajax({
url: "city_ajax_refresh.php",
type: "POST",
data: {keyword:keyword},
success:function(data){
$("#city_list").show();
$("#city_list").html(data);
}
});
} else {
$("#city_list").hide();
}
}
// set_item : this function will be executed when we select an item - a city name
function set_item(cityname, statename, cityarea) {
$("#city_namex").val(cityname);
$("#statex").val(statename);
// hide proposition list
$("#city_list").hide();
$("#cityareax").val(cityarea);
}
</script>
Can somebody help me?
tx Roberto
and thanks for your interest. I found my own solution. The main problem was timing.
I was trying to use data that I received from Ajax in a script that was inactive, having been executed onload.
When I moved my variable processing code in the function that was working AFTER THE AJAX REQUEST, everything went fine. It was about a week that I was running in circles trying to find a solution ...
Roberto
Are you missing a return type?
$.ajax({
url: "city_ajax_refresh.php",
type: "POST",
data: {keyword:keyword},
datatype: "html",
success:function(data){
$("#city_list").show();
$("#city_list").html(data);
}
});
What's the php output?
Need to use echo in PHP instead of return.
<?php
$output = some_function();
echo $output;
?>

Update mysql data on textarea click off

I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/

Categories

Resources