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

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>

Related

Sending two forms after button click and run php in background

I have created this site and integrated with payfast, it works well. but now i want to execute another php script on place order button which gets details into the db
here is my code quite long.... I no nothing about Ajax or javascript!! Please help
<form id="form1" action="payment.php" method="POST">
some stuff...
</form>
<?php
$htmlForm = '<form action="https://'.$pfHost.'/eng/process" method="post" id="form2">';
$htmlForm .= '<input type="submit" id="submit" name="submit" class="btn btn-primary btn-lg btn-flat" value="PLace Order" onclick="submitForms()"></form>';
?>
<?php
echo"
".$htmlForm."
</div>";
}
else{
echo '...';
}
?>
<script>
submitForms = function() {
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
</script>
$(function() {
$(".submit").click(function() {
var uid = $("#uid").val();
var prodtls = $("#prodtls").val();
var fname = $("#fname").val();
var amnt = $("#amnt").val();
var mail = $("#mail").val();
var dataString = 'uid='+ uid + '&prodtls=' + prodtls + '&fname' +fname + '&amnt' + amnt + '&mail' + mail;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "payment.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
I tried the ajax i found but, it never worked. Check at the end of my code!
What i need is payment.php will execute in the background while it directs user to payfast
I want to submit only the first one via AJAX.
Your attempt doesn't make much sense because it doesn't appear to target the first form (which you say you want) and may not prevent the default postback behaviour.
As I understand it, you want that whichever form the user clicks on to submit, the code will actually then submit the first form via AJAX, and then the second one via standard postback.
This should do the job:
HTML:
<form id="form1" class="doubleForm" action="payment.php" method="post">
<input type="submit" id="submit1" name="submit" class="btn btn-primary btn-lg btn-flat" value="Submit">
</form>
<form id="form2" class="doubleForm" action="https://example.com/eng/process" method="post">';
<input type="submit" id="submit2" name="submit" class="btn btn-primary btn-lg btn-flat" value="Place Order">
</form>
JavaScript:
//handle submission of both forms
$(".doubleForm").submit(function(event) {
event.preventDefault(); //stop standard postback
var uid = $("#uid").val();
var prodtls = $("#prodtls").val();
var fname = $("#fname").val();
var amnt = $("#amnt").val();
var mail = $("#mail").val();
var dataString = 'uid='+ uid + '&prodtls=' + prodtls + '&fname' +fname + '&amnt' + amnt + '&mail' + mail;
if(time == '' || date == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
//submit first form via AJAX
var request = $.ajax({
type: "POST",
url: "payment.php",
data: dataString
});
request.done(function(response) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
//now the first form is submitted and server has responded, we can trigger "normal" (non-AJAX) submission of second form
document.querySelector("#form2").submit();
});
}
});
So this actually worked well using .serialize(). Thanks #ADyson for the headsup just had to tweak it a little bit, though i'm not experienced in js
<script type="text/javascript">
$(function(){
$("#submit2").click(function(){
var dataString = $("#form1").serialize();
$.ajax({
type: "POST",
url: "payment.php",
data: dataString,
success: function(data)
{
alert('Success!');
$("#form1")[0].reset();
}
});
});
});
</script>

Use Ajax response script into a Django HttpResponse

I am trying to pass the ajax response obtained from view to the template using HttpResponse but I don't have any idea, how to do that?
view.py
analyzer=SentimentIntensityAnalyzer()
def index(request):
return render(request, "gui/index.html")
#csrf_exempt
def output(request):
sentences = request.POST.get('name',None)
senti = analyzer.polarity_scores(sentences)
context_dict = {'sentiment': senti}
return render(request,"gui/index.html", context = context_dict
I want the senti to be printed after the score on the page but I am unable to obtain it.
template file
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<form action = Post>
Enter Sentence:<input id = "name" type = "text" name = "EnterSentence" encoding = "utf-8"><br>
<input onclick = "testfunction()" type = "button" value = "Submit" >
</form>
<div><strong>Score is {{ sentiment }}</strong></div>
</body>
<script>
var testfunction = () => {
var test = document.getElementById("name").value
console.log(test)
$.ajax({
type: "POST",
dataType: "json",
url: 'output/',
data:{
csrfmiddlewaretoken: '{{ csrf_token }}',
'name': test
},
success: function(response) {
console.log("Succesful return firm ajax call");
},
error: function(result){
console.log("Failure");
}
});
}
</script>
</html>
In your view.py return render(request,"gui/index.html", context = context_dict code is missing ending paranthesis.
This is the correct order of jQuery ajax:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Your success and error fields are inside of data.
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
This is an example of how to use .html method of ajax jquery. You can adjust for your own.
Additionally, use below code to loop through response:
$.each( data, function( key, val ) {
HTMLString += <li id='" + key + "'>" + val + "</li>
});
and this should be inside of the function of success and then pass HTMLString into .html method
To make it clearer how to $.each works:
var numbers = [1, 2, 3, 4, 5, 6];
$.each(numbers , function (index, value){
console.log(index + ':' + value);
});

Pushing array of values from a form into Google Spreadsheet comes through as 'undefined'

I have a form with text fields which the user can "Add New" by clicking a button. These fields share the same name. I'm trying pass the values into Google Spreadsheets, but the values all come through as 'undefined' with the following code, even though console.log prints the answers as strings which look okay to me.
So if the user for example submits 3 separate entries for SUNDAY_NOTES[], all 3 strings should end up in one cell broken up by new lines, but instead I'm just getting "undefined".
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // the user can create multiples of these ^ for each day of the week
<input type="submit" id="submit" />
</form>
<script>
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray().map((e) => {
return e.value
}).join('\n')
});
})
});
</script>
Your code works. In the snippet below I am storing the data split by \n in a variable and logging it. You can check the output.
Although your JS is correct, I suspect that you actually want to be using a different HTTP method. Perhaps POST or PUT? I can't be specific as you have not said which API endpoint you are using.
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var data = $form.serializeArray().map((e) => {
return e.value
}).join('\n');
console.log(data);
var jqxhr = $.ajax({
url: url,
method: "POST",
dataType: "json",
data: data
}).done(response => {
console.log(response);
}).fail((jqXHR, textStatus) => {
console.log("Request failed: " + textStatus);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="submit" id="submit" />
</form>
remove the [] from your input's name as this is needed if you want to receive an array in the server side, then create a function that groups the values according to the inouts' keys :
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
and use it like :
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray()),
//... rest of your code
this will keep the original structure that works,
here's a snippet :
var $form = $('form#timesheet');
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
$form.submit(function(e) {
e.preventDefault();
var grouped = group($form.serializeArray());
console.log(JSON.stringify(grouped))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES"><br />
<input type="text" name="SUNDAY_NOTES"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES"> // and so forth
<input type="submit" id="submit" />
</form>

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');?>";
}

Page getting stuck after Ajax Call

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.

Categories

Resources