Page getting stuck after Ajax Call - javascript

So this is the form I have
<form action="javascript:void(0);" class="form-inline" id="receive-order-form"> By Receiving you agree that you have received the item <b> {{ x.item_name }} </b> at the store. </br> Order Id <b> {{ x.order_id }} </b></br><input class="btn btn-primary center-block" onclick="execute({{x.linq_order_num}})" type="submit" id= 'receive-btn' value="Receive" ></form>
On submit the remote call gets executed and I get the success pop up but somehow the screen gets stuck like this. Page becomes unresponsive.
Execute Function Definition:
function execute(linq_order_num) {
var result = "";
var tableRow=document.getElementById("order_num1_"+String(linq_order_num));
var modalId = "exampleModal1_" + "{{ linq_order_num }}";
jQuery.ajax ({
url: "/receive-order/",
type: "POST",
data: JSON.stringify({"linq_order_num":linq_order_num}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){
result = data;
$("#modalId").modal('hide');
$('#alert_placeholder').html('<div class="alert
alert-success"><a class="close" data-
dismiss="alert">×</a>
<span>Successfully received the product</span>
</div>');
var htmlElement = document.getElementById("deliver-
order_"+ String(linq_order_num));
var cln = htmlElement.cloneNode(true);
cln.style.display = null;
tableRow.cells[7].innerHTML = cln.outerHTML;
}
});
return result;
}
how can I solve this ?

Assuming you were wanting to hide the modal id referenced in:
var modalId = "exampleModal1_" + "{{ linq_order_num }}";
Change:
$("#modalId").modal('hide');
Into:
$("#" + modalId).modal('hide');
In the current version, you are trying to hide the element with id="modalId" in the HTML.

Related

The response received in AJAX call is shown in another HTML page

I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.
Form HTML
<form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">
<div class="form-group">
<input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
<button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>
</div>
</form>
AJAX
<script>
$("#AssociateForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var local_id = $('input[name=J_ID]').attr('id');
var formData = {
'J_ID' : $('input[name=J_ID]').val()
};
console.log(formData)
$.ajax({
url: url,
data: formData,
dataType: 'json',
success: function (datas) {
var data = JSON.parse(datas);
if(datas.status){
alert(datas);
//$('#Failure_'+local_id).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')'
}
},
error: function(jqXHR, textStatus){
alert("In error")
}
})
.done(function(data){
alert(data)
});
});
</script>
for some reason, the above code is not printing the console log as well.
But,
When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.
JSON Response
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
below is from View-Page-source
<html>
<head></head>
<body data-gr-c-s-loaded="true">
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
</pre>
</body>
</html>
This is possibly because you are submitting a form, and after submitting it will open a new tab, as Form is submitted.
To resolve this, you can probably use the below code:
<form action="..." method="POST" target="_blank">
<input type="submit" id="btn-form-submit"/>
</form>
<script>
$('#btn-submit').click( function(){ $('#btn-form-submit').click(); } );
</script>
success: function (datas) {
if (datas.status) {
alert(datas);
$('pre#<ID>').html(datas.category + ' issue: ' + datas.j_id + ' (' + datas.j_status + ')');
}
}
This worked for me, I removed the form completely.
Code in-place of Form
<div class="form-group AssociateForm" style="float:right">
<input type="text" name="J_ID" style="width:150px;float:left" class="form-control has-success">
<button name="button" type="submit" id="{{TR.id}}" class="Associater btn btn-primary">Associate</button>
</div>
AJAX
<script>
$('.Associater').on('click', function () {
var local_id = $(this).attr('id');
var j_id = $(this).closest("div.AssociateForm").find('input[name=J_ID]').val();
if (j_id === "") {
alert("JID cannot be empty")
return false
}
var url = "{% url 'Project:View' 0 %}".replace('0', local_id);
var formData = {
'J_ID' : j_id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
console.log(local_id);
console.log(j_id);
console.log(url);
console.log(formData);
$.ajax({
type: 'POST',
url: url,
data: formData,
dataType: 'json',
success: function (data) {
if (data.status) {
ele = 'Failure_'+local_id;
document.getElementById(ele).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')';
}
},
error: function (jqXHR, textStatus ) {
alert("For some reason im here");
}
});
});
</script>

Collecting multiple data and send by ajax in laravel

I'm using ajax to send my data to controller and save it in database, before my code was working then I needed to sort my data when they append in blade after sorting them it stop working by %50.
Good to know
Here is my old code and solution of sorting my data (which caused
this issue that i have now)
Logic
I select set
Set childs will append in blade (sorted by custom column)
I choose single or multiple options and hit save button
Data saves to database
More to know
My appended data (based on selected set) are include 2 types of data
Custom inputs (text field & text-area field) which i can manually fill and save (still working with no issue)
Dynamic select option which returns from database and i can select and save their id's (this is the issue dynamics)
Code
Script of appending data
<script defer>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$('div#dataaamsg').empty();
$('div#dataaamsg').append('Use <kbd>CTRL</kbd> or <kbd>SHIFT</kbd> button to select multiple options');
result.sort(function(a,b) {
return (a.position > b.position) ? 1 : ((b.position > a.position) ? -1 : 0);
});
$.each(result, function(key1, value1) {
var vvvid = value1.id;
if(value1['type'] == 'textfield'){
var my_row = $('<div class="row mt-20 ccin">');
$('div#dataaa').append(my_row);
}else if(value1['type'] == 'textareafield'){
var my_row = $('<div class="row mt-20 ccin">');
$('div#dataaa').append(my_row);
}else{
var my_row = $('<div class="row mt-20">');
$('div#dataaa').append(my_row);
}
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
// Check result isnt empty
var helpers = '';
$.each(data, function(key, value) {
helpers += '<option value="'+value.id+'">'+value.title+'</option>';
});
if(value1['type'] == 'textfield'){
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><input id="text_dec" name="text_dec[]" placeholder="text field" class="text_dec form-control"></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}else if(value1['type'] == 'textareafield'){
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><textarea id="longtext_dec" name="longtext_dec[]" placeholder="text area field" class="longtext_dec form-control"></textarea></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}else{
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">'+helpers+'</select></div>';
my_html += '<div class="col-md-2"><button type="button" id="savedynspecto" class="savedynspecto btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}
}
});
// second data
});
}
});
}else{
$('div#dataaa').empty();
}
});
});
</script>
script of saving data (issue part)
<script defer>
$(document).ready(function() {
$("body").on("click", ".savedynspecto", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': $(this).closest('form').find('select.subspecifications').val()
},
success: function (data) {
alert('Specifications added successfully.');
console.log($(this));
},
error: function (data) {
console.log(data);
}
});
});
});
</script>
Issue
When I try to save my dynamic values i cannot get id of selected option/options
//returned data in network params
_token g1GnKZvzXDztR1lqgDdjI5QOg67SfmmBhjm80fKu
product_id 18
subspecifications
Ps1
I've tried to change val() to serialize() and I got
_token g1GnKZvzXDztR1lqgDdjI5QOg67SfmmBhjm80fKu
product_id 18
subspecifications subspecifications%5B%5D=20&subspecifications%5B%5D=21&subspecifications%5B%5D=23&subspecifications%5B%5D=32"
All I needed was 21,23,32 instead i got subspecifications%5B%5D= before each of them.
Ps2
I've tried to change $("body").on("click", ".savedynspecto", function(e){ that would not send any data to back-end (nothing prints in network not even error codes)
Any idea?
Hi change this line in your code
'subspecifications':
$(this).closest('form').find('select.subspecifications').val()
to
'subspecifications':
$(this).closest('form').find('select.subspecifications
option:selected').map(function(){ return this.value }).get()
It should help
After the button... in the string to append, you have {{Form::close()}}</div>.
I think the </div> should come before the {{Form::close()}}.
A messed-up HTML structure can lead to strangenesses quickly.
I'm not 100% sure that is the issue... But it could.
You have MANY select with class subspecifications... So you have to loop through them to get their values.
<script defer>
$(document).ready(function() {
$("body").on("click", ".savedynspecto", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// An array to store the subspecifications values.
var spec_array = [];
// A loop to go through all them.
form.find('select.subspecifications').each(function(){
spec_array.push($(this).val());
});
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': spec_array // The array containing each SELECT values
},
success: function (data) {
alert('Specifications added successfully.');
console.log($(this));
},
error: function (data) {
console.log(data);
}
});
});
});
</script>

ajax get wrong value

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);
}
});
});

Toggle data-value after Ajax success without element ID

I have multiple buttons to toggle status of different projects:
<div class="btn-group btn-toggle project_status" data-project-id="1" data-form="project_status" data-value="1">
<button class="btn btn-default active">ACTIVE</button>
<button class="btn btn-primary">CLOSED</button>
</div>
<div class="btn-group btn-toggle project_status" data-project-id="2" data-form="project_status" data-value="1">
<button class="btn btn-default active">ACTIVE</button>
<button class="btn btn-primary">CLOSED</button>
</div>
I need to toggle the data-value between 1 and 2 when ajax post success.
I have tried this so far but without any luck:
$('.project_status').click(function(){
var project_id = $(this).attr('data-project-id');
var project_status_val = $(this).attr('data-value');
var toggle_status = function(){
$(this).find('.btn').toggleClass('active').toggleClass('btn-primary');
if (project_status_val == '1'){
alert(project_status_val);
$(this).attr('data-value','2');
} else {
alert(project_status_val);
$(this).attr('data-value','1');
}
return false;
};
var dataString = 'project_id=' + project_id + '&project_status=' + project_status_val;
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: toggle_status
});
$('#sidebar-wrapper').load('sidebar.php');
return false;
});
I have got the alert data value correct. I have got the sidebar reload with updated value (only the first click). But I am not able to change the attribute value so that the next click will send the toggled value.
Please help! Thx
$(this) inside the toggle_status method is not your btn. Inside the method the this keyword refers to the object the method belongs to. In this case Window. As a workaround, I have made a self property before the method to store a reference to the selected $('.project_status') object. I have updated the code so it will work.
https://jsfiddle.net/05akxvx3/1/
$('.project_status').click(function(){
var self = $(this);
var project_id = self.attr('data-project-id');
var project_status_val = self.attr('data-value');
var toggle_status = function(){
self.find('.btn').toggleClass('active').toggleClass('btn-primary');
if (project_status_val == '1'){
self.attr('data-value','2');
} else {
self.attr('data-value','1');
}
alert(self.attr('data-value'));
return false;
};
var dataString = 'project_id=' + project_id + '&project_status=' + project_status_val;
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: toggle_status
});
$('#sidebar-wrapper').load('sidebar.php');
return false;
});
You have an extra dash in your $(this).attr() statement.
$(this).attr('data--value','2'); ought to be:
$(this).attr('data-value','2');

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