Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});
Related
The script makes an ajax call to a PHP file on input change, but the JSON isn't parsing and I don't know why
Here's the Javascript
input.addEventListener("input", (event) => {output.innerHTML = "Cerca " + document.getElementById("tophead-searchbar").value + " su Nevent";
var searchqueryajax = new XMLHttpRequest;
ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
searchqueryajax.addEventListener("load", innerhtmlqueries());
searchqueryajax.open("GET", ajaxquerylink);
searchqueryajax.send();
function innerhtmlqueries() {
queriesarray = JSON.parse(searchqueryajax.responseText);
}
});
The input is document.getElementById("tophead-searchbar") and the output is the Result1, it says the value of the input
Here is the PHP Script:
$query = $_REQUEST["query"];
$queryresults = mysqli_query($name, "SELECT * FROM search_queries WHERE MATCH(ID, QUERY) AGAINST('$query') LIMIT 7");
if ($queryresults->num_rows > 0) {
$autocompleteresults = array();
while($row = mysqli_fetch_array($queryresults)) {
$results["ID"] = $row["ID"];
$results["value"] = $row["QUERY"];
$results["type"] = $row["TIPO"];
array_push($autocompleteresults, $results);
}
}
echo json_encode($autocompleteresults);
There are no PHP errors on the log and i don't see the PHP File on Network Tab of the browser F12 editor
I tried to do some things on Javascript code but i still don't notice the request on Network Tab
Edit: I also have another ajax call like this in the same file and it works
var checkajaxiflogged = new XMLHttpRequest();
checkajaxiflogged.addEventListener("load", checkajaxiflogged_function);
checkajaxiflogged.open("GET", "topbarprofileinformation.php");
checkajaxiflogged.send();
function checkajaxiflogged_function() {
topheadjsonresponse = JSON.parse(checkajaxiflogged.responseText);
document.getElementById("tophead-account-img").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
if (topheadjsonresponse.isloggedin == "yes") {
document.getElementById("tophead-accedi-btn").style.display = "none";
document.getElementById("tophead-account-img").style.display = "block";
document.getElementById("Immagine-Profilo-Menu-Principale").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
document.getElementById("Nome-Profilo-Menu-Principale").innerHTML = topheadjsonresponse.displayname;
document.getElementById("Username-Profilo-Menu-Principale").innerHTML = "#" + topheadjsonresponse.username;
}
}
You can use jquery for simplified get request
input.addEventListener("input", (event) => {
output.innerHTML = "Cerca " + document.getElementById("tophead-
searchbar").value + " su Nevent";
getData(); //Call the get function
});
// Ajax function to get data using jquery
function getData() {
let ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
$.ajax({
url : ajaxquerylink,
type : "GET",
success : function(data)
{
let response = JSON.parse(data);
console.log(response);
}
});
}
I solved by myself, in this row
searchqueryajax.addEventListener("load", innerhtmlqueries);
I removed the () in innerhtmlqueries() and now the call response works
Thanks anyway for the support!
I want to create pagination page using infinite scroll with filters. I'm using codeigniter. Pagination is working fine. When clicking ckeck box its working but on scroll it is duplicating the data. I had struggle for days. I will be so grateful if you can help me. Thank you.
This is my view code
$(document).ready(function() {
load_content();
function load_content(){
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
//brand is the checkbox value
var brand=check_box_values('brand');
$('#results').load("<?php echo base_url() ?>content/load_more",
{'group_no':total_record,'brand':brand}, function() {total_record++;});
}
//For passing checkbox values
function check_box_values(check_box_class){
var values = new Array();
$("."+check_box_class).each(function() {
if($(this).is(':checked')){
values.push($(this).val());
}
});
return values;
}
$(".brand").click(function(){
load_content();
});
$(window).scroll(function() {
if($(window).scrollTop()+$(window).height() >= $('#fooerdivid').offset().top)
{
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
//brand is the checkbox value
var brand=check_box_values('brand');
if(total_record <= total_groups)
{
loading = true;
$('.loader_image').show();
$.post('<?php echo site_url() ?>content/load_more',{'group_no': total_record,'brand':brand},
function(data){
if (data != "") {
$("#results").append(data);
$('.loader_image').hide();
total_record++;
}
});
}
}
});
});
I had the same issue back when I was trying to achieve the same. The problem was window.scroll trigger AJAX request multiple times with same Params and it results in a duplication of the data. To overcome this issue you can use a flag to check if the request is running or not. Try this script.
$(document).ready(function(){
var flag = true; //set initial value true for first request
$(window).scroll(function() {
if($(window).scrollTop()+$(window).height() >= $('#fooerdivid').offset().top)
{
if(flag) //run script if flag is true
{
flag = false; //script is running
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
//brand is the checkbox value
var brand=check_box_values('brand');
if(total_record <= total_groups)
{
loading = true;
$('.loader_image').show();
$.post('<?php echo site_url() ?>content/load_more',{'group_no': total_record,'brand':brand},
function(data){
if (data != "") {
$("#results").append(data);
$('.loader_image').hide();
total_record++;
flag = true; //Script execution completed and next request can be execute
}
});
}
}
}
});
});
});
Hope this will solve your problem.
Update
$(document).ready(function(){
var flag = true; //set initial value true for first request
var is_pending = false; //no request is pending
load_content();
function load_content(){
if(flag) //run script if flag is true
{
flag = false; //script is running
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
//brand is the checkbox value
var brand=check_box_values('brand');
$('#results').load("<?php echo base_url() ?>content/load_more",
{'group_no':total_record,'brand':brand}, function() {
total_record++;
flag = true;
if(is_pending)
{ is_pending = false;load_content(); }
});
}
}
//For passing checkbox values
function check_box_values(check_box_class){
var values = new Array();
$("."+check_box_class).each(function() {
if($(this).is(':checked')){
values.push($(this).val());
}
});
return values;
}
$(".brand").click(function(){
if(flag){
load_content();
}else{
is_pending = true;//request is pending
}
});
$(window).scroll(function() {
if($(window).scrollTop()+$(window).height() >= $('#fooerdivid').offset().top)
{
if(flag) //run script if flag is true
{
flag = false; //script is running
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
//brand is the checkbox value
var brand=check_box_values('brand');
if(total_record <= total_groups)
{
loading = true;
$('.loader_image').show();
$.post('<?php echo site_url() ?>content/load_more',{'group_no': total_record,'brand':brand},
function(data){
if (data != "") {
$("#results").append(data);
$('.loader_image').hide();
total_record++;
flag = true; //Script execution completed and next request can be execute
}
});
}
}
}
});
});
});
Say you send the request to the server. Hay server serv me rows between 1 and 100, then you "append" results into a div. Next you say: hay server send me rows between 1 and 150 and do a "append" to same div again. Then you have the double results
What jou want to do is to empty $('#results').empty() the div before next push and push all 150
Or "append" between 1 and 100 rows and next time you "append" rows between 100 and 150
You just need to add last id on showing data. Here an example
// Here sample data
<div class="timeline-item" id="<?= $row->id; ?>">
<p>Content Data</p>
</div>
// Here sample jquery
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
var last_id = $(".timeline-item:last").attr("id");
var last_date = $(".timeline-item:last").attr("data-date");
var base_url = $(".row").attr("data-base-url");
loadMoreData(last_id, last_date, base_url);
}
});
function loadMoreData(last_id, last_date, base_url){
$.ajax({
url: base_url + 'Kpi/timelineData?last_id=' + last_id + '&last_date='+ last_date,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#timeline-data").append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
console.log('server not responding...');
});
}
}
Hope can solve your problem.
When i inspect the response from my AJAX request to index.php, I get back some data that i want (some json, a return value i need the value of) but also a load of HTML as the index.php class is used to call a view which is responsible for loading up some HTML.
Here is the first two lines of the response:
{"returnVal":"registered"}<!DOCTYPE html>
<html lang="en">
Due to my code being MVC, i cannot just create a separate file to handle the AJAX request, so i need a way for my login.js class (where the AJAX request is generated) to go through the whole response and find the value of "returnVal" that I need. Do you know of a way I can do this?
Login.js
var loginData, urlPath;
// Allow users to log in or register
function Login() {
if(!document.getElementById("usernameField")) { // If we have no username field on this page, we are just logging in
loginData = "email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "loggingIn";
urlPath = "index.php";
} else { // we are registering
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "register";
urlPath = "../index.php";
}
// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert(result); // i need to get the value of 'returnVal' from the response
if(result.returnVal=="registered") {
document.getElementById('notification').innerHTML = "You have been registered";
} else if (result.returnVal=="username") {
document.getElementById('notification').innerHTML = "Username already taken";
} else if (result.returnVal=="email") {
document.getElementById('notification').innerHTML = "Email already taken";
} else if (result.returnVal=="notRegistered") {
document.getElementById('notification').innerHTML = "Please enter registered email";
} else if (result.returnVal=="loginFail") {
document.getElementById('notification').innerHTML = "Please enter correct password";
} else if (result.returnVal=="loggedIn") {
$('#myModal').modal('hide');
document.getElementById('loginButton').innerHTML = "Account Settings";
} else { // Something wrong, tell us
//alert(result);
}
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
})
})
}
index.php
<?php
ini_set("log_errors", 1);
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
}
}
$view->Begin();
?>
Ultra simple way is just exit() after you echo the json so the view never gets sent. If this controller is never intended to render a view get rid of $view->Begin();
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
exit();
}
}
This is a (messy but still) way to extract the data you need.
But please consider my first comment. You should do it the other way round.
var result = '{"returnVal":"registered"}<!DOCTYPE html>someother grap';
var n = result.indexOf("<!DOCTYPE");
var jsonString = input.substring(0, n);
var json = JSON.parse(jsonString);
console.log(json);
// your values are here:
// json.returnVal;
This relies on the strict convention, that every return has a '
So i am creating a simple form that checks whether or not the value that the user is inputting exists or not in my DB using jQuery. Everything up until now is working so far however i find myself stuck at this next part.
To easily explain i will just show an example of what i am trying to achieve.
For this example i will be "weeden"
weeden has an ID of 255 in the company table of my database.
If the user types in "weeden" into the client field
To the right of the client field (on the web form), the text "weeden is unavailable" will appear
what i would like to have happen instead is this: "ID 255 is unavailable"
Here is the relevant code.
HTML FORM
<form action="addrecord.php" method="post" autocomplete="off"/>
<div class="form-field">
<label for="client">Client: </label>
<input type="text" name="client" id="client" class="check-exists" data-type="client" placeholder="#">
<span class="check-exists-feedback" data-type="client"></span>
</div>
jQuery Function
$.fn.existsChecker = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function(){
var self = $(this),
selfType = self.data('type'),
selfValue,
feedback = $('.check-exists-feedback[data-type=' + selfType + ']');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()){
selfValue = self.val();
if(selfValue.length >= 1){
$.ajax({
url: 'check.php',
type: 'get',
dataType: 'json',
data: {
type: selfType,
value: selfValue
},
success: function(data){
if(data.exists !== undefined){
if (data.exists === true){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is available');
}
}
},
error: function(){
}
});
}
}
}, 1000);
}
});
});
};
Check.php
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,
array('client')
)
){
switch($type){
case 'client':
$check = $db->prepare("
SELECT COUNT(*) AS count
FROM company
WHERE name = :value
");
break;
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
Any help/suggestions would be greatly appreciated. I consider myself a beginner, this is my first time working on a web project.
Just to clarify ahead of time, there are many other input fields on the same webform such as: email, date, first, last, etc.
I hope my question was clear enough. Thank you
You have to change your Query to something like this:
$check = $db->prepare("
SELECT id, COUNT(*) AS count
FROM company
WHERE name = :value
");
I assume that your primary key field on the company-table is named id.
And finally store the id in the output-Array
$result = $check->fetchObject();
$output['exists'] = $result->count ? true: false;
$output['id'] = $result->id;
Then you can output the id like so:
if (data.exists === true){
feedback.text('ID ' + data.id + ' is unavailable');
}
You can handle everything in query
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,array('client'))){
switch($type){
case 'client':
$check = $db->prepare("
SELECT (CASE WHEN(COUNT(id)>0) THEN id ELSE FALSE END) AS count
FROM company WHERE name = :value ");
break;
}
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
}
In Ajax success
if(data.exists !== undefined){
if (!data.exists){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is already taken.');
}
}
We are getting a issue wherein while submitting a form via javascript one of the parameters (invoiceCodes) is not sent to the server. Below is the snippet of the javascript code.
The flow is as follows. When user clicks on "Print" button validateTransition() method is called in which we make a ajax call. After response of that ajax we call couponPopup(url, invoiceCodes). In this function we submit newWinForm but sometimes invoiceCodes parameter is sent empty.
Also checkForInvoiceCode is true in this case which require user to input invoice codes
Is there anything wrong in the manner in which we are putting values in the form which may lead to invoiceCodes being not sent sometimes.
function couponPopup(url, invoiceCodes)
{
var selectedOrders = '';
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
});
var frm = document.forms["newWinForm"];
frm.action = url;
frm.selectedShipments.value= selectedOrders;
frm.invoiceCodes.value = invoiceCodes;
console.log("Selected orders are "+selectedOrders);
console.log("Invoice codes with them in order are "+invoiceCodes);
document.getElementById("hiddenInvoiceCodes").value=invoiceCodes;
document.getElementById("hiddenselectedShipments").value=selectedOrders;
frm.submit();
return false;
}
function validateTransition() {
$('#statusChangeSuccess').hide();
$('#statusChangeFail').hide();
var selectedOrders = '';
var invoiceCodes = '';
var flag = 0;
var spaceError = 0;
var commaError = 0;
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
<c:if test="${checkForInvoiceCode}">
var emptyPattern = /^\s*$/;
var commaPattern = /,/;
var inv_code = $("#invoice-code-" + $(this).val()).val().trim();
if (emptyPattern.test(inv_code)) {
spaceError = 1;
flag = 1;
}
if (commaPattern.test(inv_code)) {
commaError = 1;
flag = 1;
}
invoiceCodes += inv_code + ",";
</c:if>
});
if(selectedOrders=='') {
alert('Please select at least one order');
return false;
}
if ( flag ) {
if ( commaError ) {
alert('One or more specified codes have comma, please remove comma from them');
}
if ( spaceError ) {
alert('One or more specified codes has been left blank, please fill them up');
}
if ( !commaError && !spaceError ) {
alert('Please contact tech');
}
return false;
}
var inputdata = {"selectedShipments" : selectedOrders,
"statusCode" : "PRINT"
};
//this is where we are making an ajax call
jQuery(function($){
setTimeout(function(){
var ajaxUrl = '/product/update/';
$.ajax({url:ajaxUrl, type: "POST", dataType: 'json', data:inputdata , success: function(data) {
if(data['status'] == 'success') {
//couponPopup function is called where form is submitted
couponPopup("${path.http}/product/print/", invoiceCodes);
$('#statusChangeSuccess').html(data['message']).show();
$(".selectedOrder:checked").each(function() {
$("#row-" + $(this).val()).remove();
});
} else{
$('#statusChangeFail').html(data['message']).show();
}
}});
}, 10 );
});
return false;
}
<form id="newWinForm" name="newWinForm" action="" method="post" target="_blank" >
<input type="hidden" id="hiddenselectedShipments" name="selectedShipments" value="" />
<input type="hidden" id="hiddenInvoiceCodes" name="invoiceCodes" value="" />
</form>
Controller for the form. Invoice codes is sometimes empty even when we are sending it from client side.
#RequestMapping("/product/print")
public void printSelectedPendingOrders(#RequestParam("selectedShipments") String selectedShipments,
#RequestParam(defaultValue = "", value = "invoiceCodes", required = false) String invoiceCodes, ModelMap modelMap, HttpServletResponse httpResponse)
throws IOException, DocumentException, ParserConfigurationException, SAXException {