Adding Parameter to Javascript AJAX - javascript

this is my simple hardcoded version.
$(document).ready(function(){
$.support.cors = true;
var this_id = '123456789123456';
$.ajax({
url: 'https://thisservice/delivery/'+this_id,
type: "get",
dataType: "json",
data: { },
success: function(response){
console.log(response);
var html = '';
html += '<tr>';
html += '<th>Customer Name: </th><td>'+response.custName+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line1:</th><td>'+response.addrLine1+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line2:</th><td>'+response.addrLine2+'</td>';
html += '</tr>';
html += '<th>Address Line3:</th><td>'+response.addrLine3+'</td>';
html += '</tr>';
html += '<th>Address Line4:</th><td>'+response.addrLine4+'</td>';
html += '</tr>';
html += '<th>Address Line5:</th><td>'+response.addrLine5+'</td>';
html += '</tr>';
html += '<th>Address Line6:</th><td>'+response.addrLine6+'</td>';
html += '</tr>';
html += '<th>Customer PostCode:</th><td>'+response.custPostCode+'</td>';
html += '</tr>';
$('#theDelivery').append(html);
}
})});
the code above works perfectly fine, however im now working to make this_id as a url parameter, so when the webpage is called along with a valid 16th digit number as a substring, it will return the contents of the objects that i am trying to access from this webservice.
How exactly is it done? i have attempted to do this in the code below, but no luck.
<script type="text/javascript">
function getthisId(this_id){
$.support.cors = true;
$.ajax({
type: "get",
url: 'https://thisservice/delivery/'+this_id,
dataType: "json",
cache: false,
data: { this_id },
success: function (response) {
console.log(response);
var html = '';
html += '<tr>';
html += '<th>Customer Name: </th><td>'+response.custName+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line1:</th><td>'+response.addrLine1+'</td>';
html += '</tr>';
html += '<tr>';
html += '<th>Address Line2:</th><td>'+response.addrLine2+'</td>';
html += '</tr>';
html += '<th>Address Line3:</th><td>'+response.addrLine3+'</td>';
html += '</tr>';
html += '<th>Address Line4:</th><td>'+response.addrLine4+'</td>';
html += '</tr>';
html += '<th>Address Line5:</th><td>'+response.addrLine5+'</td>';
html += '</tr>';
html += '<th>Address Line6:</th><td>'+response.addrLine6+'</td>';
html += '</tr>';
html += '<th>Customer PostCode:</th><td>'+response.custPostCode+'</td>';
html += '</tr>';
$('#theDelivery').append(html);
}
});
}
$(document).ready(function () {
getthisId(this_id);
});
this error occurs:
Uncaught ReferenceError: this_id is not defined
at HTMLDocument.<anonymous> (1032987988503654:59)
at i (jquery-1.12.3.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.12.3.min.js:2)
at Function.ready (jquery-1.12.3.min.js:2)
at HTMLDocument.K (jquery-1.12.3.min.js:2)
im very new to this, any help would be great :)

The server side is expecting the value in a parameter named parcel_id, so you need to provide that as the key in the object you provide to data, like this:
data: { parcel_id: this_id },

you should do like this
'https://thisservice/delivery/?id='+this_id

Related

Downloading CSV contents via Ajax and PHP

I am trying to download CSV contents via PHP script hosted on the server.
This is the jquery code that executes and creates a table:
$(document).ready(function() {
$("#btnSubmit").click(function(){
$.ajax({
type: 'GET',
url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
data: null,
success: function(text) {
var fields = text.split(/\n/);
fields.pop(fields.length-1);
var headers = fields[0].split(','),
html = '<table>';
html += '<tr>';
for(var i = 0; i < headers.length; i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for(var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
Contents of get-csv.php file:
<?php
header('Content-Type: text/plain');
$csv = file_get_contents('http://mydomaincom/wp-content/uploads/csv-samples.csv');
echo $csv;
?>
Here is the code for button:
<!-- Begin Button -->
<div class="demo">
<input id = "btnSubmit" type="submit" value="Get It"/>
</div>
<!-- End Button -->
From browser:
I can access http://mydomaincom/wp-content/uploads/get-csv.php - no issues
I can access http://mysitecom/wp-content/uploads/csv-samples.csv - no issues
When I click on button nothing happens.
Thanks
Below I tried to put together a working snippet where you can possibly see how it works when it works ...
$(document).ready(function () {
$("#btnSubmit").click(function () {
$.ajax({
type: 'GET',
// url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
// url: 'https://jsonplaceholder.typicode.com/users', // --> JSON
url: "https://data.cdc.gov/api/views/45um-c62r/rows.csv",
data: null,
success: function (text) {
var fields = text.split(/\n/);
fields.pop(fields.length - 1);
var headers = fields[0].split(','), html = '<table>';
html += '<tr>';
for (var i = 0; i < (headers.length,3); i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for (var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmit">get data</button>
After looking around a bit further I did actually find some publicly available CSV data ("Rates of TBI-related Emergency Department Visits, Hospitalizations, and Deaths - United States, 2001 – 2010" from the U.S. Department of Health & Human Services) and I am now using that to demonstrate the AJAX process.
So, your code basically works. It could be simplified of course but that is not the point. I guess that the problems you encounter with your site are probably CORS-related.

Web page content not shownig after JQuery loading

Above code generate HTML table using JSON output.
But, my problem is, after this JQuery runs, other page content is not shown.
<script>
$(document).ready(function () {
var html = '<table class="table table-striped">';
html += '<tr>';
var flag = 0;
var data2 = <?php echo $data; ?>;
$.each(data2[0], function(index, value){
html += '<th>'+index+'</th>';
});
html += '</tr>';
$.each(data2, function(index, value){
html += '<tr>';
$.each(value, function(index2, value2){
html += '<td>'+value2+'</td>';
});
html += '<tr>';
});
html += '</table>';
$('body').html(html);
console.log(html);
});
</script>
when the page loads, content should disappear and it should shows particular table only.
change this
$('body').html(html);
with
$('body').append(html);
Probably cause is
$('body').html(html);
Because html() method will change the content of body elements. You should use
$('body').append(html);
to insert content at the end of body elements.
you miss : html += '</tr>';
please check with full code
<script>
$(document).ready(function () {
var html = '<table class="table table-striped">';
html += '<tr>';
var flag = 0;
var data2 = <?php echo $data; ?>;
$.each(data2[0], function(index, value){
html += '<th>'+index+'</th>';
});
html += '</tr>';
$.each(data2, function(index, value){
html += '<tr>';
$.each(value, function(index2, value2){
html += '<td>'+value2+'</td>';
});
html += '</tr>';
});
html += '</table>';
$('body').html(html);
console.log(html);
});
</script>

Got runtime error when coding in my apache tomcat

I'm trying to show my data from my MongoDB to my html. The data was in the MongoDB, but it won't show on my html. My code:
$(document).ready(function(){
$( "#buttonlogin" ).click(function(){
masuklogin();
});
});
function masuklogin(){
var formdata = {
nomortelp : $("#nomortelp").val(),
password : $("#password").val()
};
var Jformdata = JSON.stringify(formdata);
console.log(Jformdata);
$.ajax({
url : "/Dompetku/BankMasuk",
context : document.body,
}).done(function (response){
console.log(response);
console.log("ini kerja");
var table = "";
table += "<table class = 'table'> ";
table += "<thread>";
table += "<tr>";
table += "<th>" + "Username" +"</th>";
table += "<th>" + "Password" +"</th>";
table += "<tr>";
table += "<thread>";
response.forEach(function(BankSinarmas) {
table += "<tr>";
table += "<th>" + BankSinarmas.nomortelp; +"</th>";
table += "<th>" + BankSinarmas.password; +"</th>";
table += "<tr>";
});
table += "</table>";
$(".initable").html(table);
});
}
And my error goes through like this:
index.js:3 Uncaught ReferenceError: masuk is not defined(anonymous function) # index.js:3dispatch # jquery-3.0.0.min.js:5q.handle # jquery-3.0.0.min.js:5
Doesn't it suppose to read masuklogin() function instead of masuk() function?
Thanks before and I hope you guys can help me.

Binding eventhandlers in a for-loop

I am creating html-elements in a loop, and want to attach event-handlers to some of the elements. This handlers need to know the id of the element that fired the event, so I added the elements id's as a parameter of the binded function, but anyway what element I click at the end, the function always received the id of the last element, not of the element that I clicked.
Here is the code (more simplified version in the next code-block) (I'm using jQuery, but this is not a jQuery-problem, just a JavaScript-problem)
receiveObjects = function (JSONobj, StatusString, jqXHR) {
var html, i, el;
// error-handling is not shown here
html = '<table>';
for (i = 0; i < JSONobj.list.length; i++) {
el = JSONobj.list[i];
html += '<tr>';
html += '<td class="td1" id="td1'+el.itemID+'">';
html += '<table>';
html += '<tr>';
html += '<td><img id="up9x'+el.itemID+'" src="pics/arrowUp9.png" alt="" style="width:25px;height:66px;"></td>';
html += '<td><img id="up3x'+el.itemID+'" src="pics/arrowUp3.png" alt="" style="width:25px;height:66px;"></td>';
html += '<td><img id="up1x'+el.itemID+'" src="pics/arrowUp1.png" alt="" style="width:25px;height:66px;"></td>';
html += '</tr>';
html += '<tr>';
html += '<td><img id="down9x'+el.itemID+'" src="pics/arrowDown9.png" alt="" style="width:25px;height:66px;"></td>';
html += '<td><img id="down3x'+el.itemID+'" src="pics/arrowDown3.png" alt="" style="width:25px;height:66px;"></td>';
html += '<td><img id="down1x'+el.itemID+'" src="pics/arrowDown1.png" alt="" style="width:25px;height:66px;"></td>';
html += '</tr>';
html += '<tr>';
html += '<td colspan="3">';
html += '<div><button id="delete'+el.itemID+'" name="delete'+el.itemID+'" value="delete'+el.itemID+'">delete</button></div>';
html += '<div id="saveDiv'+el.itemID+'" style="display:none;">';
html += '<button id="save'+el.itemID+'" name="save'+el.itemID+'" value="save'+el.itemID+'">save</button>';
html += '</div>';
html += '</td>';
html += '</tr>';
html += '</table>';
html += '</td>';
html += '<td class="td2" id="td2'+el.itemID+'">';
html += '<table>';
html += '<tr>';
html += '<td>Titel </td>';
html += '<td>';
html += '<input class="grau" type="text" id="inTitel'+el.itemID+'" size="30" maxsize="50" value="'+el.Titel+'">';
html += '</td>';
html += '</tr>';
html += '<tr>';
html += '<td>ET</td>';
html += '<td>';
html += '<input class="grau" type="text" id="inET'+el.itemID+'" size="20" maxsize="30" value="'+el.ET+'">';
html += '</td>';
html += '</tr>';
html += '<tr>';
html += '<td>Text </td>';
html += '<td>';
html += '<textarea class="grau" id="inText'+el.itemID+'" rows="4" cols="30">'+el.Text+'</textarea>';
html += '</td>';
html += '</tr>';
html += '</table>';
html += '<button id="loadPdf'+el.itemID+'" name="loadPdf'+el.itemID+'" value="loadPdf'+el.itemID+'">upload pdf</button>';
html += '</td>';
html += '<td class="td3" id="td3'+el.itemID+'">';
html += '<img src="'+el.pic+'">';
html += '<div>';
html += '<button id="newPic'+el.itemID+'" name="newPic'+el.itemID+'" value="newPic'+el.itemID+'">create pic from pdf</button> ';
html += '</div>';
html += '</td>';
html += '</tr>';
}
html += '</table><div class="ErrorMsg" id="changeRedError"></div>';
$('#workBlock').html(html);
//after the elements are inserted into the dom, the eventhandlers should be binded:
for (i = 0; i < JSONobj.list.length; i++) {
el = JSONobj.list[i];
$('#up9x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,-9);})
$('#up3x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,-3);})
$('#up1x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,-1);})
$('#down9x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,9);})
$('#down3x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,3);})
$('#down1x'+el.itemID).on('click',function(){evHd.clickMove(el.itemID,1);})
$('#delete'+el.itemID).on('click',function(){evHd.clickDelete(el.itemID);})
$('#save'+el.itemID).on('click',function(){evHd.clickSave(el.itemID);})
$('#inTitel'+el.itemID).on('change keyup paste mouseup',function(){evHd.changed(el.itemID);})
$('#inET'+el.itemID).on('change keyup paste mouseup',function(){evHd.changed(el.itemID);})
$('#inText'+el.itemID).on('change keyup paste mouseup',function(){evHd.changed(el.itemID);})
$('#loadPdf'+el.itemID).on('click',function(){evHd.clickLoadPdf(el.itemID);})
$('#newPic'+el.itemID).on('click',function(){evHd.clickNewPic(el.itemID);})
}
}
The problem must be located in the way how I attach the id (el.itemID) to the event-handler function. Simplified:
for (i = 0; i < 500; i++) {
el = JSONobj.list[i];
$('#prefix'+i).on('click',function(){
handler(i); //this seems to be problematic
})
}
I think I know where the problem is, but I have no idea how to solve it. Can you help, please?
This is a very common mistake, due to JavaScript's concept of closures (function plus pointers to all the variables outside the function that have been referenced in the function body). You can solve this with an IIFE (immediately invoked function expression):
for (i = 0; i < 500; i++) {
(function(num) {
$('#prefix' + num).on('click',function() {
handler(num);
})
})(i);
}
This immediately invoked function will create a new scope and thus have the correct i saved in num. Otherwise, JavaScript's closure (the function keeps a pointer on i and thus always references 500 after the for loop ended) will mess with your event handlers.

jquery remove everything after space

I am trying to remove everything in my string after space like so:
value.baseOrSchedStartList[i].substring(0, value.baseOrSchedStartList[i].indexOf(' '))
But I get this error:
Uncaught TypeError: Cannot read property 'substring' of undefined
What am I doing wrong ? This is inside an ajax call...here is the full ajax call:
$.ajax({
type: "GET",
url: "/vendorProject/api/connection/getVendorItems?community=" + $("#communtiyDropdown").val(),
dataType: 'json',
cache: false,
success: function (results) {
var html;
html = "<table border='1'>";
html += "<tr>";
html += "<th>Task</th>";
$.each(results, function (key, value) {
html += "<th>" + key + "</th>";
});
html += "<th></th>";
html += "</tr>";
for (i = 0; i < taskArray.length; i++) {
html += "<tr>"
html += "<td>" + taskArray[i] + "</td>";
$.each(results, function (key, value) {
html += "<td>" + value.baseOrSchedStartList[i].substring(0, value.baseOrSchedStartList[i].indexOf(' ')) + "</td>";
});
html += "<td><input type='checkbox' name='checkbox' id='checkbox' /></td>"
html += "</tr>";
}
html += "</table>";
$("#tableData").html(html);
}
});
The string in question is 12-12-2015 08:00:00 AM and I looking for 12-12-2015....no time.
Try to substr :)
$("button").on("click",function(){
var a = $("input").val();
var cropped = a;
if(a.indexOf(" ")>=0) cropped = a.substr(0,a.indexOf(" "));
$("b").html(cropped);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' placeholder='write something here and hit the button' style='width:60%;'>
<br>
<button>Ready!</button>
<br>
<div>
The result without space and after all : <b></b>
</div>

Categories

Resources