how can i use ajax jquery to autoreload data from selected field related data to input field? it's only working when i am using $("#id_books").change(function()! but i want to load data when browser page refresh or on page load....
create-form.html
<select name="books" class="form-control" id="id_books">
<option value="1" selected="">haxer</option>
<option value="2">django</option>
<option value="3">HCV</option>
<option value="4">python</option>
<option value="5">CBC</option>
</select>
<div class="form-group col-sm-2 text-center">
<input class="form-control" type="text" name="price" id="priceData" readonly>
</div>
<script>
$("#id_books").load(function () {
var id = $(this).val();
$.ajax({
url: `http://localhost:8000/report/${id}`,
data: { 'id': id },
dataType: 'json',
success: function (response) {
if (response != null) {
$('#priceData').val(response.price);
}
}
});
});
</script>
Try using $(document).ready(), which will fire on page load. e.g:
$(document).ready(function() {
alert("Page has loaded!");
});
You'll most likely need to refactor your code as $(this).val(); won't work (as 'this' is no longer '#id_books')
I've not tested the following (but it should give you an idea), try the following:
<script>
$(document).ready(function() {
loadData()
});
$("#id_books").change(function () {
loadData()
});
function loadData()
{
var id = $("#id_books").val();
$.ajax({
url: `http://localhost:8000/report/${id}`,
data: { 'id': id },
dataType: 'json',
success: function (response) {
if (response != null) {
$('#priceData').val(response.price);
}
}
});
}
</script>
Related
I have a datatable where I have the detail column with an edit button. When the user clicks on the edit am passing the id as a parameter. I am fetching all the values for that id and displaying in the form. Now when I edit the values and submit the form using PUT method it is getting inserted in the table, the values are passing as a parameter and it shows the empty form. How to solve this issue.
HTML:
<form class="container" id="myform" name="myform" novalidate>
<div class="form-group row">
<label for="position" class="col-sm-2 col-form-label fw-6">Position</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" required>
</div>
</div>
<div class="form-group row">
<label for="location" class="col-sm-2 col-form-label fw-6">Location</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="location" name="location" placeholder="Location" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
PUT Method Script:
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
GET method script:
<script type="text/javascript">
$(document).ready(function(){
var id_val;
var params = new window.URLSearchParams(window.location.search);
id_val = params.get('id');
console.log(id_val);
var url1=id_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
type: "GET",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
console.log(typeof(data));
$("#position").val(data.position);
$("#location").val(data.location);
},
error: function(data) {
console.log(data);
}
});
});
</script>
After submitting the form the page should remain the same with edit form values. only the edited values should be inserted. How to achieve this.
$('#myform').on('submit', function (e) {
e.preventDefault();
..........
I have checked your code in my editor. There are some changes which i made in ajax request, and it now works for me. here is the code. Try it
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
e.preventDefault();
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
method: 'POST', //or you can use GET
dataType : "json", //REMOVED CONTENT TYPE AND ASYNC
data: {send_obj:JSON.stringify(parms)}, //ADDED OBJECT FOR DATA
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
Adding prevent default in form submit handle is enough. You're handling the post request by ajax call.
e.preventDefault();
There are 2 changes in your code.
This code will prevent your page from reloading and also you are not sending the data in proper format.
$("#myform").submit(function(e) {
e.preventDefault(); // 1. Dont reload the page
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: parms, // 2. Just send the parms object bcoz you already defined the dataType as json so it will automatically convert it into string.
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
I'm not able to access skills value using id while I can access finduserType value.
I don't know why, It should call on change event and click event as well.
$(function() {
$("#findUserType").change(function () {
var user_type = $("#findUserType").val();
var skills = $("#skills").val();
var phone = $("#phones").val();
var src = '{{Request::root()}}/api/user/suggestion/email';
var srcPhone = '{{Request::root()}}/api/user/suggestion/phone';
/* var skills = $("#skills").val();
var phone = $("#phones").val();*/
// Load the Users from the server, passing the usertype as an extra param
$("#skills").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
method: 'GET',
dataType: "json",
data: {
term : skills,
user_type : user_type
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
// Load the Users from phone to the server, passing the usertype as an extra param
$("#phones").autocomplete({
source: function(request, response) {
$.ajax({
url: srcPhone,
dataType: "json",
data: {
term : phone,
user_type : user_type
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
});
<form>
<div class="input-group">
<select class="form-control" id="findUserType" name="finduser">
<option value="">--Select--</option>
<option value="2">D</option>
<option value="3">P</option>
</select>
</div>
<div class="input-group">
<input type="text" id="skills" class="form-control">
<input type="text" id="phones" class="form-control" name="phone">
</div>
</form>
Updated the code please take a look what exactly i'm going to stuck it does not take email's values. When I call ajax change event does work fine but skills value does not have the any value. Also suggest how can i compress this code. I just want to check on change event call ajax base on skills and phone values.
I think this will work better:
$("#findUserType").change(function() {
if ($(this).val() == "") {
$("#textboxes").hide();
} else {
$("#textboxes").show();
}
});
$("#skills").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
method: 'GET',
dataType: "json",
data: {
term: $("#skills").val(),
user_type: $("#findUserType").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
// Load the Users from phone to the server, passing the usertype as an extra param
$("#phones").autocomplete({
source: function(request, response) {
$.ajax({
url: srcPhone,
dataType: "json",
data: {
term: $("#phones").val(),
user_type: $("#findUserType").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select class="form-control" id="findUserType" name="finduser">
<option value="">--Select--</option>
<option value="2">Doctor</option>
<option value="3">Pharmacy</option>
</select>
<br/>
<div id="textboxes" hidden>
<input type="text" id="skills" class="form-control">
<br/>
<input type="text" id="phones" class="form-control" name="phone">
</div>
</form>
At present your two later autocomplete handlers are not bound until the "findUserType"'s "change" event has happened at least once, because they are declared within that code block. And also if that "change" event happens multiple times then multiple handlers will be attached to the other two elements, and then when those events are triggered, multiple copies of the code will run - I doubt that's what you intended.
The change handler for #skills and the click handler for #phone will only be registered after the first change event firing on #findUserType.
Move those two handlers outside of #findUserType's change handler.
$(document).ready(function(){
$("#findUserType").change(function () {
var user_type = $(this).val();
});
$("#skills").change(function () {
var skills = $(this).val();
var phone = $("#phones").val();
});
$("#phone").change(function () {
var phone = $(this).val();
});
});
I hope you this will help you get the values of skills and phone when user type is selected.
I tried to receive Ajax response but the response is null.
My HTML Looks like this
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<select class="form-control" class="form-control" id="choose_country">
<option value="">Select a prefered language</option>
<option value="en">EN</option>
<option value="fr">FR</option>
<option value="de">DE</option>
<option value="nl">NL</option>
</select>
</form>
<div id="table_load"></div> <!-- loads search table -->
My Javascript looks like this
<script>
$('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');
$("#choose_country").change(function(){
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url(); ?>admin/manage_article/search",
type: "post",
data: {choose_country: choose_country},
dataType: 'json',
async: false,
success: function (response) {
if(response.success == true){
alert('success');
$('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');
}else{
alert('fail');
}
},
});
});
</script>
My controller looks like this
public function search(){
$choose_language = $this->input->post('choose_country');
$this->load->view('admin/manage_article/search');
}
}
I want to pass the value of select box to the controller and return back the selected value in the page $this->load->view('admin/manage_article/search');
I have tried the above code but the response alerts "fail".
I am new to ajax so pardon me if there are any mistakes in coding.
Try this, in your controller
public function search() {
$choose_language = $this->input->post('choose_country');
$result = ($choose_language) ? true : false;
$this->output->set_content_type('application/json')->set_output(json_encode(array('choose_country' => $choose_language, 'result' => $result)));
}
your jquery will be as below
<script type="text/javascript">
$(document).ready(function() {
$("#choose_country").change(function() {
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url(); ?>admin/manage_article/search",
type: "post",
data: {
choose_country: choose_country
},
dataType: 'json',
async: false,
success: function(response) {
if (response.result) {
alert('success');
$('#table_load').html(response.choose_country);
} else {
alert('fail');
}
},
});
});
});
</script>
I dont know why you are using the ajax, you might have business logic in controller, which you have not shown. If not then you can simply load the value of choose_country in table_load, as below.
<script type="text/javascript">
$(document).ready(function() {
$("#choose_country").change(function() {
var choose_country = $("#choose_country").val();
$('#table_load').text(choose_country);
});
});
</script>
There is no reason to make two calls to the server - once for the ajax call and then again to load html.
To return and load html into the browser via AJAX do this in your javascript.
$("#choose_country").change(function () {
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url('admin/manage_article/search'); ?>",
type: "post",
data: {choose_country: choose_country},
dataType: 'html',
// Forcing synchronous strongly discouraged,
// as it can cause the browser to become unresponsive.
//async: false,
success: function (response) {
$('#table_load').html(response);
},
error: function(xhr, textStatus, errorThrown){
console.log(textStatus, errorThrown);
}
});
});
Your controller will work the way you show it in the question except I don't see where the posted var is used, so you may not receive the language specific html what you want (If that is what you're trying to do).
If you really feel the need to have the return contain a property called result that you can check using if (response.result) {... then you will need a variation on parth's answer to your question. You can add the html to the returned json with this in your controller.
public function search()
{
//What do you do with this?
//You don't show how this is used so I'm mostly going to ignore it.
$choose_language = $this->input->post('choose_country');
$result = !empty($choose_language) ? true : false;
///get the view file as a string of html markup
$html = $this->load->view('admin/manage_article/search', NULL, TRUE);
$out = array('result' => $result, 'html' => $html);
$this->output
->set_content_type('application/json')
->set_status_header('200')
->set_output(json_encode($out));
}
Then your success function would be like this
success: function(response) {
if (response.result === true) {
alert('success');
$('#table_load').html(response.html);
} else {
alert('fail');
I know that there was a similar questions to this, but I tried everything and nothing seems to work. I'm not that good with ajax thats why i posted this question.
$("#buttons_holder").find("#add_users").click(function() {
var ob = document.getElementById('all_users[]');
var selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[i].selected) {
selected.push(ob.options[i].value);
}// if
}// for
var selected_users = selected;
var link = $("#buttons_holder").find("#add_users").attr('href');
$.ajax({
url: link,
type: 'POST',
data: {
s : selected_users
},
'success': function(data){
alert ('succes');
},
'error' : function(data) {
alert ('fail');
}
});
});
And I always get fail alerted. I try to alert all parametes(selected_users, link) before function and everything seems ok. Can anyone tell me what could be a problem? Thanks you all very much for your answers.
EDIT: Here's my HTML Code:
<div class="main_content">
<div id="users_holder">
<div class="div_grids">
<div class="inline_wrapper">
<h4>Users that belong to selected company:</h4>
<label for="company_users">
<select multiple="" name="company_users[]" id="company_users[]">
<option value="1">admin#sms.com</option>
<option value="3">b#bba.com</option>
<option value="5">dfsdf#dmfkdmf.com</option>
</select>
</label>
</div>
<div style="margin-top:2%; margin-left:5%; margin-right:5%" id="buttons_holder" class="inline_wrapper">
<div class="common_add_button">
<a id="remove_users" name="remove_users" href="http://localhost/cake/crawler/companies/1/manage-agents/remove"> >> </a>
</div>
<div class="common_add_button">
<a id="add_users" name="add_users" href="http://localhost/cake/crawler/companies/1/manage-agents/add"> << </a>
</div>
</div>
<div class="inline_wrapper">
<h4>All users:</h4>
<label for="all_users">
<select multiple="" name="all_users[]" id="all_users[]">
<option value="4">11111#qweqwe.com</option>
</select>
</label>
</div>
</div>
SOLUTION:
$("#buttons_holder").find("#add_users").click(function() {
var selected_users = $('#all_users option:selected').map(function() {
return this.value
}).get();
var link = '{$add_users_link}';
$.ajax({
url: link,
type: 'POST',
data: {
'new_users' : selected_users
},
'success': function(data) {
App.Messages.showOkFlashMessage(data);
},
'error': function(data) {
App.Messages.showErrorFlashMessage(data.responseText);
}
});
return false;
});
When I use Ajax and arrays, I always pass the data as string and deserialize on the server.
Since the parameters seem to be ok to you, maybe you can try this:
$.ajax({
url: link,
type: 'POST',
data: { s : JSON.stringify(selected_users) },
'success': function(data) { alert ('success'); },
'error': function(data) { alert ('fail'); }
});
#Marko Vasic Ajax require Json format data so you have to send data in json format like
JSON.stringify({ s: selected_users })
var selected_users = selected;
var link = $("#buttons_holder").find("#add_users").attr('href');
$.ajax({
url: link,
type: 'POST',
data:
JSON.stringify({ s: selected_users }),
'success': function(data){
alert ('succes');
},
'error' : function(data) {
alert ('fail');
}
});
});
I am trying to pull text from another page (ajaxuseradd.psp) which is in JSON format. I am then trying to insert this text into several text boxes and/or select lists. For right now, I am merely trying to do the text boxes.
Here's my code, a good deal of which was given to me, because I am not all that familiar with jQuery:
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript">
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$.each(data, function(key, value) {
$('#' + key).val(value);
});
},
dataType: 'json'
})
});
</script>
<form action="adduser.psp" method="get">
<fieldset>
<label for="uname">Username:</label>
<select name="uname" id="useruname" onchange="updateAdduser();">
<%
Random Python Code That Isn't Important But Generates Option Values
%>
<%= options %>
</select>
</fieldset>
<fieldset>
<label for="fname">First Name:</label>
<input type="text" name="fname" />
</fieldset>
<fieldset>
<label for="lname">Last Name:</label>
<input type="text" name="lname" />
</fieldset>
<fieldset>
<label for="email">Email:</label>
<input type="text" name="email">
</fieldset>
Output from ajaxuser.psp should be as follows, or some variation thereof. This will be displayed on the page ajaxuser.psp when the argument ?uname=neverland is used, for example:
{"fname" : Neverland, "lname" : Conference Room, "email" : nobody#mediaG.com, "deptid" : deptid, "active" : active, "sentient" : sentient}
So my code should look like this?
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$("#fname").val(data.fname);
});
},
dataType: 'json'
})
});
});
</script>
EDIT: This is still not working - I select a drop down value, and NO CHANGE for any of the fields.
The first thing I see is that you need to wrap the onchange handler in this:
$(document).ready(function () {
});
So it looks like this:
$(document).ready(function () {
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$.each(data, function(key, value) {
$('#' + key).val(value);
});
},
dataType: 'json'
})
});
});
Also, this:
$.each(data, function(key, value) {
$('#' + key).val(value);
});
Is not going to work like you think. You get back ONE object with the properties, so more like this:
success: function(data, status, xhr) {
$("#fname").val(data.fname);
....
},