How to send a php variable from a js file to a php file using ajax?
I new with ajax
and php
. I have a file named as main.php
which contains a text box ,when the user scan a number using a scanner or just type the number with pressing the enter key ,then that number will stored by a jquery function which is located in test.js
file.I would like to send that number in to a php file named fetch.php
for processing.But it's not working as well as which is not showing any error messages.I added my snippet below.any useful help will get appreciated!!!
//==================test.js file=============================//
$('#custom-barcode').on({
keypress: function() { typed_into = true; },
change: function() {
if (typed_into) {
var php_val = $('#custom-barcode').val();
alert('your-barcode-is' + php_val);
$.ajax({
method:"post",
url:"fetch.php",
data:{barcode:php_val}
})
clear();
typed_into = false; //reset type listener
} else {
alert('not type');
clear();
}
}
});
function clear(){
$('#custom-barcode').val('');
}
<input id="custom-barcode" type="number" name="custom-barcode" autofocus/>
PHP File :- fetch.php
<?php
if (isset($_POST['barcode'])) {
$bcode = $_POST['barcode'];
echo $bcode;
}
else{
echo "not set";
} ?>
1 answer
-
answered 2018-09-21 19:15
user9741470
Try rewrite this part of the code in this way. According to the
Jquery
documentation, the.on()
event expect as the first parameter an event handler, and as second, a callback function that will manage the related logics.From the doc:
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
$('#custom-barcode').on('keypress change', function(e){ e.preventDefault(); var php_val = $('#custom-barcode').val(); if(php_val != ''){ alert('your-barcode-is' + php_val); $.ajax({ method:"post", url:"fetch.php", data:{barcode:php_val}, cache: false, success: function(response){ clear(); } }); } else { alert('not type'); clear(); } }); function clear(){ $('#custom-barcode').val(''); }
See also questions close to this topic
-
Materialize CSS autocomplete from XML
I am trying to parse XML in PHP and then put it as an object in JavaScript to Materialize CSS autocomplete.
I tried to parse it in PHP and put it as an object in JavaScript with
json_encode($array)
But it didn't work. Autocomplete shows just numbers.You have to put data as an object in "data". And it must be as
"string": 'http://url'
the URL is for a thumbnail. But I want it as"string": null
. So there won't be a thumbnail.This is a sample from Materialize CSS documentation: https://materializecss.com/autocomplete.html
$(document).ready(function(){ $('input.autocomplete').autocomplete({ data: { "Apple": null, "Microsoft": null, "Google": 'https://placehold.it/250x250' }, }); });
My XML file:
<tittle> <topic> <name>PHP</name> </topic> <topic> <name>JS</name> </topic> <topic> <name>CSS</name> </topic> </tittle>
My PHP and JavaScript code:
<?php $xml = simplexml_load_file("xml.xml"); $array = array(); foreach($xml->topic as $topic) { $array[] = $topic->name; } ?> <script > var data = <?php echo json_encode($array); ?>; $(function () { $('input.autocomplete').autocomplete({ data: data }); }); <script>
Thank you for response
-
How do I add a close button to a FullCalendar event?
I am learning how to append a close button to dynamically created selectable events in FullCalendar. I found a demo that uses the eventRender callback to append a close button to selectable events as they are created. However, I don't understand why an underscore "_" was added to "event._id" inside this callback. Is it necessary to have this underscore? Could someone perhaps explain this concept? Here is the demo to which I am referring. Thanks!
HTML
<div id='calendar'></div>
JS
$(document).ready(function() { $("#calendar").fullCalendar({ header: { left: "prev,next today", center: "title", right: "month,agendaWeek,agendaDay" }, defaultView: "month", navLinks: true, // can click day/week names to navigate views selectable: true, selectHelper: false, editable: true, eventLimit: true, // allow "more" link when too many events select: function(start, end) { var title = prompt("Event Content:"); var eventData; if (title) { eventData = { title: title, start: start, end: end }; $("#calendar").fullCalendar("renderEvent", eventData, true); // stick? = true } $("#calendar").fullCalendar("unselect"); }, eventRender: function(event, element) { element .find(".fc-content") .prepend("<span class='closeon material-icons'></span>"); element.find(".closeon").on("click", function() { $("#calendar").fullCalendar("removeEvents", event._id); }); }, eventClick: function(calEvent, jsEvent) { var title = prompt("Edit Event Content:", calEvent.title); calEvent.title = title; $("#calendar").fullCalendar("updateEvent", calEvent); } }); });
CSS
body { margin: 40px 10px; padding: 0; font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif; font-size: 14px; } #calendar { max-width: 900px; margin: 0 auto; } #wrap { width: 1100px; margin: 0 auto; } .closeon { border-radius: 5px; } /*info btn*/ .dropbtn { /*background-color: #4CAF50;*/ background-color: #eee; margin: 10px; padding: 8px 16px 8px 16px; font-size: 16px; border: none; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f1f1f1; min-width: 200px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; margin-left: 100px; margin-top: -200px; } .dropdown-content p { color: black; padding: 4px 4px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #ddd;} .dropdown:hover .dropdown-content {display: block;} .dropdown:hover .dropbtn {background-color: grey;} .dropdown:hover .dropbtn span {color: white}
-
How to connect over wifi for multiplayer Connect Four game in React?
I'm learning webdev and React by writing a simple 'Connect Four' game (https://github.com/DavidDeprost/connect4_react). It's not yet finished, but it already works fine (fully responsive with customizable gridsize, checkers and timer)! I've noticed that Create-React-App by default makes the app available on my home network, which is amazing. What I'd like to try next though is network it, so that I can access the same instance from different computers in the network, in order to play against each other (now you can only play with 2 persons on the same computer).
But I honestly have no clue on how to proceed with this, or even what to research ... Would it require node.js to just play over wifi? Something else? Is it actually simpler if I just want multiplayer over wifi, compared to fully online (with a backend), or does a (peer-to-peer?) app require pretty much the same? Would this require massive changes, or be a rather straightforward addition?
Sorry for the ton of questions, but it is mostly just to illustrate what I'm struggling with, never having done anything networked before. I'd be more than happy if someone could provide some pointers or feedback on how to proceed (or even the topic name to research on google/blogs/...). (Any general feedback, tips, or even PR's on the app itself are also very much welcome)
-
Update if exists, else insert (without ON DUPLICATE KEY UPDATE)
I am trying to write a script to insert data from an API in a database, but if it already exists, update the data. Next to this, I want to delete data from the database if the data doesn't exist in the Array. (For now already happy if I could just have the update working)
Have been Googling for 2 days to find a solution for my problem, but nothing that I have tried has helped. For now I have the first time insert working, so it will write the initial call to the DB, but all next calls don't do anything. No updates or inserts anymore.
The ON DUPLICATE KEY UPDATE option is not possible in my case, because the id mentioned in my code is not the primary key of the table where I will be inserting in. (This code is just the example, the real database is a bit more complex and I can't change the tables itself).
$content = file_get_contents($url); $array = json_decode($content, true); $sql = array(); $update = array(); foreach($array as $row) { // Create insert string $sql[] = '('.$row['userId'].', '.$row['id'].', "'.mysqli_real_escape_string($link, $row['title']).'", "'.mysqli_real_escape_string($link, $row['body']).'")'; // Create update data $update[] = 'UPDATE TestDB.testTabel SET userId='.$row['userId'].', id='.$row['id'].', title= "'.mysqli_real_escape_string($link, $row['title']).'", body = "'.mysqli_real_escape_string($link, $row['body']).'" WHERE id = '.$row['id']. ';'; $flag = 0; $query = "SELECT id FROM TestDB.testTabel WHERE id =".$row['id']; $result = mysqli_query($link, $query); if(mysqli_num_rows($result) > 0) { $flag=1; } else { $flag=0; } } if($flag==1) { echo 'found!'; mysqli_query($link, " ".implode('', $update)); //print ''.implode('', $update); } else if ($flag==0) { echo 'not found!'; mysqli_query($link, "INSERT INTO TestDB.testTabel (userId, id, title, body) VALUES ".implode(',', $sql)); // print 'INSERT INTO TestDB.testTabel (userId, id, title, body) VALUES '.implode(',', $sql); } else { echo 'ERROR!'; }
I would want my script to check for every array line if it exists, if yes --> update, else --> insert.
So basically, what I want to do this (in pseudo code):
Get data from API
for each [API record] { Query database to see if ID already exists
if (ID exists) { update record }
else if (ID not exists) ( insert record }
else { error } }
for each [DB record] { check if DB id is in API data
if (DB id not in API data) { Remove record from db }
else { do nothing } }
Really stuck now :( who could help me out?
-
How to insert the current date within an array
I'm trying to insert the current date into a database for each entry within an array. I've found documentation for inserting the current date, but nothing that explains how to do it within an array.
<?php $connect = new PDO("mysql:host=localhost;dbname=testing", "root", ""); $query = " INSERT INTO tbl_test (full_name, id_number, email, pin_rank, team_name) VALUES (:full_name, :id_number, :email, :pin_rank, :team_name) "; for($count = 0; $count<count($_POST['hidden_full_name']); $count++) { $data = array( ':full_name' => $_POST['hidden_full_name'][$count], ':id_number' => $_POST['hidden_id_number'][$count], ':email' => $_POST['hidden_email'][$count], ':pin_rank' => $_POST['hidden_pin_rank'][$count], ':team_name' => $_POST['hidden_team_name'] ); $statement = $connect->prepare($query); $statement->execute($data); } ?>
I would like the current date to display in the last column within the table. Any help would be appreciated.
-
Validate whether checkbox with the same name is selected in different groups
I have several checkboxes on a page that contains the same name. However, they are arranged in rows in a table so that they can be selected by the user. So, I need to validate if at least one checkbox in each row is selected.
The following image visually shows the page for this problem:
The following code is only a part of all the code that generates the above image.
<div class="form-group"> <label>Ensino Fundamental</label> <div class="form-check m-l-10"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="1anoensinofundamental" name="OfertaSerie" value="63" data-oferta-nivel-ensino="1"> <label class="custom-control-label" for="1anoensinofundamental">1º ano</label> </div> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="2anoensinofundamental" name="OfertaSerie" value="64" data-oferta-nivel-ensino="1"> <label class="custom-control-label" for="2anoensinofundamental">2º ano</label> </div> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="3anoensinofundamental" name="OfertaSerie" value="51" data-oferta-nivel-ensino="1"> <label class="custom-control-label" for="3anoensinofundamental">3º ano</label> </div> </div> </div> <div class="form-group m-t-20"> <label>Ensino Médio</label> <div class="form-check m-l-10"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="1serieensinomedio" name="OfertaSerie" value="45" data-oferta-nivel-ensino="2"> <label class="custom-control-label" for="1serieensinomedio">1ª série</label> </div> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="2serieensinomedio" name="OfertaSerie" value="54" data-oferta-nivel-ensino="2"> <label class="custom-control-label" for="2serieensinomedio">2ª série</label> </div> </div> </div>
-
JS add text in generated ajax div
looking for some help, how to add custom text value to Ajax generated input text field. But cannot get element by id or class, none of the code works. Tried code which one check if regul price not empty, then it should to add text to field, but it doesn't work.
<script type="text/javascript"> if($("#_regular_price").length > 0) { $("#snippet-editor-field-description").text('labas') }; </script>
Tried this code as well to check if even work with alert, but it doesn't.
<script type="text/javascript"> $('#snippet-editor-field-description').click( function() { alert('clicked'); }); </script>
Anyone could asist how to get element and add custom text before Excerpt where is marked yellow?
-
How to solve mysql high usage problem for shared hosting in my website?
Today suddenly my hosting for website was suspended by my service provider. I need help finding what is actually causing the problem. They sent me logs shared below.
Reason of suspension :High Usage of MYSQL Here are your logs of high usage for MYSQL:
ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1663045 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1663674 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1664163 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1664518 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1665183 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1675598 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1676464 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1676932 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1677146 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1708438 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1789011 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1800685 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1816150 ncgtjnoe_begreen localhost ncgtjnoe_crmbegreen Sleep 4 NULL 1824685 ijnxqsbq_boltlgu localhost ijnxqsbq_boltlgu Sleep 95 NULL 1825121 ijnxqsbq_boltlgu localhost ijnxqsbq_boltlgu Sleep 18 NULL 1825190 ijnxqsbq_boltlgu localhost ijnxqsbq_boltlgu Sleep 4 NULL 1825191 ijnxqsbq_boltlgu localhost ijnxqsbq_boltlgu Sleep 3 NULL
Whats causing high usage i doubt i am using long-pooling for push notification which is causing problem.
Here is the code for notifications used on every page of website.
<script type="text/javascript"> function poll() { var ajax = new XMLHttpRequest(); ajax.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { if (this.status === 200) { try { var json = JSON.parse(this.responseText); //alert('changed'); } catch { setTimeout(poll,55000);return; } if (json.status !== true) { alert(json.error);return; } var data = json.data; for (var i = 0, len = data.length; i < len; i++) { var x = data[i]; var body = 'Task: ' + x.content + '\nDate: ' + x.time + '\nID: ' + x.id; notifyMe(body,x.id); } setTimeout(poll,55000); } else { setTimeout(poll,55000); } } } ajax.open('GET', 'long-polling.php', true); ajax.send(); } setTimeout(poll,60000); //var body1 = "This is the body of the notification asargument"; function notifyMe(body1,id) { // Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } // Let's check if the user is okay to get some notification else if (Notification.permission === "granted") { // If it's okay let's create a notification var options = { body: body1, icon: "icon.png", dir : "ltr" }; var notification = new Notification("Task Alert",options); notification.addEventListener("click", function() { window.open('opentask.php?id='+id, '_blank'); window.focus(); this.close(); // Do something cool }, {once : true}); } // Otherwise, we need to ask the user for permission // Note, Chrome does not implement the permission static property // So we have to check for NOT 'denied' instead of 'default' else if (Notification.permission !== 'denied') { Notification.requestPermission(function (permission) { // Whatever the user answers, we make sure we store the information if (!('permission' in Notification)) { Notification.permission = permission; } // If the user is okay, let's create a notification if (permission === "granted") { var options = { body: "Notifications enabled", icon: "icon.png", dir : "ltr" }; var notification = new Notification("Notification",options); } }); } // At last, if the user already denied any notification, and you // want to be respectful there is no need to bother them any more. } </script>
Here is the code for long-polling.php file
<?php //session_start(); session_write_close(); ignore_user_abort(false); set_time_limit(40); try { include_once '../config.php'; $user = $_COOKIE['loggedinid']; while (true) { // select new rows $result = $mysqli -> query("SELECT t.id, t.title, t.description , t.reminder FROM tasks t INNER JOIN tasks_update_track ud ON ud.last_sent_id < t.id WHERE ud.user_id = $user AND t.responsibleperson=$user ORDER BY t.id"); // check whether there were new rows in above query if ($result && $result -> num_rows) { //if yes, makes the output $output = []; // this is used to update the db_user_data table at last. As rows are ordered by t.id in ascending order in above query, last row has the last Id $lastId = 0; foreach ($result as $row) { $output[] = [ 'content' => $row['title'], 'id' => $row['id'], 'time' => $row['reminder']]; $lastId = $row['id']; } // update the table and set last_sent_id to the last sent row id of other table. $mysqli -> query("UPDATE tasks_update_track SET last_sent_id = $lastId WHERE user_id = $user"); echo json_encode([ 'status' => true, 'data' => $output ]); exit; } // db queries are heavy. So 2 seconds sleep(5); } } catch (Exception $e) { exit( json_encode( array ( 'status' => false, 'error' => $e -> getMessage() ) ) ); }
-
Sending multiple JSON lists and image in FormData to C#
I'm trying to send two lists of JSON, a DateTime, int, string, and file to a C# controller via JQuery AJAX POST request.
All data sends fine except the two object arrays, they send nothing.
I've tried changing them from a list of objects to a list of strings to convert from there, but the array is received as one long string, making it nonconvertible via JsonConvert in Newtonsoft.Json.
I've tried logging the formdata objects in order to check their validity, and they seem fine in console. I'm not entirely sure where I've messed up.
Here is my JS:
var formData = new FormData(); formData.append("assignedUsers", JSON.stringify(assignedUsers)); formData.append("ccUsers", JSON.stringify(ccUsers)); formData.append("dueDate", $("#DueDate").val()); formData.append("goalClassID", parseInt(goalClassID)); formData.append("goalDescription", $("#GoalDescription").val()); formData.append("file", document.getElementById("GoalFile").files[0]); for (var pair of formData.entries()) { console.log(pair[0] + ', ' + pair[1]); } $.ajax({ url: api + "main/CreateGoal", type: "POST", data: formData, cache: false, dataType: "json", processData: false, contentType: false, success: function (result) { if (result) { toastr.success("Goal successfully created"); } else { toastr.error("Goal creation failed."); } } })
This is my C# Controller:
public bool CreateGoal([FromForm]List<User>AssignedUsers, [FromForm]List<User>CCUsers, [FromForm]DateTime DueDate, [FromForm]int GoalClassID, [FromForm]string GoalDescription, [FromForm]IFormFile File = null)
This is User class
public class User : Base { public string UUID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public int Permission { get; set; } public string FullName { get { return FirstName + " " + LastName; } } }
-
How can I print a document with textboxes showing? (vB)
So I have been trying to print a document where the textboxes are shown on top of a picturebox, however it just doesn't seem to work.
Imports System.Drawing.Printing Public Class Form1 Dim WithEvents mPrintDocument As New PrintDocument Dim mPrintBitMap As Bitmap
Private Sub m_PrintDocument_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles mPrintDocument.PrintPage ' Draw the image centered. Dim lWidth As Integer = e.MarginBounds.X + (e.MarginBounds.Width / 0.95 - mPrintBitMap.Width) \ 1 Dim lHeight As Integer = e.MarginBounds.Y + (e.MarginBounds.Height / 0.9 - mPrintBitMap.Height) \ 2 e.Graphics.DrawImage(mPrintBitMap, lWidth, lHeight) ' There's only one page. e.HasMorePages = False End Sub Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click picFij.SendToBack() lblDN.BringToFront() mPrintBitMap = New Bitmap(Me.Width, Me.Width) Dim lRect As System.Drawing.Rectangle lRect.Width = Me.Width lRect.Height = Me.Width Me.DrawToBitmap(mPrintBitMap, lRect) mPrintDocument = New PrintDocument printPreviewDialog1.Document = mPrintDocument PrintPreviewDialog1.ShowDialog() End Sub
I attempted a BringToFront() and SendToBack() but that didn't work.
This is what I want to print: https://cdn.discordapp.com/attachments/358502382910570497/546555282940100648/unknown.png
And this is print preview https://cdn.discordapp.com/attachments/358502382910570497/546555621806178324/unknown.png
Any ideas?
-
How to add values into an array from a textbox with a button click event in angular 2
“How to add values into an array from a single textbox with a button click event in angular 2”
-
Qlikview Format textbox expression as percentage to 3 decimal places
I am trying to show percentage increase / decrease based on week number for 2018 v 2019 with an expression in a textbox in Qlikview: Here is my expression:
= num(Sum({<Year = {$(=Max(Year))}, Week = {"$(=Week(Today()))"}>}Retail) - Sum({<Year = {$(=Max(Year)-1)}, Week = {"$(=Week(Today()))"}>}Retail)) / num(Sum({<Year = {$(=Max(Year)-1)}, Week = {"$(=Week(Today()))"}>}Retail),'##0 %')
No matter what i try i end up with
-0.38877082
etc.What am i doing wrong?