Proper way of doing AJAX request to retrieve data from database - javascript

I got a database with one table in it.
Table has Company and Time columns, and some more, but these two are important.
So the user makes an appointment through the filling of the form.
In the form I have 2 <select>s - Company And Time, so he chooses both from the selections.
He clicks a button and the form is stored in the database.
How do I use AJAX to retrieve all the hours(Time) that are in use, and then disable them accordingly.
For example: I made the appointment selected Nokia from Companies and 9:30 from Time dropdowns. Now You want to make the appointment with Nokia but the 9:30 time is disabled because it has already been used.
What would be the correct way to use AJAX for this:
this is my structure
function MakeApp() {
var AppWith = $("#CompanySelect").val();
var AppTime = $("#TimeSelect").val();
var Yritys = $("#YritysNtext").val();
var Henkilonimi = $("#HenkilonimiText").val();
var Asema = $("#AsemaText").val();
var PuhelinNR = $("#PuhelinText").val();
var EMail = $("#EMailText").val();
var Keskustelun = $("#KeskustelunText").val();
var app = { AppWithYritys: AppWith, AppTime: AppTime, YritysN: Yritys, Henkilonimi: Henkilonimi, Asema: Asema, PuhelinNR: PuhelinNR, EMail: EMail, Keskustelun: Keskustelun }
var request = $.ajax({
type: "POST",
data: JSON.stringify(app),
url: "/api/Appointments",
contentType: "application/json",
dataType: "html"
});
request.done(function (podaci) {
if (podaci != -1) {
alert("You Have successfully made an appointment");
location.assign("BookAppointment.html");
}
else {
$("#p1").html("Greska pri unosu");
}
});
request.fail(function (gr) {
$("#p1").html(gr.statusText);
});
};

Actually it's your server job to manage data and database. AJAX is only a way to send information to a server aysnchronously. What you could do, is when you load the page, you retrieve only the occupied time with AJAX, you disable their options in your select, and whenever your server receive an request, it checks if there is an available place for the company and times.
I'm sorry i don't have a code for your since I think it's pretty clear. If it's not, feel free to comment, i'll try to help you the best i can.
Edit
Here I have a few lines of code, it's not complete since we are missing a few informations but it is the main algorythm.
Your server:
{GET}
public void getUnavailable() {
//get all times from Databases for today's date.,
//Encode them in JSON.
//returns the times.
}
Lets assume that your JSON looks like this:
[
{
"company": "Nokia",
"times": [
"9:30",
"10:00",
"10:30"
]
}
]
You need to retrieve your JSON and parse it to disable the time in the selected select:
$(document).ready(function(){
$.ajax({
'url': API_URL + 'event/getUnavailable',
'method': 'GET',
'success': function(data) {
$.each(data.data, function($index, $company){
var select = /* .. Get the Select of the current company .. */
$.each($company.times, function($index, $times){
select./*.. Find the time associate with $time .. */.setDisable(true); // I don't know if setDisable is the correct function, you might want to check this out.
})
})
},
'error': function(error) {
console.error(error.data);
}
});
$('.myForm').submit(function(){
// This is where you submit your data to your server.
$.ajax({
'url': API_URL + "event/create",
'method': 'POST',
'data': /* your data */,
'success': function(){
console.log('success');
},
'error': function(error) {
console.error(error);
}
})
});
})
This is the most I can do with the info I have.

The real way to handle this, is whatever web technology you have behind /api/Appointments, is to return whatever appointments are available. Your variable names don't make much sense to me, so try to understand what the code below does.
$.get( "/api/Appointments", JSON.stringify(app) )
.done(function( data ) {
//note that the "data" variable holds your returned appointments
//I would return a json document of available appointment times to filter your select
//sample json would look something like this
// { "availableAppointments": ["9:30 AM", "10:00 AM"] }
// and then iterate through available appointments and populate your select
for(var i = 0; i < data.availableAppointments.length; i++){
$('#yourSelectId').append($('<option>', {
value: 930,
text: data.availableAppointments[i]
}));
}
});
Please note this code may not be syntactically correct.
Here are some links that helped me answer this for you, in case they might help.
Adding options to a <select> using jQuery?
https://api.jquery.com/jquery.get/

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.

Security issues while sending variable from Javascript to PHP

I'm developing JavaScript game. I need to insert some records (such as score, time, level, etc.) to database.
To do It I can use JavaScript in following:
function jsFunction() {
var jsScore = 1000;
window.location.href = "file.php?score=" + jsScore;
}
And in PHP file I could use $_GET['score'];
But looks like this way is not secure, user could change score at address bar directly in browser. Am I wrong?
How could I do It in more secure way?
Maybe sending the data via AJAX post would be more appropriate. Technically the user could still edit it using the dev console but it much less visible.
<script>
function jsFunction() {
var jsScore = 1000;
$.post( "file.php", { score: jsScore})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
</script>
You can make use of the jquery library and send the ajax request to the php page. like below.
function jsFunction() {
var jsScore = 1000;
$.ajax({
method: "POST",
url: "file.php",
data: { score: jsScore }
}).done(function(response){
//you can perform some activity after score saved etc..
}).fail(function(response){
//you can perform some activity if score do not saved etc..
})
}
then you can access the score using $_POST['score']; in php.
Try sending data in post using ajax. This will not show data in url and is also secure as the data passes in post.Here is the code
var score = '1000';
var time = '10';
$.ajax({
url: 'file.php',
type: "POST",
data: {score: score, time: time,},
success: function(posData) {
// success code here
},
});
In file.php you can get all parameters in
print_R($_POST);

Having a hard time understanding redirecting / routing in laravel

I am completely stuck since two hours and definitely need your help. Disclaimer: I am not a coder - just a guy who is trying to mock up an idea.
So my page is actually working fine but I thought about moving content from a modal-popup to an actual sub-page. Meaning: If a user clicks on a button, some data points from the current page are being collected and passed to another view which shall be rendered using the data points as input.
EDIT: For clarification: The button is on /results.php where data is generated dynamically. The method should take some data points from here and generate a new view and render it at /buy.php or maybe at /buy/custom.php
My thoughts:
Normal redirect without parameters: Internal Link
Updating page-content without redirect but with parameters: Ajax
So combining my thoughts -> use ajax and return a new fresh view.
What I tried:
$("body").on("click", ".fa-shopping-cart", function() {
var $para1 = $(this).attr("data1");
var $para2 = $(this).attr("data2");
var $para3 = $(this).attr("data3");
var $para4 = $(this).attr("data4");
$.ajax({
url: "buy",
data: {
a: $para1,
b: $para2,
c: $para3,
d: $para4
},
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
type: "post",
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});});
Routing:
Route::post('/buy', 'PageRouting#buy');
Controller:
public function buy()
{
$para1= $_POST['a'];
$para2 = $_POST['b'];
$para3 = $_POST['c'];
$para4 = $_POST['d'];
// some magic to output $data
return view('pages.buy', compact("data"));
}
buy.blade.php exists and displays $data with help of an foreach-loop.
So, when I first clicked the button the obvious happend:
The view ('pages.buy') is logged / displayed in my console in plain html and not rendered in the browser.
Now I am sitting here since two hours and I have no clue whatsoever. I read some blog post saying that you cannot redirect within an ajax-call. Unfortunately the post did not gave any hint on how to do it instead.
Can someone help me?
All best
If you want to replace entire document with the response you have to use document.write but it's not the best thing to do. Why don't you use normal form submit if you need to return a view?
success: function(response){
document.write(response);
},
P.S. if you want also to change the url, use the history manipulation functions.
https://developer.mozilla.org/en-US/docs/Web/API/History_API
in your buy method -
public function buy ()
{
....//some stuff to get $data
$html = view('pages.buy', compact("data"))->render();
return response()->json([
'success' => true,
'html' => $html
])
}
in your ajax success function
success: function(response){
if(response.success)
{
$('#elementId').html(reponse.html) // or whatever you need
}
},

Ajax-Post data again AFTER success

So I have got a small application that check metrics for domains that are valuable for SEO. I establish a connection with API and process them to get the relevant data.
Everything works great there and I do get my data, problem is with Javascript main.js that processes that data.
So my main idea is that I have a select input that corresponds to specific API calls, then a textarea where you paste your links. All works great, and I manage to get the response using ajax and build a relevant view corresponding to a specific method selected.
When ajax responds with success, I fetch data, parse it and make relevant function calls. When page is built, on top I need to have a small select box that would make user to select different method and would retrieve data for the same links. After success I have built a input that correspond to the same select used on main page.
And my question is How can i send data again?
So, here is the code
$("#parseLink").on("click", function () {
var textBox = $("#linkInput").val();
var method = $("#select").val();
var newTextBox = textBox.split("\n");
var methodsList = {
"Social Values": "GetValueSocialSpread",
"Social Visibility": "SocialGetValueVisibility",
"Organic Keyword Count": "GetCountDomainKeyword",
"Seo Visibility": "SeoVisibilityWorld"
};
var selectedApi = methodsList[method];
var dataToSend = {
url: newTextBox,
api: selectedApi
}
$("#container").replaceWith("<div class='containter text-center'><h1>Loading...</h1><i class='fa fa-spinner fa-pulse fa-5x'></i></div>");
function mainFunc() {
$.ajax({
type: "POST",
url: "../parser.php",
data: {
data: JSON.stringify(dataToSend)
},
success: function (response) {
//remove loading
$("div.text-center").remove();
$("div.main_holder").append("<div class='container'><div class='row'><div class='pull-right'><button id='export' type='button' class='btn btn-info'>Export</button></div></div></div>");
$("div.main_holder").append("<div class='container'><div class='row'><select class='form-control' id='select'><option>Social Values</option><option>Social Visibility</option><option>Organic Keyword Count</option><option>Seo Visibility</option></select></div></div>");
var result = JSON.parse(response);
var jsonObject = result;
urlArray = [];
$.each(result, function (k, v) {
urlArray.push(k);
});
if (method === "Social Values") {
socialValues(result, urlArray);
} else if (method === "Social Visibility") {
socialVisibility(result, urlArray);
} else if (method === "Organic Keyword Count") {
organicKeyWordCount(result, urlArray);
} else if (method === "Seo Visibility") {
seoVisibility(result, urlArray);
}
}
});
}
});
I tried calling ajax function again, not working... it probably has a simple solution(hopefully)
I am opened to suggestions! And please tell me if you need more elaborate explanation! Was doing it all night :))

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