ajax get wrong value - javascript

I used ajax for my current project with laravel and i try to pass value of textbox using ajax but it pass R every time, even if i pass the wrong variable with ajax. my code is as below
<div class="form-group">
<label for="">Total Amount</label>
<input type="text" class="form-control" id="total_amount" value="123" name="total">
</div>
javascript code
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: {
lists: list, total: total, "_token": "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});
laravel method
public function getTotal(Request $request)
{
$list = #$request['lists'];
$total = #request['total'];
return $total;
}
varibale list work fine but total always return value R, when it print first time log that time it print correct value in console, but second time in success function of ajax it print always R. where i made mistake??

Change this:
$total = #request['total'];
to this:
$total = #$request['total'];
^

Try like below:
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: "lists="+list+"&total="+total+"&_token={{ csrf_token()}}",
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});

Related

Submit form using ajax and pass the value submitted to new page

i have form that need the previous value inserted....i'm using ajax,but the success: function(data) wont let me moved to the next page...
here is my code
HTML
<form>
<input type="text" name="id_1" id="id_1>
<input type="text" name="id_2" id="id_2>
<input type="text" name="id_3" id="id_3>
<button type="button" onclick="next();">
</form>
<div id="tabelna"></div>
JQuery
var id_1 = $('#id_1').val();
var id_2= $('#id_2').val();
var id_3= $('#id_3').val();
var datana = 'id_1='+id_1+'&id_2='+id_2+'&id_3='+id_3;
var urlna="<?=base_url()?>something/something/something";
$.ajax({
type: 'POST',
url: urlna,
data: datana,
beforeSend:function(data){
},
message:"<center>><h3>Loading Data. . .</h3></center>"
});
},
error: function(data) {
jAlert('Failed');
},
success: function(data) {
load();
}
})
return false;
}
function load()
{
$('#tabelna').load('<?=base_url()?>something/something/something') (This is my mistake)
}
CONTROLLER
function set_value()
{
extract($_POST);
$d['id1'] = $this-db->query('SELECT * FROM TBL1 where id='.$id_1);
$d['id2'] = $this-db->query('SELECT * FROM TBL2 where id='.$id_2);
$d['id3'] = $this-db->query('SELECT * FROM TBL3 where id='.$id_3);
$this->load->view('something/v_add',$d); (this is my mistake)
}
How can i pass the submitted value to the controller and shows new form ?
we can call controller function using window.location
function load()
{
window.location.href = "<?php echo site_url('controller_d/login/admin_link_delete_user');?>";
}

Check the value of a text input field with ajax

I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.

Unexpected characters in image url in ajax response Javascript

In My Codeigniter web application I'm using an ajax function to get some data from the database inorder to show it in the view.The data from database contains an image url and other fields.
My problem is that when I get the data in ajax success function, the image url looks like this:
<button id='product-1301' type='button' value=1301 class='blue' ><i><img src='assets\/uploads\/thumbs\/default.png'></button>
Since the url contains these characters \ my view is not rendering properly. I tried using stripslash function to remove this. But didn't work. I didn't know where am going wrong.
my ajax function
$.ajax({
type: "get",
url: "index.php?module=pos&view=ajaxproducts1",
data: {category_id: cat_id, per_page: p_page},
dataType: "html",
success: function(data) {
var x= data;
alert(x);
if(data!=1)
{
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
}
else
{
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
Controller
function ajaxproducts1()
{
$mn;$data1;
$img="assets/uploads/thumbs/default.png"; //this is my image path, when this comes in ajax success,\ character adds
$img=str_replace('\"', '', $img);
if($this->input->get('category_id')) { $category_id = $this->input->get('category_id'); }
if($this->input->get('per_page')) { $per_page = $this->input->get('per_page'); }
if($item = $this->pos_model->getProductsByCategory($category_id,$per_page))
{
foreach ($item as $i)
{
$button="<button id='product-".$i->id."' type='button' value=".$i->id." class='blue' ><i><img src='".$img."'><span><span>".$i->name;
$mn=$mn.$button;
}
$data1=$mn;
}
else
{
$data1=1;
}
echo json_encode($data1);
}
Can anyone help me with this ?
Try this:
// use an array to gather up all the values
// call encodeURIComponent() on the variables before adding them
// join them all together and pass them as "data"
var tempVars=['module=pos&view=ajaxproducts1'];
tempVars.push('category_id='+encodeURIComponent( cat_id ));
tempVars.push('userInfo='+encodeURIComponent( p_page ));
var sendVars=tempVars.join('&');
$.ajax({
type: "get",
url: "index.php",
data: sendVars,
dataType: "text",
success: function(data) {
var x = data;
alert(x);
if (data != 1) {
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
} else {
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
My issue was solved by using jQuery.parseJSON function.

Trouble with Ajax post in Django

I need three dependent drop down menus. When a user selects the first menu (market environment), then I need ajax to send that selection to my view in django so I can query SQL to get a list of currencies and populate the second list. In firebug, I keep getting the following error:
MultiValueDictKeyError at /Tplots/ajax_curr/"'mkt'"
I also notice that my Post is empty so I think something is going wrong with my ajax code and I'm not sure whats wrong. Any help would be great.
HTML
<script type="text/javascript">
$(document).ready(function get_currency(){
$('#id_mkt').on('change', function(e) {
e.preventDefault();
$.ajax({
type:"POST",
url: "/Tplots/ajax_curr/",
datatype: "json",
success: function(data) {
alert(data);
},
error:function(){
alert("failure");
}
})
})
})
</script>
<div align="center">
<h1>Swap Curves</h1>
<form action="{% url 'Tplots:swapFig' %}" method = "post">
{% csrf_token %}
{{form.mkt}}
{{form.curr}}
{{form.horizon}}
<input type = "submit" value="Go To" />
</form>
view.py
#csrf_exempt
def ajax_curr(request):
if request.is_ajax():
selected_mkt = MktEnv.objects.get(mkt=request.POST['mkt'])
#selected_mkt = request.POST.get('mkt','')
conn = pyodbc.connect('abcd')
cursor = conn.cursor()
sql_raw = r'''
select currency from market_env_detail
where mkt_env_id=%s
and idx = 1''' % (selected_mkt)
cursor.execute(sql_raw)
xx = cursor.fetchall()
currencyL = []
for items in xx:
x = str(items[0])
currencyL.append(x)
curr = list(set(currencyL))
json = simplejson.dumps(curr)
print json
return HttpResponse(json, mimetype="application/json")
forms.py
class CurrencyForm(forms.Form):
Env_Choices = [('', '-- Choose a Environment --'), ] + [(m.mkt, m.mkt) for m in MktEnv.objects.all()]
Curr_Choices = [('', '--Choose a Currency --'),]+[(c.curr, c.curr) for c in CurrencyAjax.objects.all()]
Horizon_Choices = [('', '--Choose a Horizon --'),] +[(h.hid, h.hid) for h in HorIdAjax.objects.all()]
mkt = forms.ChoiceField(choices=Env_Choices)
curr = forms.ChoiceField(choices=Curr_Choices)
horizon = forms.ChoiceField(choices=Horizon_Choices)
Edit:
I'm trying to put the data into the second dropdown using this success function but all my values become blank. Don't know why.
success: function(data) {
for(var i =0; i<data.length; i++) {
var item=data[i];
$('#curr').append(
$("<option></option>").val(item.Id).html(item.Name));
}
}
You are not sending POST data. You are missing the data parameter.
var data = $(this).parents('form').serialize();
$.ajax({
type:"POST",
url: "/Tplots/ajax_curr/",
data: data,
datatype: "json",
success: function(data) {
alert(data);
},
error:function(){
alert("failure");
}
})

Variable doesn't get passed to Ajax call : undefined variable

I've edited this question from the original OP to better represent my issue.
How can I pass the variable data-uid with AJAX ?
Right now the variable doesnt get passed.
var uid = $(this).data("uid"); doesn't work = undefined
var uid = '199'; gets passed. works.
is it possible to have something like : var uid = $uid; ?
HTML
<form>
<fieldset>
<textarea id="post_form" type="text" data-uid="<?php echo $uid ?>"/></textarea>
<button type="submit" id="add" value="Update" name="submit" />OK</button>
</fieldset>
</form>
JS
$(function() {
$("#add").click(function() {
var boxval = $("#post_form").val();
var uid = $(this).data("uid"); // this needs to be changed
var dataString = 'post_form=' + boxval + '&uid=' + uid;
if (boxval == '') {
return false;
} else {
$.ajax({
type: "POST",
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
return false;
});
});
problem in your code in:
var uid = $(this).data("uid");
you're trying to wrap this into jquery object, but it is button object in this context, then you're trying to obtain something unassigned from it
you shoud use:
var uid = $('#post_form').attr('data-uid');
or, you can add <input type="hidden" name=... value=... and get id from it, this is more general way
Looks like your issue is with the data attribute that should be data-uid="somevalue" Like.
Check this fiddle to see if this solves your main problem

Categories

Resources