JavaScript failing after second ajax request using submit/selection button - javascript

I'm guessing this error has to do with asynchronous programming, but I can't seem to wrap my head around it after looking at various examples on here...
I have a basic form that should do a post request and then it produces a d3 graph based on the form selection value...
<form id="target" method="post">
<select name="len" id="len">
<option value="sel">--Select--</option>
<option value="year">Most Recent Year</option>
<option value="all">All Data</option>
</select>
<input type = "submit"class="btn" value="Submit"/>
</form>
$(document).ready(function(){
$('.btn').on('click',function(){
var myvar = $('select[name=len]').val();
$.ajax({
url: 'dbquery_o2_select.php',
type: 'POST',
data: {'var':myvar},
dataType: "JSON",
success: function (result){
// produce a d3 graph here
},
error: function(jqXHR,textStatus){
alert(textStatus);
}
});
return false; });
});
Upon the second "submit", I get an error saying that 'sampledate' (which is an associated name in the ajax return array named 'result') is undefined.
Thanks in advance for any help. Let me know if you need more info!

Related

How can I load a list of object into select tag with Ajax through API Controller?

I have a list of options inside a 'select' tag. For whichever option is selected, an 'onchange' function will be activated which carries on the value of that option. A function which activated will use Ajax to call to a controller to get a list of data that I can store into my others 'select' tag. How can I achieve this?
My HTML:
<select id="category-select" onchange="GetEmployee()">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
My JS:
function GetEmployee() {
var MaNguoiDung = 120;
var MaThuMuc = document.getElementById("category-select").value;
$('#employeeDisplay').change(function () {
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien?MaNguoiDung=" + MaNguoiDung + "&MaThuMuc=" + MaThuMuc,
success: function () {
alert('Get Success');
}
});
});
}
The alert was only to test if my ajax can run or not. Apparently, it can't. Also, I need to know how to stored query data into the second 'select'. Like after the URL attribute, I don't know what to write next after that. Sorry but I'm completely new in Ajax. Some referencing and tutorial online mostly shown how to load ajax into the table. There might be more but table is the only thing I can find so I'm very in need of a way to store it into select.
Edit: This is the response data I receive from my Controller
Sample JSON
You have several problems with the code shown.
The <select> you have the onchange in is not the same one you target to get value inside the function.
You are creating a new change event inside the function called by onchange. That new jQuery change() won't fire until next time you edit the <select>
You are manually creating the url query string but also providing a data object. Internally jQuery takes that object and will add it to the query string you manually created, effectively duplicating the parameters
So, lets get rid of the onchange , give the <select> an id and fix the query string in the ajax. Also you want an error handler to help troubleshooting
As for how to handle the response will need to see a sample of it first
HTML
<select id="category-select">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
JS
$(function () {
$('#category-select').change(function () {
var category = this.value;
// I don't know which variable is which in `data`
var MaNguoiDung = 120;// is this category ???
var MaThuMuc = null // confused where this comes from because other select is empty
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien",
success: function (response) {
// ^^ missing argument needed to receive the data
console.log(response)// log it to console for now
alert('Get Success');
},
error: function(xhr, status, message){
console.log('Status: ', status, ', Message: ', message)
}
});
});
});

How to auto select "select" option in html input after ajax request?

I have an AJAX request going to my PHP file to pull data from the database that pertains to the users. I want to autofill the form inputs. I was able to fill most of the inputs, but the HTML "select" option is really stumping me. Does anyone know how to autoselect the value in the database?
HTML
<select class="gender-reg" name="gender-reg">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="optout">Rather Not Say</option>
</select>
AJAX REQUEST
$(function () {
$.ajax({
type: 'GET',
url: 'http://localhost:8090/HELPERSITE/src/php/session.php',
dataType: 'json',
data: '',
success: function (response) {
console.log(response);
$(".username-reg").attr("value", (response['username']));
$(".pwd-reg").attr("value", (response['password']));
$(".email-reg").attr("value", (response['email']));
$(".acct-type").text(response['type']);
$(".fname-reg").attr("value", (response['fname']));
$(".lname-reg").attr("value", (response['lname']));
$(".gender-reg").attr("value", (response['gender']));
$(".street-reg").attr("value", (response['street']));
}
})
});
You can simply use .val():
$(".gender-reg").val(response['gender']);

update value after Ajax call PHP

I want to update TextBox value on basis of selectChange
HTML:
<select name="abc" id="def">
<option value="1">1st Record</option>
<option value="2">2nd Record</option>
<option value="3">3rd Record</option>
</select>
<input value="" name="final_value" id="final_value" />
JS:
$("#selectboxid").change(function() {
$.ajax({ url: "test.php", data:"value="+$("#def").val() , success: function(){
$("#final_value").val(data);
}});
});
PHP:
<?php
function abc($data){
// Database operations
echo json_encode($response);
}
abc($_GET);
?>
With this approach value is updating very nicely But i have below points:
above approach prints values and one can see in Network Tab. Is it a nice way to do it?
I also tried using return $response in PHP function but then response is null and console.log(data) in ajax shows null array.
So, how to update Input value after Ajax without echoing. I do not want that user shall see any type of response even in Network Tab.
I have seen various websites which does the same and not showing any values in Network tab.
** Is there any different approach to do this?
You can alternatively try like this
All HTTP requests can possible to watch on their own network. You can restrict this
$(document).ready(function(){
var params = {};
params['value'] = $("#def").val();
$.post('test.php', params, function(response){
console.log(response);
alert(response);
});
});
I've not tested this, but immediatly I've spotted a couple of things:
$("#selectboxid").change(function() {
// .val is a function
$.ajax({ url: "test.php", data:"value"+$("def").val() , success: function(data) { //Your success callback needs to take an argument
//data will be either a string or a JSON object, so depending on what you want from it, you'll probably not be able to just pass it to the val() function
$("#final_value").val(data);
}});
});
Not 100% complete I'm sure, but hopefully will give you a good starting point
It should be like this
$("#selectboxid").change(function() {
$.ajax({
url: "test.php",
data:{
"value": $("def").val()
},
success: function(){
$("#final_value").val(data);
}
});
});

codeigniter call a view / controller on ajax call sucess

I am new to codeigniter , I am trying to call a controller on AJAX call sucess...
I tried to search stackoverflow but i didn't get what i needed..
Form in my view
<form onsubmit="categorysearch()" method="GET">
<label for="username">Category : </label>
<select id="category" name="category">
<option value="android">android</option>
<option value="iphone">iphone</option>
<option value="windowsphone">windowsphone</option>
<option value="blackberry">blackberry</option>
</select>
<input type="submit" name="searchkeywordsubmit" title="Search" id="searchkeywordsubmit" />
</form>
When the form is submitted the below java script is executed.
JavaScript in my View
function categorysearch()
{
var categorykeyword = document.getElementById("category").value;
alert("Category keyword is " + categorykeyword);
$.ajax({
type: "GET",
async: false,
//dataType: "json",
url: "http://localhost/2009074/index.php/rest/resource/categorysearch/category/" + categorykeyword + "",
success: function(data)
{
alert("Returned data is " + data);
// i want to call the constructor here with the returned data
//$("body").html(data);
//$('body').append(output_string);
},
error: function(data)
{
alert("error is " + data);
}
});
}
AJAX call works successfully , I can see the returned data in the alert (Returned data is JSON encoded)
Now i want to call another controller with the recieved data ...
Please help me to figure this out
you just need to redirect the control the required controller :
success: function(data)
{
window.location.href="http://localhost/my_project_name/my_controller_name";// you just need to add this event on success call.
},
A really dirty way to do it is save the JSON object as session variable and navigate to a page or reload the page and in the constructor of the page, check for the session variable and use the variable.
well that's the only way I can think of at the moment.

jQuery ajax "data" field with mixed data

I have a form with some fields in it:
<form id="unit">
<input type="hidden" name="item_id" value="100" />
<input type="hidden" name="name" value="item one" />
<select name="option[1]">
<option value="1">1GB</option>
<option value="2">8GB</option>
</select>
<select name="option[2]">
<option value="3">Red</option>
<option value="4">Blue</option>
</select>
</form>
I want to pass that data over jQuery ajax so I'm using:
$.ajax({
type: 'post',
url: 'index.php?route=product/options_plus_redux/updateImage',
dataType: 'json',
data: $('form#unit :input'),
success: function (data) {
//do something here...
}
});
And that works fine. However, I want to add another bit of data along with the form fields. But I can't figure out the syntax for it. I know since the selectbox is named "option" there it will try to serialize that array. but basically I'm trying to do:
data: $('form#unit :input') +'x=test',
But it comes back very wrong
Any ideas?
try this:
data: $('form#unit').serialize() +'&x=test',
look up about jQuery form serialization
you can see it running here: http://jsfiddle.net/maniator/pfb2c/
var data = $('form#unit :input');
data.x = "test";
.......
url: 'index.php?route=product/options_plus_redux/updateImage',
dataType: 'json',
data: data,
.......

Categories