Angular.js $http.post with Codeigniter not working - javascript

I'm trying to submit a new post using $http. it's not working. I tried the shore version and the long version, both fail. console:" Failed to load resource: the server responded with a status of 500 (Internal Server Error) "
This my code:
$scope.doAdd = function(){
$http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'api/addduans',
method: "POST",
})
.success(function(data) {
alert('OK');
});
}
My controller:
function addduans_post()
{
$id_duan = $this->post('id_duan');
$title = $this->post('title');
$addr = $this->post('addr');
$dis = $this->post('dis');
$img_duan = $this->post('img_duan');
$result = $this->admin_model->add_id_da($id_duan,$title,$addr,$dis,$img_duan);
if($result === FALSE)
{
$this->response(array('status' => 'failed'));
}
else
{
$this->response(array('status' => 'success'));
}
}
My Model:
public function add_id_da($id_duan,$title,$addr,$dis,$img_duan)
{
$data = array(
'id_duan' => $id_duan,
'title' => $title,
'addr' => $addr,
'dis' => $dis,
'img_duan' => $img_duan
);
$this->db->insert('duan_test', $data);
}
This my view :
<tr>
<td> <input name='id_duan' style='width: 50px' ng-model='id_duan'/> </td>
<td> <input name='title' ng-model='title'/> </td>
<td> <input name= 'addr' ng-model='addr'/> </td>
<td> <input name='dis' style='width: 60px' ng-model='dis'/> </td>
<td> <input name='img_duan' ng-model='file_name'/> </td>
<td> Add </td>
</tr>
Anyone got any idea on how to make this work? Thanks!

Step 1: Make your input fields into a form.
<form ng-submit='doAdd()'>
<tr>
<td> <input name='id_duan' style='width: 50px' ng-model='myForm.id_duan'/> </td>
<td> <input name='title' ng-model='myForm.title'/> </td>
<td> <input name= 'addr' ng-model='myForm.addr'/> </td>
<td> <input name='dis' style='width: 60px' ng-model='myForm.dis'/> </td>
<td> <input name='img_duan' ng-model='myForm.file_name'/> </td>
<td> <input type="submit" class="btn - btn-info" value="add"> </td>
</tr>
</form>
Step 2: Submit the form
$scope.formData = {};
$scope.doAdd = function(){
$http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'api/addduans',
method: "POST",
data : $.param($scope.formData)
})
.success(function(data) {
alert('OK');
});
}
Hope it helps. You seem to be switching from jQuery. Refer here for a simple tutorial.

I faced such condition. I have used custom serialize service as following . it may be use for your problem.
appCommonServiceModule.factory('SerialiazeService', function () {
function SeriliazeService() {
this.serialiaze = function (obj, prefix) {
var str = [];
for (var p in obj) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ? this.seriliaze(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
}
return new SeriliazeService();
});
it is used in $http.post like that (memberModel is javascript object data type):
$http.post(BASE_URL + 'index.php/signUp', SerialiazeService.serialiaze(memberModel), {responseType: 'json', headers: {'Content-Type': 'application/x-www-form-urlencoded'}})

change this code
$http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'api/addduans',
method: "POST",
data : $.param($scope.formData)
})
to this:
var request = $http.post('api/addduans', $.param($scope.formData), {headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}});

Related

update function failing, create & delete working

I can create, delete and display all but the update function will not work and does nothing. When I look the error in the console log it points to
jquery.min.js:2 PUT http://localhost:5000/shop/9 400 (BAD REQUEST)
send # jquery.min.js:2
ajax # jquery.min.js:2
updateServer # index.html:133
doUpdate # index.html:129
onclick # index.html:35
index.html:147
I cant see where I am going wrong. Am I missing something or is it within the update server code? This is the html code. A lot of the code for the update server is taken from other places within the html which works fine.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title> View Shopping List</title>
</head>
<body>
<h1>Shop</h1>
<div id="create-update" style="display:none">
<h2>create-edit</h2>
<table id="createUpdateForm">
<tr>
<td>ID</td>
<td><input type="hidden" name="ID" id="idInput"></td>
</tr>
<tr>
<td>Dept</td>
<td><input type="text" name="Dept"></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="Name"></td>
</tr>
<tr>
<td>Amount</td>
<td><input type="text" name="Amount"></td>
</tr>
<tr>
<td></td><td>
<button id="create-button" onclick="doCreate()">Create</button>
<button id="update-button" onclick="doUpdate()">update</button>
</td>
</tr>
</table>
</div>
<div id="display">
<h2>Shop</h2>
<button onClick="showCreate()">Create</button>
<table id="shopTable" class="table">
<tr>
<th>ID</th><th>Dept</th><th>Name</th><th>Amount</th><th></th><th></th>
</tr>
</table>
</div>
JS:
function showCreate() {
document.getElementById('display').style.display = "none"
document.getElementById('update-button').style.display = "none"
document.getElementById('create-button').style.display = "block"
document.getElementById('create-update').style.display = "block"
}
function showUpdate(thisElem) {
var rowElement = thisElem.parentNode.parentNode;
shop = readShopFromRow(rowElement)
populateForm(shop)
document.getElementById('display').style.display = "none"
document.getElementById('update-button').style.display = "block"
document.getElementById('create-button').style.display = "none"
document.getElementById('create-update').style.display = "block"
}
function readShopFromRow(rowElement) {
shop = {}
shop.ID = rowElement.getAttribute("ID");
shop.Dept = rowElement.cells[1].firstChild.textContent
shop.Name = rowElement.cells[2].firstChild.textContent
shop.Amount = rowElement.cells[3].firstChild.textContent
return shop
}
function populateForm(shop) {
var form = document.getElementById('createUpdateForm')
form.querySelector('input[name="ID"]').value = shop.ID
form.querySelector('input[name="ID"]').disabled = true
form.querySelector('input[name="Dept"]').value = shop.Dept
form.querySelector('input[name="Name"]').value = shop.Name
form.querySelector('input[name="Amount"]').value = shop.Amount
}
function clearForm() {
var form = document.getElementById('createUpdateForm')
form.querySelector('input[name="ID"]').value = ''
form.querySelector('input[name="ID"]').disabled = false
form.querySelector('input[name="Dept"]').value = ''
form.querySelector('input[name="Name"]').value = ''
form.querySelector('input[name="Amount"]').value = ''
}
function doCreate() {
console.log("in doCreate")
shop = getShopFromForm()
console.log(shop)
$.ajax({
url: "/shop",
data: JSON.stringify(shop),
method: "POST",
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result)
addShopToTable(shop)
showDisplay()
clearForm()
},
error: function(xhr, status, error) {
console.log("error" + error)
}
})
}
function doUpdate() {
shop = getShopFromForm()
updateServer(shop)
}
function updateServer(shop) {
$.ajax({
url: "/shop/" + shop.ID,
data: JSON.stringify(shop),
method: "PUT",
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result)
updateTableRow(shop)
showDisplay()
clearForm()
},
error: function(xhr, status, error) {
console.log("error" + error)
}
})
}
function doDelete(thisElem) {
var tableElement = document.getElementById('shopTable');
var rowElement = thisElem.parentNode.parentNode;
var index = rowElement.rowIndex;
ID = rowElement.getAttribute("id");
$.ajax({
url: "/shop/" + ID,
method: "DELETE",
dateType: "JSON",
success: function(result) {
tableElement.deleteRow(index);
},
error: function(xhr, status, error) {
console.log(error)
}
})
}
function updateTableRow(shop) {
rowElement = document.getElementById(shop.ID)
rowElement.cells[1].firstChild.textContent = shop.Dept
rowElement.cells[2].firstChild.textContent = shop.Name
rowElement.cells[3].firstChild.textContent = shop.Amount
//console.log("updating table")
}
function getShopFromForm() {
var form = document.getElementById('createUpdateForm')
var shop = {}
shop.ID = form.querySelector('input[name="ID"]').value
shop.Dept = form.querySelector('input[name="Dept"]').value
shop.Name = form.querySelector('input[name="Name"]').value
shop.Amount = form.querySelector('input[name="Amount"]').value
//console.log(shop)
return shop
}
function showDisplay() {
document.getElementById('display').style.display = "block"
document.getElementById('create-update').style.display = "none"
}
function populateTable() {
//ajax getAll
$.ajax({
url: 'http://127.0.0.1:5000/shop',
method: 'GET',
datatype: 'JSON',
success: function(results) {
for (shop of results) {
addShopToTable(shop)
}
},
error: function(xhr, status, error) {
console.log("error " + error + " code:" + status)
}
})
}
function addShopToTable(shop) {
//console.log("working so far")
tableElem = document.getElementById("shopTable")
rowElem = tableElem.insertRow(-1)
rowElem.setAttribute("ID", shop.ID)
cell1 = rowElem.insertCell(0)
cell1.innerHTML = shop.ID
cell2 = rowElem.insertCell(1)
cell2.innerHTML = shop.Dept
cell3 = rowElem.insertCell(2)
cell3.innerHTML = shop.Name
cell4 = rowElem.insertCell(3)
cell4.innerHTML = shop.Amount
cell5 = rowElem.insertCell(4)
cell5.innerHTML = '<button onclick="showUpdate(this)">Update</button>'
cell6 = rowElem.insertCell(5)
cell6.innerHTML = '<button onclick="doDelete(this)">delete</button>'
}
populateTable()
Server API
from flask import Flask, jsonify, request, abort, make_response, url_for, render_template, redirect #https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates Render template takes template and returns actual values
from flask_cors import CORS
from ShoppingDAO import ShoppingDAO
#from userinput import userinput
app = Flask(__name__,
static_url_path='',
static_folder='staticpages')
CORS (app)
#app.route('/')
def hello_world():
return 'Hello World'
# curl http://127.0.0.1:5000/
#app.route('/shop')
def getAllShop():
return jsonify(ShoppingDAO.getAllShop())
# curl http://127.0.0.1:5000/shop
# find By dept
#app.route('/shop/<string:Dept>', methods =['GET'])
def findShopByDept(Dept):
return jsonify(ShoppingDAO.findShopByDept(Dept))
# curl http://127.0.0.1:5000/shop/Spud
# find By ID
##app.route('/shop/<int:ID>')
#def findShopByID(ID):
# return jsonify(ShoppingDAO.findShopByID(ID))
# curl http://127.0.0.1:5000/shop/1
#app.route('/shop/<int:ID>', methods =['GET'])
def findShopByID(ID):
foundShop = ShoppingDAO.findShopByID(ID)
return jsonify(foundShop)
# Create
#app.route('/shop', methods=['POST'])
def createShop():
if not request.json:
abort(400)
if not 'ID' in request.json:
abort(400)
Shop={
"Dept": request.json['Dept'],
"Name":request.json['Name'],
"Amount":request.json['Amount']
}
values = (Shop['Dept'], Shop['Name'], Shop['Amount'])
newId = ShoppingDAO.createShop(values)
Shop['ID'] = newId
return jsonify(Shop)
# curl -X POST -d "{\"ID\":1, \"Dept\":\"Fresh\", \"Name\":\"Test\", \"Amount\": 5}" -H Content-Type:application/json http://127.0.0.1:5000/shop
#app.route('/shop/<int:ID>', methods=['PUT'])
def updateShop(ID):
foundShop = ShoppingDAO.findShopByID(ID)
if not foundShop:
abort(404)
if not request.json:
abort(400)
reqJson = request.json
if 'Amount' in reqJson and type(reqJson['Amount']) is not int:
abort(400)
if 'Dept' in reqJson:
foundShop['Dept'] = reqJson['Dept']
if 'Name' in reqJson:
foundShop['Name'] = reqJson['Name']
if 'Amount' in reqJson:
foundShop['Amount'] = reqJson['Amount']
values = (foundShop['Dept'],foundShop['Name'],foundShop['Amount'],foundShop['ID'])
ShoppingDAO.updateShop(values)
return jsonify(foundShop)
# curl -X PUT -d "{\"Dept\":\"Monday\", \"Name\":\"Mondy\", \"Amount\": 50}" -H Content-Type:application/json http://127.0.0.1:5000/shop/3
# Delete
#app.route('/shop/<int:ID>' , methods=['DELETE'])
def deleteShop(ID):
ShoppingDAO.deleteShop(ID)
return jsonify({"done":True})
# curl -X DELETE http://127.0.0.1:5000/shop/2
if __name__ == '__main__' :
app.run(debug= True)
The value property is a string, so the test type(reqJson['Amount']) is not int is succeeding and you're reporting an error.
Convert the amount to an integer when creating the JSON:
shop.Amount = parseInt(form.querySelector('input[name="Amount"]').value)

Angular JS script throwing $http:baddata when trying to receive response from Spring Boot controller [duplicate]

I am working on an application using Angular in the frontend and J2EE in the backend , I made a form where i have to post data to be saved in the database
The problem that the post work fine but I cant get the server response after the add ,always i get this error(strangely the error comes in gray color not in red and usually)
Error: [$http:baddata]
http://errors.angularjs.org/1.6.4/$http/baddata?p0=%7B%22success%22%7D&p1=%7B%7D
at angular.min.js:6
at nc (angular.min.js:96)
at angular.min.js:97
at q (angular.min.js:7)
at xd (angular.min.js:97)
at f (angular.min.js:99)
at angular.min.js:134
at m.$digest (angular.min.js:145)
at m.$apply (angular.min.js:149)
at l (angular.min.js:102)
Here's the angular code
$scope.wflow = {
"worcode": "HELLOoo",
"wordest": "AVDOSS",
"worstatus": "ACTIF",
"worheight": 0,
"lancode": "EN",
"worlabel": "Salut monde",
"wordescription": "Salut monde",
"size": 0
};
$scope.submitForm = function () {
console.log(JSON.stringify($scope.wflow));
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: host + 'api/workflow/add',
data: $scope.wflow
}).then(function (response) {
console.log(response);
}, function (response) {
console.log(response);
});
};
And here's the Java one
#RequestMapping(value = "/add", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<String> addWorkflow(#RequestBody LWflow lworkflow){
service.addWorkflow(lworkflow);
return new ResponseEntity<String>("{\"success\"}", HttpStatus.OK);
}
this is the html part if needed
<table class="table">
<tbody>
<tr>
<td><b>Code</b></td>
<td><input type="text" name="worcode" class="form-control" ng-model="wflow.worcode"></td>
</tr>
<tr>
<td><b>Destination</b></td>
<td><input type="text" name="wordest" class="form-control" ng-model="wflow.wordest"><td>
</tr>
<tr>
<td><b>Status</b></td>
<td><input type="text" name="worstatus" class="form-control" ng-model="wflow.worstatus"></td>
</tr>
<tr>
<td><b>Height</b></td>
<td><input type="number" name="worheight" class="form-control" ng-model="wflow.worheight"><td>
</tr>
<tr>
<td><b>Langue</b></td>
<td><input type="text" name="lancode" class="form-control" ng-model="wflow.lancode"></td>
</tr>
<tr>
<td><b>Label</b></td>
<td><input type="text" name="worlabel" class="form-control" ng-model="wflow.worlabel"></td>
</tr>
<tr>
<td><b>Description</b></td>
<td><input type="text" name="wordescription" class="form-control" ng-model="wflow.wordescription"></td>
</tr>
<tr>
<td><b>Taille</b></td>
<td><input type="number" name="size" class="form-control" ng-model="wflow.size"></td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
note that the error comes from the errorCallback function
This error can be caused because response is in json string so angular trying to parse that json string to JSON.
i used transformResponse and error resolved.
$http({
url : url,
method : 'POST',
data: data,
transformResponse: [
function (data) {
return data;
}
]
})
That was a server side problem because the response was not valid to read by angular
PS: read #georgeawg's last comment
I resolved using a object class that encapusulates the error message and in the angular response i catch the right property.
Example
#RequestMapping(value = "/save", method = RequestMethod.POST, produces= MediaType.APPLICATION_JSON_VALUE)
public default ResponseEntity<S> save(#RequestBody T entidade,HttpServletRequest request){
try {
getService().save(entidade.build());
return new ResponseEntity(entidade, HttpStatus.OK);
} catch (EasyQuoteServiceException e) {
return new ResponseEntity(new Message(e.getMessage(),MessageType.ERROR), HttpStatus.BAD_REQUEST);
}
}
I have a class called Message
public class Message implements Serializable{
private static final long serialVersionUID = 904580124116256409L;
private String message;
private MessageType typeMessage;
public Message() {
super();
}
public Message(String message, MessageType typeMessage) {
super();
this.message = message;
this.typeMessage = typeMessage;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public MessageType getTypeMessage() {
return typeMessage;
}
public void setTypeMessage(MessageType typeMessage) {
this.typeMessage = typeMessage;
}
}
and in the angularjs response method
}).catch(function(error){
$scope.erromessage=error.data.message;
});
}else{
mensagem+="As senhas não parecem ser iguais;";
}
if(mensagem!=""){
$scope.erromessage = mensagem;
}
}
in this case you should return your response like this example:
#RequestMapping( value = "/add", method = RequestMethod.POST, produces="application/json" )
#ResponseBody
public String saveCustomer(#RequestPart(name = "customer") Customer customer, #RequestPart(name = "file") MultipartFile file) { return "{\"message\": \"success\"}"; }
Try This way
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: host + 'api/workflow/add',
data: angular.toJson($scope.wflow)
}).then(function (response) {
console.log(response);
}, function (response) {
console.log(response);
});

autocomplete How to avoid duplicate selection

I am using JQuery autocomplete. In which i want to avoid duplicate selection of pre-selected and pre-located (pre fetched) list.
The following script works with currently selected list. But how can I do it with pre-located list which are fetched with document onload.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
JS
$(document).on('focus','.search',function(){
let type = $(this).data('type');
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'autocomplete.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
success: function( data ) {
let selected = [],
uniques = [],
choices = [];
$('tr .search[id^="name_"]').each(function(){
let value = this.value.trim().toLowerCase();
if (value && selected.indexOf(value) < 0) {
selected.push(value);
}
});
data.forEach(item => {
let value = item.name.trim().toLowerCase();
if (uniques.indexOf(value) < 0 && selected.indexOf(value) < 0) {
choices.push({
label: item.name,
value: item.name,
data: item,
type: 'name'
});
uniques.push(value);
}
});
response(choices);
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
// Strips the 'team_' part, leaving just the number.
let id_num = $(this).attr('id').substring(5);
$(this).val(ui.item.value);
$('#id_' + id_num).val(ui.item.data.id).change();
$('#marks_' + id_num).val(ui.item.data.marks);
$(this).attr('data-type', ui.item.type);
return false;
},
appendTo: $(this).parent()
});
});
HTML
<table class="table table-bordered table-hover" id="pat_tests">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="number" id="id_1"> </td>
<td><input type="text" id="name_1" class="search" data-type="type"></td>
<td><input type="number" id="marks_1" ></td>
</tr>
<tr>
<td> <input type="number" id="id_2"> </td>
<td><input type="text" id="name_2" class="search" data-type="type"></td>
<td><input type="number" id="marks_2" ></td>
</tr>
<tr>
<td> <input type="number" id="id_3"> </td>
<td><input type="text" id="name_3" class="search" data-type="type"></td>
<td><input type="number" id="marks_3" ></td>
</tr>
</tbody>
</table>
<h2>Pre Selected List of Students</h2>
<p class="selected">Mario</p>
<p class="selected">Nico"</p>
<p class="selected">Mento</p>
PHP
if(!empty($_POST['type'])){
$type = $_POST['type'];
$name = $_POST['name_startsWith'];
$query = $db->prepare("SELECT id, name, marks FROM class where (name LIKE '".$name."%') ");
$query->execute();
$data = array();
$i = 0;
while ($row = $query->fetch(PDO:: FETCH_ASSOC)) {
$data[$i]['id'] = $row['id'];
$data[$i]['name'] = $row['name'];
$data[$i]['marks'] = $row['marks'];
++$i;
}
echo json_encode($data);
I recommend to use an array in Js, you can put preselected in it. and then use it to verify if not selected already push in it then you can add to your dom.
so in js you would have something like
var selected = [<?= !empty($selected) ? '"'.implode('","', $selected).'"' : '' ?>];
above code in firs line of script make an array of empty or already selected if selected is not empty
then you can use it to check if an item is selected or not. also it's better to use $selected = array_map('strtolower', $selected); before in php (according to your code)
EDIT
<script type="text/javascript">
//in case you have php array of already selected items. remove it if $selected is not provided in php.
//var selected = [<?= !empty($selected) ? '"'.implode('","', $selected).'"' : '' ?>];
var selected = [];
$(".selected").each(function(index, value){
selected.push($(this).text().trim().toLowerCase());
});
$(document).on('focus', '.search', function (e) {
let type = $(this).data('type');
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: 'your url',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
success: function (data) {
let uniques = [],
choices = [];
data.forEach(function (item) {
let value = item.name.trim().toLowerCase();
if (uniques.indexOf(value) < 0 && selected.indexOf(value) < 0) {
choices.push({
label: item.name,
value: item.name,
data: item,
type: 'name'
});
uniques.push(value);
}
});
response(choices);
}
});
},
autoFocus: true,
minLength: 1,
select: function (event, ui) {
// Strips the 'team_' part, leaving just the number.
let id_num = $(this).attr('id').substring(5);
$(this).val(ui.item.value);
$('#id_' + id_num).val(ui.item.data.id).change();
$('#marks_' + id_num).val(ui.item.data.marks);
$(this).attr('data-type', ui.item.type);
selected.push(ui.item.value.trim().toLowerCase());
return false;
},
appendTo: $(this).parent()
});
});
</script>
dont wory if you load js as an external file. just make sure define
<script>
var selected = [<?= !empty($selected) ? '"'.implode('","', $selected).'"' : '' ?>];
</script>
before it.
Updated answer:
Because you changed your HTML a solution could be based on:
if ($('.selected:contains(' + value + ')').length == 0) {
The updated snippet:
$(document).on('focus', '.search', function (e) {
let type = $(this).data('type');
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: 'https://api.github.com/repositories?since=364',
dataType: "json",
method: 'get',
data: {
name_startsWith: request.term,
type: type
},
success: function (data) {
data = data.map((a) => ({name: a.name || ''})).filter((e) => e.name.indexOf('_') == -1);
let selected = [],
uniques = [],
choices = [];
$('tr .search[id^="name_"]').each(function () {
let value = this.value.trim().toLowerCase();
if (value && selected.indexOf(value) < 0) {
selected.push(value);
}
});
data.forEach(function (item) {
let value = item.name.trim().toLowerCase();
if (uniques.indexOf(value) < 0 && selected.indexOf(value) < 0) {
if ($('.selected:contains(' + value + ')').length == 0) {
choices.push({
label: item.name,
value: item.name,
data: item,
type: 'name'
});
uniques.push(value);
}
}
});
response(choices);
}
});
},
autoFocus: true,
minLength: 1,
select: function (event, ui) {
// Strips the 'team_' part, leaving just the number.
let id_num = $(this).attr('id').substring(5);
$(this).val(ui.item.value);
$('#id_' + id_num).val(ui.item.data.id).change();
$('#marks_' + id_num).val(ui.item.data.marks);
$(this).attr('data-type', ui.item.type);
return false;
},
appendTo: $(this).parent()
});
});
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<table class="table table-bordered table-hover" id="pat_tests">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="number" id="id_1"> </td>
<td><input type="text" id="name_1" class="search" data-type="type"></td>
<td><input type="number" id="marks_1" ></td>
</tr>
<tr>
<td> <input type="number" id="id_2"> </td>
<td><input type="text" id="name_2" class="search" data-type="type"></td>
<td><input type="number" id="marks_2" ></td>
</tr>
<tr>
<td> <input type="number" id="id_3"> </td>
<td><input type="text" id="name_3" class="search" data-type="type"></td>
<td><input type="number" id="marks_3" ></td>
</tr>
</tbody>
</table>
<h2>Pre Selected List of Students</h2>
<p class="selected">invisible</p>
<p class="selected">tinder</p>
<p class="selected">ike</p>
Try to select tinder, just for a test.
Old answer:
First issue: you initialize the autocomplete on every focus event! Please, avoid to initialize it more times.
If I understood correctly, you want to remove from the autocomplete list elements having a value already contained in one of the Pre Selected List of Students.
If so, you can add, before the choices.push({ a test:
if ($('.selected:text[value="' + item.name + '"]').length == 0) {
Full code:
$(document).on('focus', '.search', function (e) {
let type = $(this).data('type');
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: 'your url',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
success: function (data) {
let selected = [],
uniques = [],
choices = [];
$('tr .search[id^="name_"]').each(function () {
let value = this.value.trim().toLowerCase();
if (value && selected.indexOf(value) < 0) {
selected.push(value);
}
});
data.forEach(function (item) {
let value = item.name.trim().toLowerCase();
if (uniques.indexOf(value) < 0 && selected.indexOf(value) < 0) {
if ($('.selected:text[value="' + item.name + '"]').length == 0) {
choices.push({
label: item.name,
value: item.name,
data: item,
type: 'name'
});
uniques.push(value);
}
}
});
response(choices);
}
});
},
autoFocus: true,
minLength: 1,
select: function (event, ui) {
// Strips the 'team_' part, leaving just the number.
let id_num = $(this).attr('id').substring(5);
$(this).val(ui.item.value);
$('#id_' + id_num).val(ui.item.data.id).change();
$('#marks_' + id_num).val(ui.item.data.marks);
$(this).attr('data-type', ui.item.type);
return false;
},
appendTo: $(this).parent()
});
});

How to pass the id in vue js for the post ajax request?

I need to pass an "id" obtained as data in vue js? I am getting id as "agnt.basic.actor". Since there are many id's present, how can i able to pass the same
<tr v-for="agnt in agentlist">
<td v-if="agnt.basic">{{agnt.basic.actor}}</td>
<td v-if="agnt.basic">{{agnt.basic.name}}</td>
<td v-if="agnt.basic">{{agnt.basic.email}}</td>
<td v-if="agnt.basic">{{agnt.basic.phone}}</td>
<td v-if="agnt.basic"><a v-bind:href="'/agentpendingdetails/'+agnt.basic.actor">Basic Details</a></td>
<td> <form method="POST" v-on:submit.prevent="handelSubmit();">
<div class="text-center">
<button type="submit" class="btn btn-info btn-fill btn-wd"><a v-bind:value="agnt.basic.actor"> Verify</a></button>
</div>
<div class="clearfix"></div>
</form></td>
</tr>
When I click on submit button i need to pass the id obtained from "agnt.basic.actor".
How can I able to implement the same? Please help me.
My vue js code is
<script>
dash = new Vue({
el: '#dash',
data: {
agentlist: {
basic: [],
},
authType: '{{ uid }}',
id: '',
},
mounted() {
var self = this;
data = {};
data['auth-token'] = this.authType;
$.ajax({
url: "http://alpha/admin/get/agents/pending/",
data: data,
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status == 1) {
self.agentlist = e.data
}
},
});
},
methods: {
handelSubmit: function (e) {
var vm = this;
data = {};
data['auth-token'] = this.authType;
data['uid'] = this.uid;
$.ajax({
url: 'http://127.0.0.1:8000/alpha/admin/verify/user/',
data: data,
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status) {
vm.pid = e.pid;
console.log(vm.pid);
}
else {
vm.response = e;
}
}
});
return false;
},
},
})
</script>
So, how can I able to pass the id? Please help me to obatain the result.
Instead of using form tag just use a normal button to submit the form and pass the current agnt data to submit function.
So your HTML Should be
<tr v-for="agnt in agentlist">
<td v-if="agnt.basic">{{agnt.basic.actor}}</td>
<td v-if="agnt.basic">{{agnt.basic.name}}</td>
<td v-if="agnt.basic">{{agnt.basic.email}}</td>
<td v-if="agnt.basic">{{agnt.basic.phone}}</td>
<td v-if="agnt.basic"><a :href="'/agentpendingdetails/'+agnt.basic.actor">Basic Details</a></td>
<td>
<button #click="handleSubmit(agnt)" class="btn btn-info btn-fill btn-wd">Verify</button>
</td>
</tr>
and method should be,
handleSubmit: function (agnt) {
var vm = this;
data = {};
data['auth-token'] = this.authType;
data['uid'] = this.uid;
data['agent-actor'] = agnt.basic.actor
$.ajax({
url: 'http://127.0.0.1:8000/alpha/admin/verify/user/',
data: data,
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status) {
vm.pid = e.pid;
console.log(vm.pid);
} else {
vm.response = e;
}
}
});
return false;

mootools getElements failed

i want to access a form with mootools.
My html code looks like:
<table border="0">
<tr>
<td>username</td>
<td><input type="text" id="username" value="bla "/></td>
</tr>
<tr>
<td>password</td>
<td><input type="password" id="password"/></td>
</tr>
<tr>
<td>project</td>
<td><input type="text" id="project"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" id="login" value="login"/></td>
</tr>
</table>
my JavaScript like:
window.addEvent('domready', function() {
//We are going to fill this with Mootools goodness
var jsonReq = new Request.JSON({
url: 'test.php',
method: 'post',
data: {
username: $('username').value,
password: $('password').value,
project : $('project').value
},
onSuccess: function( response )
{
if ( response.status )
{
document.location = "home.html"
}
else
{
$('response').addClass('error');
$('response').set('html', response.message);
alert( "Msg" + response.message );
}
},
// onRequest: function() { alert('Request made. Please wait...'); },
onError: function( response, err ) { alert('Faiure' + response + err); },
onFailure: function( response ) { alert('Faiure' + response); },
});
$('login').addEvent('click',function( event ){
event.stop();
jsonReq.send();
});
});
the problem is, if the value attribute is set, i can retriev this in my php script, but no changes.
so i alwayes see username=bla but no changes...
could someone help me ?
because the data object gets populated at domready state. at that time, there is no value.
you can do in the submit handler:
jsonReq.setOptions({
data: document.id('someform')
}).send();
you can pass an actual form element to data and it will serialize it for you. else, do what you did above

Categories