This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I have a php script that executes a query against a mySQL database and returns an array. Here is the output:
[["185","177","8","10h:43m:54s","http:\/\/localhost\/toastReport\/cd7bf9ae-c21d-4746-bdd9-6934f8e5924e_ed13cfdc-403b-4a82-8f71-0da41a466e62_report\/feature-overview.html"]]
I am using ajax to call the PHP script and am then trying to load the data into a javascript array and then print out different values later in my HMTL page. Here is the javascript script I have in my page header:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function myfunction() {
var automation = [];
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function (jsonData) {
automation = jsonData;
console.log(automation);
}
});
}
</script>
I am trying to use the array data in a card at the top of my page:
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div class="mr-5">Total tests: <script type="text/javascript"> myfunction(); </script></div>
<div class="mr-5">Failed tests:</div>
<div class="mr-5">Passed tests:</div>
<span class="float-right"><div class="mr-5">Run Time:</div></span>
</div>
<a class="card-footer text-white clearfix small z-1" href="http:\//localhost\/toastReport\/cd7bf9ae-c21d-4746-bdd9-6934f8e5924e_ed13cfdc-403b-4a82-8f71-0da41a466e62_report\/feature-overview.html">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
I am confused on how to make this work and any info or links to pages with a guide on how to make this work would be greatly appreciated. Thanks!
Simply use the data when it's returned from ajax().
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function (data) {
console.log(data);
var total = data[0];
var failed = data[1];
var passed = data[2];
var time = data[3];
document.getElementById('total').innerHTML = "Total tests: " + total;
document.getElementById('failed').innerHTML = "Failed tests: " + failed;
document.getElementById('passed').innerHTML = "Passed tests: " + passed;
document.getElementById('runTime').innerHTML = "Run Time: " + time;
}
});
}
HTML
<div id="total" class="mr-5">Total tests: <script type="text/javascript"> myfunction(); </script></div>
<div id="failed" class="mr-5">Failed tests:</div>
<div id="passed" class="mr-5">Passed tests:</div>
<span id="runTime" class="float-right"><div class="mr-5">Run Time:</div></span>
Related
I am trying to update the status for my orders on the same page where it's displayed with an ajax HTML.
Displaying works just fine, but I want to set the status the the next one with only one click so I figured to use ajax for it too.
My ajax PUT for the next status
$(function () {
$(document).on('click', 'button#order_update', function (e) {
e.preventDefault();
let newStatus = '';
if ($(this).data('status') == 'pending') {
newStatus = 'confirm';
} else if ($(this).data('status') == 'confirm') {
newStatus = 'processing';
} else if ($(this).data('status') == 'processing') {
newStatus = 'picked';
}
let formStatusData = new FormData();
formStatusData.append('order_id', $(this).data('order'));
$.ajax({
type: 'PUT',
url: '{{ route("update-order-status") }}',
data: formStatusData,
success: (response) => {
console.log(response);
$(this).data('status', newStatus);
$(this).text(newStatus.charAt(0).toUpperCase() + ' order');
}
});
});
});
My ajax for the html
$.ajax({
type: 'GET',
url: '/order/view/all',
dataType: 'json',
cache: false,
success:function(response){
$('#pimage').attr('url','/'+response.product.product_thambnail);
var product_name = $('#pname').text();
var id = $('#product_id').val();
var quantity = $('#qty').val();
var OrderView = ""
$.each(response.orders, function (key,value){
var productsList = '';
$.each(value.product, function (key,value) {
productsList += `
<div class="row gx-4">
<div class="col-lg-3">
<div class="pos-task-product">
<div class="pos-task-product-img">
<div class="cover" style="background-image: url(${value.product_thambnail});"></div>
</div>
<div class="pos-task-product-info">
<div class="flex-1">
<div class="d-flex mb-2">
<div class="h5 mb-0 flex-1">${value.product_name_en}</div>
<div class="h5 mb-0">${value.pivot.qty} DB</div>
</div>
</div>
</div>
<div class="pos-task-product-action">
Complete
Cancel
</div>
</div>
</div>
</div>
`;
});
OrderView += `<div class="pos-task">
<div class="pos-task-info">
<div class="h3 mb-1" id=""><td>Üzenet: ${value.notes}</td></div>
<div><div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div></div>
<br>
<!-- You can safely remove this if not needed
<div class="mb-3">${value.product_id}</div>
<div class="h4 mb-8">${value.product_name}</div>
-->
<td> </td>
<div class="mb-2">
<span class="badge bg-success text-black fs-14px">${value.status}</span>
</div>
<div><span class="text">${value.created_at}</span> Beérkezett</div>
</div>
<div class="pos-task-body">
<div class="fs-16px mb-3">
Completed: (1/4)
</div>
${productsList}
</div>
</div>`
});
$('#OrderView').html(OrderView);
}
})
}
OrderView();```
**Im currently trying to use this button inside the HTML ajax**<div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div>
I tried using processData: false, but it just kills the process and the button is unusable. Please help.
Your problem is that you have many identifiers # with the same name.
id must be unique.
Replace in code
$(document).on('click', 'button#order_update'
to
$(document).on('click', 'button.order_update'
and
<button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button>
to
<button type="button" class="btn btn-outline-theme rounded-0 w-150px order_update" data-status="${value.status}" data-order="${value.status}">Confirm Order</button>
You still have the problem that you didn't close the class quote after w-150px, I closed it in the formatted code
I want to automatically reorder/sort a div according to the highest vote count once an ajax call is done, I have tried many thing codes and none seems to be working.
Below is the code.
#foreach($candidates->sortByDesc("voteCount") as $candidate)
<div class="col-md-6" id="{{$candidate->voteCount}}">// this is the div I want to reorder
<div class="card">
<div class="card-header">
<h4 class="card-title" id="heading-multiple-thumbnails">{{$candidate->name}} {{$candidate->runningMate[0]->name}}</h4>
<a class="heading-elements-toggle">
<i class="la la-ellipsis-v font-medium-3"></i>
</a>
</div>
</div>
</div>
#endforeach
The Javascript
$('.castVoteForCandidateButton').on('click', function (e) {
$("#voteCofirmStatus").hide();
$("#voteProccessStatus").show();
$.ajax({
type:'POST',
url:'/vote',
data:{candidateId : candidateId, _token: "<?php echo csrf_token(); ?>",name:name ,position:position},
success:function(data){
if(data.status =='ok' ){
setTimeout(function() {$('#voteProcessingModal').modal('hide');}, 500);
$("#voteProccessStatus").hide();
$("#voteSuccessStatus").show().text('Nice job!,you have successfully voted for '+ data.name);
$("#voteCount"+data.id).text(parseFloat(data.voteCount)+" Votes");
$("#confirmCandidateVoteButton"+data.id).hide();
var div = $("#voteCount"+data.id);
div.animate({fontSize: "30px"}, "slow");
div.animate({fontSize: "17px"}, "slow");
const main = document.querySelector('#main');// this
const divs = [...main.children];// is
divs.sort((a, b) => a.id - b.id);// the
divs.forEach(div => main.appendChild(div));// Latest code I tried and its not working
}else{
$("#voteErrorStatus").show().text(data);
}
}
});
} );
I have a card in my web page that reads in Automation Data and displays it in the card my the page. I am about to read in all the needed data except for the URL to the automation test summary.
Here is my code:
function Cox() {
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function(data) {
console.log(data);
var total = data[0];
var passed = data[1];
var failed = data[2];
var time = data[3];
var url = data[4];
document.getElementById('coxTotal').innerHTML = "Total tests: " + total;
document.getElementById('coxFailed').innerHTML = "Failed tests: " + failed;
document.getElementById('coxPassed').innerHTML = "Passed tests: " + passed;
document.getElementById('coxRunTime').innerHTML = "Run Time: " + time;
document.getElementById('coxUrl').innerHTML = "url " + url;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div id="coxTotal" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
<div id="coxFailed" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
<div id="coxPassed" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
<div id="coxRunTime" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
When I try to load the URL into the HMTL like I did for the other 4 variables it does not seem to work correctly. Any ideas?
UPDATE:
Thank you for the helpful comments on how to clean up my code. I have aded it in and it has made it a lot cleaner. I have also found the following post that has provided a solution to my issue. Thanks
document.getElementById to include href
You will get the error message as "Uncaught ReferenceError: Cox is not defined" because you are calling 'Cox()' function before define it. DOM will process line by line and during that time, the function does not exist.
I changed your code and mentioned below. it will work as you expected. :)
I called 'Cox()' function after definition. You can change the place where ever you want but after definition.
<html>
<body>
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div id="coxTotal" class="mr-5"></div>
<div id="coxFailed" class="mr-5"></div>
<div id="coxPassed" class="mr-5"></div>
<div id="coxRunTime" class="mr-5"></div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function Cox()
{
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function (data) {
console.log(data);
var total = data[0];
var passed = data[1];
var failed = data[2];
var time = data[3];
var url = data[4];
document.getElementById('coxTotal').innerHTML = "Total tests: " + total;
document.getElementById('coxFailed').innerHTML = "Failed tests: " + failed;
document.getElementById('coxPassed').innerHTML = "Passed tests: " + passed;
document.getElementById('coxRunTime').innerHTML = "Run Time: " + time;
document.getElementById('coxUrl').innerHTML = "url " + url;
}
});
}
Cox();
</script>
</body>
</html>
You should only call Cox() once: when the page loads as it targets all the divs anyway. Also, Cox() is undefined because you call it before you define it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function Cox() {
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function(data) {
console.log(data);
var total = data[0];
var passed = data[1];
var failed = data[2];
var time = data[3];
var url = data[4];
document.getElementById('coxTotal').innerHTML = "Total tests: " + total;
document.getElementById('coxFailed').innerHTML = "Failed tests: " + failed;
document.getElementById('coxPassed').innerHTML = "Passed tests: " + passed;
document.getElementById('coxRunTime').innerHTML = "Run Time: " + time;
document.getElementById('coxUrl').innerHTML = "url " + url;
}
});
}
window.onload = function(){
Cox();
}
</script>
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div id="coxTotal" class="mr-5">
</div>
<div id="coxFailed" class="mr-5">
</div>
<div id="coxPassed" class="mr-5">
</div>
<div id="coxRunTime" class="mr-5">
</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
This is my script code where i will get a array list, then i have iterated and got each one in a variable. Now my requirement is to show this values in my html page which i have designed. I have to load the retried values in my page. The imageurl should be given inside the img src to show that image. Plus this should be dynamically incremented.
<script>
function getValueFromServer(e) {
//make the AJAX request to server
$.ajax({
type: "GET",
url: "http://example./../getAllBrandList",
dataType: "json",
//if received a response from the server
success: function( data) {
console.log(data);
var brands=data;
var i = 0
//our country code was correct so we have some information to display
for ( var i = 0; i < brands.allBrands.length; i++) {
var obj = brands.allBrands[i];
console.log(obj);
var fundedType= "LIVE";
var url=obj.url;
var imageUrl=obj.image_url;
var brandName=obj.brandName;
var description=obj.description;
var totalGoal=obj.total_goal;
var totalRaised=obj.total_raised;
var profitMargin=obj.profit_margin;
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown){
console.log("Something really bad happened " + textStatus);
$("#ajaxResponse").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function(jqXHR, settings){
//adding some Dummy data to the request
settings.data += "&dummyData=whatever";
//disable the button until we get the response
$('#myButton').attr("disabled", true);
},
//this is called after the response or error functions are finsihed
//so that we can take some action
complete: function(jqXHR, textStatus){
//enable the button
$('#myButton').attr("disabled", false);
}
});
};
window.onload = getValueFromServer();
</script>
<div class="small-12 columns" onload="getValueFromServer()">
<ul class="small-block-grid-1 medium-block-grid-2 large-block-grid-3" id="brands">
<!-- <li class="item" >
<a href="" class="badge-live" data-badge="LIVE" ></a>
<a href=""><div class="offer">
<span class="link-overlay"></span>
<img src="" id="imageurl">
<div class="offer-info">
<h6 id="brandname"></h6>
<p class="offer-short" id="description"></p>
<p class="funded">
<span class="goal">
<strong id="totalgoal">$</strong> raised 1 day ago in 13 minutes
</span>
</p>
<div class="nice round progress"><span class="meter-reserved" style="width: 100%;"></span><span class="meter" style="width: 100%;"></span></div>
<div class="row offer-stats">
<div class="small-12 columns text-center">
<p>
<span id="profitmargin">%</span> Co-Op Profit Margin
</p>
</div>
</div>
<hr style="margin:0.5rem 0 1rem;">
<div class="row text-center offer-stats">
<div class="small-6 columns">
<p>
<span>96</span>following
</p>
</div>
<div class="small-6 columns" style="border-left: 1px solid #dbdbdb;">
<p>
<span>4</span>Months
</p>
</div>
</div></a>
<div class="text-center">
GET STARTED
</div>
</div>
</div>
</li> -->
</ul>
</div>
not tested but should work using innerHTML to write list to brands ul
function getValueFromServer(e) {
//make the AJAX request to server
$.ajax({
type: "GET",
url: "http://example./../getAllBrandList",
dataType: "json",
//if received a response from the server
success: function( data) {
console.log(data);
var brands=data;
var i = 0
//our country code was correct so we have some information to display
for ( var i = 0; i < brands.allBrands.length; i++) {
var obj = brands.allBrands[i];
console.log(obj);
var fundedType= "LIVE";
var url=obj.url;
var imageUrl=obj.image_url;
var brandName=obj.brandName;
var description=obj.description;
var totalGoal=obj.total_goal;
var totalRaised=obj.total_raised;
var profitMargin=obj.profit_margin;
document.getElementById("brands").innerHTML += '<li class="item" >\
<a href="" class="badge-live" data-badge="LIVE" ></a>\
<a href=""><div class="offer">\
<span class="link-overlay"></span>\
<img src="'+imageUrl+'" id="imageurl">\
<div class="offer-info">\
<h6 id="brandname">'+brandName+'</h6>\
<p class="offer-short" id="description">'+description+'</p>\
<p class="funded">\
<span class="goal">\
<strong id="totalgoal">$'+totalGoal+'</strong> raised 1 day ago in 13 minutes\
</span>\
</p>\
<div class="nice round progress"><span class="meter-reserved" style="width: 100%;"></span><span class="meter" style="width: 100%;"></span></div>\
<div class="row offer-stats">\
<div class="small-12 columns text-center">\
<p>\
<span id="profitmargin">%'+profitMargin+'</span> Co-Op Profit Margin\
</p>\
</div>\
</div>\
<hr style="margin:0.5rem 0 1rem;">\
<div class="row text-center offer-stats">\
<div class="small-6 columns">\
<p>\
<span>96</span>following\
</p>\
</div>\
<div class="small-6 columns" style="border-left: 1px solid #dbdbdb;">\
<p>\
<span>4</span>Months\
</p>\
</div>\
</div></a>\
<div class="text-center">\
GET\ STARTED\
</div>\
</div>\
</div>\
</li>';
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown){
console.log("Something really bad happened " + textStatus);
$("#ajaxResponse").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function(jqXHR, settings){
//adding some Dummy data to the request
settings.data += "&dummyData=whatever";
//disable the button until we get the response
$('#myButton').attr("disabled", true);
},
//this is called after the response or error functions are finsihed
//so that we can take some action
complete: function(jqXHR, textStatus){
//enable the button
$('#myButton').attr("disabled", false);
}
});
};
window.onload = getValueFromServer();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small-12 columns" onload="getValueFromServer()">
<ul class="small-block-grid-1 medium-block-grid-2 large-block-grid-3" id="brands">
</ul>
</div>
I've searched and tried for 2 days now, with no luck whatsoever.
What i'm trying:
I generate several div's through a foreach in xslt, that contains a hidden div where i store a code to match value out of an external xml file on. Something like this:
<div class="pakket_content">
<a href="http://">
<div class="waardering_wrapper col-xs-12">
<div class="sterwaardering col-xs-8">
<img src="http://">
</div>
<div class="CODE">CODE</div>
<div class="waardering col-xs-4">
<p>-</p>
</div>
<div class="waardering pull-right">
<b>-</b>
</div>
</div>
</a>
<a href="">
<button type="button" class="btn btn-default btn-md pull-right col-xs-12">
Nu boeken!
<span class="glyphicon glyphicon-arrow-right"></span>
</button>
</a>
</div>
Where the div class 'code' contains the code to match on.
The xml that comes out of this is:
<entities>
<accommodation cms-id="458245" external-id="CODE" name="Trip A">
<destination cms-id="45541" name="Paramaribo" level="destination"/>
<country cms-id="4545" name="Suriname" level="country"/>
<accommodation-type>Hotel</accommodation-type>
<testimonial-count>88</testimonial-count>
<average-testimonial-score>7.6</average-testimonial-score>
<deep-link>
http://link.com
</deep-link>
<testimonial-count-per-language>88</testimonial-count-per-language>
<testimonial-count-all>88</testimonial-count-all>
<average-testimonial-score-all>7.6</average-testimonial-score-all>
</accommodation>
</entities>
Now i wanted to append the average-testimonial-score to div "waardering" when the external-id attribute in equals the value in . But how would i go about that?
I tried with looping through the value of the div class and the attribute, like this:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "file.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('accommodation').each(function(index) {
var cijfer = $(this).find('average-testimonial-score-all').text();
$('.CODE').each(function(index) {
var divcode = $(this).text();
$.attr('external-id').each(function(index) {
var attrcode = $(this).text();
if (divcode == attrcode) {
$(".waardering").append(cijfer);
};
});
});
});
}
});
});
With no result.
Can someone push me in the right direction with this?
Fetching accommodation external-id in correct way (according to how .attr() is supposed to work), the code works as it should.
I omitted Ajax request for testing.
Fiddle.
$(document).ready(function()
{
var xml = '<entities><accommodation cms-id="458245" external-id="CODE" name="Trip A"> <destination cms-id="45541" name="Paramaribo" level="destination"/> <country cms-id="4545" name="Suriname" level="country"/> <accommodation-type>Hotel</accommodation-type> <testimonial-count>88</testimonial-count> <average-testimonial-score>7.6</average-testimonial-score> <deep-link>http://link.com</deep-link> <testimonial-count-per-language>88</testimonial-count-per-language> <testimonial-count-all>88</testimonial-count-all> <average-testimonial-score-all>7.6</average-testimonial-score-all> </accommodation></entities>';
$(xml).find('accommodation').each(function(index)
{
var cijfer = $(this).find('average-testimonial-score-all').text();
var externalId = $(this).attr("external-id");
$('.CODE').each(function(index)
{
var divcode = $(this).text();
if (divcode == externalId)
{
$(".waardering").append(cijfer);
};
});
});
});