how to use Ajax in this code? - ajax

</tr>
<tr>
<td><input type="radio" name="ans" id='ans_2' value="2" /> <? echo " "; echo $ans2 = $ques['ans_2'];?></td>
</tr>
<tr></tr>
<tr>
<td><input type="radio" name="ans" id='ans_3' value="3" /> <? echo " "; echo $ans3 = $ques['ans_3'];?></td>
</tr>
<tr></tr>
<tr>
<td><input type="radio" name="ans" id='ans_4' value="4" /> <? echo " "; echo $ans4 = $ques['ans_4'];?></td>
</tr>
hello everyone i am creating online MSQ's website and i need your help in this code
when user click on the radio button the given answer will store in db how can i do this?

Firstly, I strongly suggest you use a JS Framework like jQuery to do it. This is how you would do this in jQuery:
$('input.radio').click(function() {
$.ajax({
url: 'script.php?answer=' + $(this).attr('value'),
success: function(data) {
// this is the server response
}
});
});
Of course your script.php file should manage the DB connection and everything else. You may need to add extra parameters but this is a general solution that you can use in cases similar to this one.
EDIT
I used the 'input.radio' selector since you didn't add any specific class to the radio buttons, of course this will apply that click function to every radio button on the page. You may need to add a more specific selector (like a class selector) to affect only the correct buttons

$('input.radio[name='ans']).click(function() {
$.ajax({
url: 'script.php?answer=' + this.value,
success: function(data) {
// this is the server response
}
});
});
Pretty much the same as above. Except you can spercify this group of inputs by name:
$('input.radio[name='ans']).click // binds the ajax function to the click event
And you can just use this.value instead of:
$(this).attr('value')
I would recommend using jQuery also

Related

when hit enter go to next element vuejs2

i have function on click vuejs2
this is the function
#change='units(chosed_item.id,$event)'
and this is the code for this function to send the id and put result inside array
units:function(item_id,$event){
var unit_id = event.target.value;
$.ajax({
type:'POST',
url: path+'unit_search',
data: {unit_id,item_id},
success:(data) => {
this.voucher_items.push({
id:data['id'],
item_desc_ar:data['item_desc_ar'],
item_unit_name:data['item_unit_name'],
item_smallest_unit_cost:data['item_smallest_unit_cost'],
item_smallest_unit:data['item_smallest_unit'],
item_smallest_unit_selling_price:data['item_smallest_unit_selling_price'],
item_discount_value:data['item_discount_value'],
item_tax_value:data['item_tax_value'],
});
this.chosed_items = [];
}
});
},
and i loop the voucher_items in loop
like this
<tr v-for="voucher_item , key in voucher_items">
<td>
<input name='items_quantity_coast[]' type='text' class='form-control' />
</td>
<td>
<input type='number' name='items_quantity_quantity[]' min='1' class='form-control' v-model='voucher_item.quantity' required />
</td>
<td>
<input type='number' name='items_quantity_discount[]' min='1' class='form-control' v-model='voucher_item.item_discount_value_input' min='1' max=''/>
</td>
</tr>
how can i make the input focus go to last input in voucher_items like when i click unit function do the code above and focus the input in
<input type='number' name='items_quantity_discount[]' min='1' class='form-control' v-model='voucher_item.item_discount_value_input' min='1' max=''/>
thanks
You can use a custom directive ..
In your component, add a directives option ..
directives: {
focus: {
inserted(el) {
el.focus()
}
}
}
Use your new v-focusdirective to focus on the desired element ..
This will focus on the last input on your last row. If you want finer control on which element to focus you can create a custom directive and use it on an upper level element (the table element for example), then use normal DOM traversing techniques(firtElementChild, lastElementChild et al.) to target specific elements. The process will be the same.

VueJs and Laravel - multiple select fields

Using Laravel 5.4 and Vuejs 2.1
In code I have a select field with two input fields (quantity and stock) in tr (Table Row). Table Row with the fields can be dynamically added as much as user is needed, this is the code:
<tbody id="loads-content">
<tr v-for="(item, index) in items">
<td>
<select v-model="item.load_id" name="load_id[]" class="loads" v-on:change="getLoadStock()">
<option v-for="load in loads" :value="load.id" :id="load.id">{{load.name}}</option>
</select>
</td>
<td><input type="text" v-model="item.quantity" name="quantity[]" class="input is-hovered qty"></td>
<td><input type="text" v-model="item.stock" class="input is-hovered stock" disabled readonly="true"></td>
<td>
<button type="button" class="button is-danger remove" #click="items.splice(index, 1)"><i class="fa fa-minus-square-o" aria-hidden="true"></i></button>
</td>
</tr>
<a #click="addLine" class="button is-success"><i class="fa fa-plus-square-o" aria-hidden="true"></i></a>
</tbody>
When you choose some value from select field I need to populate the STOCK input field with stock data from the database. For that I used an API call. I made something like this:
methods: {
addLine() {
this.items.push({
load_id: '',
quantity: '',
stock: ''
})
},
getLoadStock(){
var loadsContent = $('#loads-content');
var tr = loadsContent.parent().parent();
var id = tr.find('.loads').val();
axios.get('/api/load/' + id)
.then(function(response) {
tr.find('.stock').val(response.data.stock);
})
.catch(function(error) {
console.log(error)
});
},
This code is not working as expected.
The goal is to fetch actual stock for current choosen load, to see how much quantity can you enter in the input field for quantity.
I am open for any suggestions, if anyone has a better approach and solution please help.
Thanks in advance! :)
You are mixing two different and incompatible ways of building a web app: Vue.js and jQuery.
When using Vue, you should not be manipulating the DOM directly. You should instead be binding the DOM elements to Vue model attributes. Then, if you need a DOM element to reflect a change, you change the model – not the DOM.
So for instance, you would want something like this (note adding index as an argument to getLoadStock):
<select v-model="item.load_id" name="load_id[]" class="loads" v-on:change="getLoadStock(index)">
<option v-for="load in loads" :value="load.id" :id="load.id">{{load.name}}</option>
</select>
and
getLoadStock(index){
axios.get('/api/load/' + this.items[index].load_id)
.then(function(response) {
this.items[index].stock = response.data.stock;
})
.catch(function(error) {
console.log(error)
});
},

WebMatrix AJAX INSERT not working

i'm trying to add an entry into my database and update a table i have created using AJAX. I think i'm halfway there, i can send my form contents to the "partial" page, but thats where it gets stuck?
Here's my content page:
#{
Layout = "~/_SiteLayout.cshtml";
WebSecurity.RequireAuthenticatedUser();
var db = Database.Open("StayInFlorida");
var rPropertyId = Request.QueryString["PropertyID"];
var Roominfo = "SELECT * FROM RoomInfo WHERE PropertyID=#0";
var qRoominfo = db.Query(Roominfo, rPropertyId);
}
<h2>Current Rooms</h2>
<table id="room-table" class="table table-bordered">
<tr>
<th>Room Name</th>
<th>Room Type</th>
<th>Room Description</th>
</tr>
#foreach(var row in qRoominfo){
<tr>
<td>#row.RoomName</td>
<td>#row.RoomType</td>
<td>#row.RoomDescription</td>
</tr>
}
</table>
<form id="add-room-form" action="#Href("~/Partials/AddRoom")">
<div class="row">
<span class="label"><label for="title">Room Name:</label></span>
<input type="text" name="roomname" id="roomname" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Type:</label></span>
<input type="text" name="roomtype" id="roomtype" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Description:</label></span>
<input type="text" name="roomdescription" id="roomdescription" size="50" />
</div>
<input type="hidden" name="propertyid" value="#rPropertyId" />
<button class="btn btn-success" id="submitbutton">Submit</button>
</form>
<script type="text/javascript">
$(function(){
$('#submitbutton').click(function(){
$.ajax({
type: "POST",
url: "/Partials/AddRoom",
data: $("#add-room-form").serialize(),
dataType: "text/plain",
success: function (data) {
$('#room-table').html(data);
}
return false;
});
});
});
</script>
and here is the partial page which "should" insert the data into the database:
#{
var db = Database.Open("StayInFlorida");
var sql = "INSERT INTO RoomInfo (PropertyID, RoomName, RoomType, RoomDescription, LastModified) " +
"VALUES (#0, #1, #2, #3, GetDate())";
var propertyid = Request["propertyid"];
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
db.Execute(sql, propertyid, roomname, roomtype, roomdescription);
}
In theory, it should write the info to the database, and then refresh my table, so im guessing something isn't quite right with the javascript?
You cannot sent the data through an ajax call is because you cannot even start the request. You are using the function to trigger when a click is made. But there will be no click event.
Reason: There is no button with the ID for click event. See Click trigger issue section below.
Tip: To check whether there is any Request to the server or not, you should make use of this. In every browser when you press F12 you get Developer Tools opened. Make sure you are on network tab. You will be able to check any network request made to server through there. Ajax requests are also saved there as a log, there status and everything is present there. That will be a basic but a powerfull tool to help you out in understanding how Ajax requests are made.
There are certain issues in your code too.
Issue in the HTML: There is an error in your code, look at the submit button. Its having code as:
<button class="btn btn-success" type="submit" value="Submit"/>Submit</button>
Which should be:
<button class="btn btn-success" type="submit" value="Submit">Submit</button>
And then, I should change that too the following because the type="submit" will submit the form instead of creating an ajax request. I used your page in my website and just replaced the DataBase objects and replaced them with simple Response like Response.Write() and wrote the variables that I caught:
<button class="btn btn-success" id="submitbutton">Submit</button>
So the code that I changed the above one to is like this:
#{
if(IsPost){
var propertyid = "1";
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
var lastmodified = DateTime.Now;
// here you will write the data to database using Database.Execute
// Remember you should write the ajax response
// here as a result of Response.Write()
// However if you still want to load that page, its OK!
}
}
As mentioned earlier, you were write the propertyid as "'1'" I changed that to "1". But in case you want to execute as "'1'" its ok too.
Click trigger issue:
There were some other issues too. You were using:
$('#submitbutton').click(function(){
But there was no button with the ID submitbutton. So I changed the id of the button you were using there.
What I changed in your code:
What change I made in your code was I changed the POST request to GET. To have a look at what variables are being sent to server and what results I get. I had it easier to make use of this code as GET request was easily able to check then POST request.
If you still want to use POST request you should try to serialize() the form as JSON and send it to server. But GET will be easy.
Then I gave another field to the $.ajax section as:
data: 'roomname=' + $('#roomname').val() +
'roomtype=' + $('#roomtype').val() +
'roomdescription=' + $('#roomdescription').val(),
This will create a string of the data to be sent. And then it will be caught on that page. And I removed if(IsPost) too. I was able to get the result of the Response. So what you can do is to change the Response of the request and write is as:
$("#room-table").html(response);
And the table will be changed! This will remove the previous data in the table Or even whole of the table and update it with the data recieved from the Response. And then I was able to send the request to server, process the QueryString and then write a response and then using $('#idofelement').html(response) I wrote it in the specific area. You can try it as I did.
The full code that I used was:
One the main page I had this code:
#{
Layout = "~/_SiteLayout.cshtml";
}
<h2>Current Rooms</h2>
<div class="row">
<span class="label"><label for="title">Room Name:</label></span>
<input type="text" name="roomname" id="roomname" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Type:</label></span>
<input type="text" name="roomtype" id="roomtype" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Description:</label></span>
<input type="text" name="roomdescription" id="roomdescription" size="50" />
</div>
<button class="btn btn-success" id="submitbutton" value="Submit" >Submit</button>
<script type="text/javascript">
$(function(){
$('#submitbutton').click(function(){
$.ajax({
url: '/Partials',
data: 'roomname=' + $('#roomname').val() + 'roomtype=' +
$('#roomtype').val() + "roomdescription=" +
$('#roomdescription').val(),
dataType: 'text',
contentType: 'text/html',
success: function(response) {
$("#body").html(response);
},
error: function(data){
alert('Something went wrong');
}
});
});
});
</script>
I changed the page to partials only and used it. Here is the content for that page.
#{
var propertyid = "1";
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
var lastmodified = DateTime.Now;
Response.Write("Room name: " + roomname + "<br>Room Type: "
+ roomtype + "<br>Room Description: " + roomdescription +
"<br>Property: " + propertyid);
}
Now its upto you to use the Database variables here. Where I used Response.Write and other codes You can use the Database methods. And also you can add WebSecurity method.
The Database.Execute method requires the SQL to be executed to be passed in first. You don't appear to be passing it in at all. Also, I assume that PropertyId is an integer? If so, you should not surround it in quotes. In fact, you should try delimiting values that will be passed in via parameter at all. That's one of the benefits of using parameters. Try this:
#{
if(IsPost){
var db = Database.Open("StayInFlorida");
var sql = "INSERT INTO RoomInfo (PropertyID, RoomName, RoomType, RoomDescription, LastModified) " +
"VALUES (#0, #1, #2, #3, GetDate())";
var propertyid = 1;
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
db.Execute(sql, propertyid, roomname, roomtype, roomdescription);
}
}
You are hardcoding the Properytid at the moment. If you want that to be dynamic, add a hidden field to your AJAX form and set the value to rPropertyId:
<input type="hidden" name="propertyId" value="#rPropertyId" />
Then you can alter the 4th line in the snippet above:
var propertyId = Request["propertyId"];

Can I access the same controller multiple times in one view without changing the view?

I am using Spring MVC. I have a view that dynamically populates 2 dropdown lists based on queries called from the controller. I want to dynamically run a query based on the first dropdown selection to change the second dropdown, which means access the controller again (I think). Can I access the controller multiple times from the same view without changing the view? So for example, say starting out the first dropdown was a list of US States and the second started out as a list of all US cities, if I selected NC from the first list I would want to change the second list to include only NC cities.
Here is an example of the first dropdown:
<select name = "states" onChange = "populateCityList(this.options[this.selectedIndex].value)">
<option value ="*">All States</option>
<c:forEach items="${states}" var ="state">
<option value ="${state}">${state}</option>
Pretty straightforward, but I don't really know where to go from there. I have it calling a Javascript function within the current view right now, but I don't know if that is correct or what to even do within that function.
The magic word is AJAX.
Your JavaScript function needs to make an AJAX request to your controller, which should ideally return a JSON data structure containing the values for the second drop down. Your JS function should then have a callback that catches the JSON from your controller and populates the drop down HTML by manipulating the DOM. JQuery is the way to go. There are lots of examples on the web, just search for it.
Hi #user2033734 you can do something like this:
JQuery code
$(document).ready(function() {
$("#id1").change(function () {
position = $(this).attr("name");
val = $(this).val()
if((position == 'id1') && (val == 0)) {
$("#id2").html('<option value="0" selected="selected">Select...</option>')
} else {
$("#id2").html('<option selected="selected" value="0">Loading...</option>')
var id = $("#id1").find(':selected').val()
$("#id2").load('controllerMethod?yourVariable=' + id, function(response, status, xhr) {
if(status == "error") {
alert("No can getting Data. \nPlease, Try to late");
}
})
}
})
})
And JSP within
<table style="width: 100%;">
<tr>
<td width="40%"><form:label path="">Data 1: </form:label></td>
<td width="60%">
<form:select path="" cssClass="" id="id1">
<form:option value="" label="Select..." />
<form:options items="${yourList1FromController}" itemValue="id1" itemLabel="nameLabel1" />
</form:select>
</td>
</tr>
<tr>
<td width="40%"><form:label path="">Data 2: </form:label></td>
<td width="60%">
<form:select path="" cssClass="" id="id2">
<form:option value="" label="Select..." />
<form:options items="${yourList2FromController}" itemValue="id2" itemLabel="nameLabel2" />
</form:select>
</td>
</tr>
</table>
I hope help you :)
One solution would be to move some of the data gathering out into a service, so your main controller could use the service to gather the data before sending to the view.

ajax gif loader

can you tell me where and how to put an ajx loading.gif?
my html code is below
<div class="searchbox">
<input id="Search" onkeyup="searchKeyUp(event)
" name="Search" class="searchtextbox"/>
</div>
</td>
<td width="57"><br> <img onclick="search(); return false;" style=" cursor:pointer" eight="30" onmouseover="this.src='images/j3.jpg'" type="image" src="images/j1.jpg" onmouseout="this.src='images/s1.jpg';" alt="" width="57" ></td>
</tr>
</table>
<div>
<table cellspacing="0" cellpadding="0" border="0">
<tr valign="left">
<td><div class="resultCss" content="tableId" id='resultDiv'>
</div></td>
</tr>
</table>
Before your AJAX request starts , display the ajax_load.gif and after it ends, remove it.
Tip: Make sure you have only 1 AJAX request sent to your server at a time like https://www.buxfer.com
build in on the position you want to have it and give display:none on it. In search() before AJAX Call edit the display:none to block and hide the image onSuccess off the AJAX function again.
You need to place gif file to any proper place and set "display:none;"
You can use my function based on jQuery. It automatically shows or hide the spinner on every ajax call.
function simpleAjax(pageUrl , divId , spinnerId , formId , isFormEnabled)
{
var dataVar ='';
var d = new Date();
if(isFormEnabled)
dataVar = $('#'+formId).serialize();
$.ajax(
{
type: 'GET',
url: pageUrl,
cache:false,
data:dataVar,
success: function(response){ $('#'+divId).html(response); $('#'+spinnerId).hide(); },
beforeSend: function(){ $('#'+spinnerId).show();},
error: function(m){ alert(m); },
complete: function(){}
});
}

Resources