I have a basic table with an id column and a location name column. I also have an html form where a user can insert a new location into the table. Before inserting I want to check if my locations table already includes a location name and if it does exist I want to alert the user. If not it will be inserted into the table. First I query the locations table and then I try to use an if statement to see if the input value already matches a location name in my table. But I can't get it to work. My insert code works fine on it's own but I just can't get the conditions working. Any help would be greatly appreciated.
// add a new location
$("#btn-locationAdd").on("click", function() {
var addLocationName = $("#addLocationName");
$.ajax({
url: 'libs/php/getAllLocations.php',
method: 'POST',
dataType: 'json',
success: function (result) {
for (let i = 0; i < result.data.length; i++) {
if (result.data[i].name === addLocationName.val()) {
alert('This location aready exists')
} else {
$.ajax({
url: 'libs/php/insertLocation.php',
method: 'POST',
dataType: 'json',
data: {
addLocationName: addLocationName.val(),
},
success: function (result) {
$("#addNewLocationModal").modal('hide');
const newLocation = $("#alertTxt").html('New Location Record Created');
alertModal(newLocation);
}
});
}
this is the array I get after I query the locations table and get all locations in the table:
{
"status": {
"code": "200",
"name": "ok",
"description": "success",
"returnedIn": "1.5790462493896E-6 ms"
},
"data": [
{
"id": "1",
"name": "London"
},
{
"id": "2",
"name": "New York"
},
{
"id": "3",
"name": "Paris"
},
{
"id": "4",
"name": "Munich"
},
{
"id": "5",
"name": "Rome"
}
]
}
my html:
<!-- Add Location Modal -->
<div id="addNewLocationModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Add New Location</h2>
</div>
<div class="modal-body">
<input type="text" class="form-control" placeholder="Location Name" id="addLocationName"><br>
</div>
<div class="modal-footer">
<input type="button" id="btn-locationAdd" value="Add Location" class="btn btn-success">
<input type="button" id="btn-addLocationCancel" value="CANCEL" data-bs-dismiss="modal" class="btn btn-secondary">
</div>
</div>
</div>
</div>
$("#btn-locationAdd").on("click", function () {
var addLocationName = $("#addLocationName");
$.ajax({
url: 'libs/php/getAllLocations.php',
method: 'POST',
dataType: 'json',
success: function (result) {
let existed = false;
for (let i = 0; i < result.data.length; i++) {
if (result.data[i].name === addLocationName.val()) {
existed = true
break
}
}
if(existed){
alert('This location aready exists')
return
}
$.ajax({
url: 'libs/php/insertLocation.php',
method: 'POST',
dataType: 'json',
data: {
addLocationName: addLocationName.val(),
},
success: function (result) {
$("#addNewLocationModal").modal('hide');
const newLocation = $("#alertTxt").html('New Location Record Created');
alertModal(newLocation);
}
});
}
})
})
Related
I have a table TableElements and a Javascript valiable jsonData.
I want to reload TableElements' dataTable using the reload() method but without success.
The goal is to add a row to the table, inserting it into the database. This is the code I used so far
$.ajax({
url: 'AddRow.php',
type: 'POST',
data: {
CatProg: catProg,
CatUser: catUser,
CatPass: catPass,
CatInUso: catInUso,
CatDesc: catDesc,
CatUltimo: catUltimo,
CatDat: catDat
},
dataType: "text",
success: function(result){
// draw table again
var table = document.getElementById('TableElements');
table.remove();
var tableContainer = document.getElementById('tableContainer');
tableContainer.innerHTML = result;
jsonData = GetJsonFromTable(); // it works
$('#TableElements').DataTable({ ajax: 'data.json' }).reload(); //?? how to put 'jsonData' here?
},
error: function(){
alert("Request did not succeed. Reload and try again.");
}
});
}
This is what jsonData is holding:
[
{
"Aggiungi": "Modifica Elimina",
"CatProg": "1",
"CatUser": "user1",
"CatPass": "user1pass1",
"CatInUso": "Y",
"CatDesc": "desc",
"CatUltimo": "1",
"CatDat": "12-12-2001"
},
{
"Aggiungi": "Modifica Elimina",
"CatProg": "2",
"CatUser": "admin",
"CatPass": "admin",
"CatInUso": "N",
"CatDesc": "aaa",
"CatUltimo": "1",
"CatDat": "01-01-1999"
}
]
I have an API response like this:
{
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}
I want to write the total value from the response above, 5, to my HTML. When I create the js file to get the response the result in HTML is empty.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<div class="inner">
<h3 id="total"></h3>
<p>Total</p>
</div>
$(function() {
$.ajax({
url: 'https://api-url',
type: 'GET',
dataType: 'json',
success: function(data) {
$.each(data, function(value) {
//append each row data to datatable
var row = value.total
$('#total').append(row);
});
}
})
})
Do you know how to show the total that I want from the API in HTML? Thank you
You don't need an each() loop here as the response is a single object, not an array. As such you can access the data.value and set it as the text() of #total, like this:
$(function() {
$.ajax({
url: 'https://api-url',
type: 'GET',
dataType: 'json',
success: function(response) {
var total = response.data.total;
$('#total').text(total);
}
})
})
Use innerHTML to insert value
var a= {
"status": 200,
"message": "OK",
"data": {
"total": 5
}
};
document.querySelector('#total').innerHTML=a.data.total
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<div class="inner">
<h3 id="total"></h3>
<p>Total</p>
</div>
/* $(function() {
$.ajax({
url: 'https://api-url',
type: 'GET',
dataType: 'json',
success: function(response) {
var total = 0;
for (var i = 0; i < response.length; i++) {
total = total + response[i].data.total;
}
$('#total').text(total);
}
})
}) */
// for ex.: -
const data = [{
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}, {
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}, {
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}];
var total = 0;
for (var i = 0; i < data.length; i++) {
total = total + data[i].data.total;
}
$('#total').text(total);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<div class="inner">
<h3 id="total"></h3>
<p>Total</p>
</div>
try this I think it should be work
$('#total').append(`<p>${row}</p>`)
{
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<div class="inner">
<h3 id="total"></h3>
<p>Total</p>
</div>
$(function() {
$.ajax({
url: 'https://api-url',
type: 'GET',
dataType: 'json',
success: function(data) {
var row = data.data.total
$('#total').text(row);
});
}
})
})
I am trying to pass an array that inside an object from a parent component to a child component but answers is coming up undefined. When checking the prop in the parent component the data is there, but when it gets past to the child it is undefined.
Vue.component('single-question', {
props: ['question'],
data: function () {
let vm = this
return {
answers: vm.question.answers
}
},
template: `<div class="question mb-3">
<div class="card">
<div class="card-body">
<h5 class="class-title">{{question.questionId}}</h5>
<p class="card-text">{{question.questionText}}</p>
<a class="btn btn-primary" data-toggle="collapse" v-bind:href="'#answerArea' + question.questionId" role="button" aria-expanded="false" aria-controls="answerArea">List answers</a>
</div>
</div>
<answer-area v-bind:id="'answerArea' + question.questionId" v-bind:answers="question.answers"></answer-area>
</div>`
})
Vue.component('answer-area', {
data: function() {
return {
show: false
}
},
props: ['answers'],
template: `<div class="collapse" id="">
<div class="card card-body">
<ol>
<li v-for="answer in answers" v-bind:key="answer.answerId"></li>
</ol>
</div>
</div>`
})
edit: Here is where the parent is declared
<div id="question-area">
<single-question v-for="question in questions" v-bind:key="question.questionId" v-bind:question="question"
v-bind:id="question.questionId"></single-question>
</div>
Parent data:
new Vue ({
el: '#question-area',
data: {
questions: [{
"answers": [{
"answerId": 21,
"questionId": 1,
"answerText": "One",
"iscorrect": false
},
{
"answerId": 40,
"questionId": 1,
"answerText": "In",
"iscorrect": false
}],
"questionId": 1,
"classCode": "123",
"questionText": "Result",
}],
},
})
Query:
$.getJSON(prestring + "/api/v1/classes/"+parsed.classcode+"/questions", function(json) {
vm.questions = json
vm.questions.forEach(question => {
$.ajax({
url: prestring + "/api/v1/questions/" + question.questionId + "/answers",
dataType: 'json',
//async: false,
success: function (json) {
question["answers"] = json
// question["answers"].push(json)
}
})
})
})
We would have to check what's in your data to be sure, but you are probably facing one of the Change Detection Caveats.
Try using Vue.set() to create your answers property, as below:
$.getJSON(prestring + "/api/v1/classes/"+parsed.classcode+"/questions",
function(json) {
vm.questions = json
vm.questions.forEach(question => {
$.ajax({
url: prestring + "/api/v1/questions/" + question.questionId + "/answers",
dataType: 'json',
//async: false,
success: function (json) {
// question["answers"] = json
Vue.set(question, 'answers', json); // changed this line
// question["answers"].push(json)
}
})
})
})
My json data is as follows
{"status": true, "plans": [{"planId": 1, "name": "Baic", "cost": 500.0, "validity": 365}, {"planId": 3, "name": "free", "cost": 0.0, "validity": 999}, {"planId": 4, "name": "Premium", "cost": 500.0, "validity": 500}, {"planId": 5, "name": "Super Premium", "cost": 750.0, "validity": 600}, {"planId": 6, "name": "New", "cost": 600.0, "validity": 180}]}
I need to select a particular category from the above list and display the corresponding cost of the category in a text box and i need to able to edit the value. How acan I able to obtain the same.
Currently my html code is
<div class="form-group">
<label>Plan <small>(select your plan)</small></label>
<select id="bas" class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Select Plan" v-model="plan" name="plan" ref="plan" required="required">
<option v-for="post in plansb" v-bind:value="post.planId" v-if="plansb.indexOf(post) > 0">{{post.name}} (Rs.{{post.cost}})</option>
</select>
</div>
<div class="form-group">
<label>Plan Amount <small>(required)</small></label>
<input name="plan_amt" type="text" class="form-control" id="plan_amt" placeholder="Plan Amount" v-model="plan_amt" />
</div>
In the Plan Amount text-box I need to display the cost of which category is selected from the above selection. Now I need to enter the amount. IF is selected planId = 1, I need to display 500 in the text-box. Also i need to edit those value and send as as ajax request.
How can I able to get the result as such.
My vue js code is
vBox = new Vue({
el: "#vBox",
data: {
plansb: [],
plan: '',
plan_amt: '',
},
mounted: function() {
var vm = this;
$.ajax({
url: "http://127.0.0.1:8000/alpha/get/plan/",
method: "GET",
dataType: "JSON",
success: function(e) {
if (e.status == 1) {
vm.plansb = e.plans;
}
},
});
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['plan'] = this.plan;
data['plan_amt'] = this.plan_amt;
$.ajax({
url: 'http://127.0.0.1:8000/alpha/add/post/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
$("#alertModal").modal('show');
$(".alert").removeClass("hidden").html("Your data has been successfully recorded");
vm.pid=e.pid;
console.log(vm.pid);
}
else {
vm.response = e;
alert("Registration Failed")
}
}
});
return false;
},
Can anybody please help me to obtain the result. Based on the selection of plans from the select, I need to update the values in the text box. Please help me to have a result.
You need to add change event of list and get the planid of palns, and according to planid get cost of it and assign it to cost(text-box) model where u want to show change plan cost
I am trying to build a single page app that uses $.ajax.
Here is the json data:
{
"restaurants": [
{
"id": 1,
"name": "Denny's",
"location": "Los Angeles",
"cuisine": "American",
"image_url": "http://www.coupons4utah.com/wp-content/uploads/2012/06/dennys-breakfast.jpg"
}
],
"items": [
{
"id": 1,
"restaurantId": 1,
"name": "hamburger",
"price": 10,
"order_count": 0,
"image_url": "http://kleberly.com/data_images/wallpapers/7/277047-hamburger.jpg"
}
],
"public": []
}
I have three buttons on my welcome screen and on of them is "Los Angeles". When I click "Los Angeles", I want it to take me to a page with only results with restaurants from that location. Every time I click it gets me nowhere. I'm stuck and been trying to code my way to make it work for a awhile. I am looking for a solution that will lead me into the right direction. Thanks!
var $body = $("body")
var $losAngeles = $('#los_angeles')
$losAngeles.on('click',function(e){
e.preventDefault();
for (i = 0; i < data.length; i++){
var location = data[i].location;
$.ajax({
url: "/restaurants/:location",
type: "GET",
dataType: 'json',
data:[{location: location}],
success: function(data) {
$.each(data[i].location, function(i, location){
console.log(data[i].location)
})
}
})
}
})
})
I have also tried coming up with this:
$.ajax({
url: '/restaurants/:location',
type: 'GET',
data: [{location: location}],
dataType: 'json',
}).done(function(data){
for ( var i = 0; i < data.length; i++){
var location = data[i].location
if (location === "Los Angeles"){
var name = data[i].name;
var $LA = $('#LA');
$LA.append('<li>' + name + '</li>' )
}
}
})
})
})
Still nothing.
$.ajax({
url: "/restaurants/location", //changed
type: "GET",
dataType: 'json',
data:[{location: location}],
success: function(data) {
$.each(data.restaurants, function(i, location){ //changed
console.log(data.restaurants[i].location); //changed
})
}
})
Also remember not to use ajax calls in loop. If multiple ajax calls are needed use .then jQuery API.