How to get a response from another website using AJAX? - html

I have a problem about how to get a response from another website using php (api.php) but it works if api.php is placed in my folder where ( Index.php ) is also. Is it possible to get the responses from other pages like ( myurl.com/api.php ). Sorry for my bad english.
ajax placed from index.php
<script title="ajax do checker">
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
var ap = 0;
var rp = 0;
linhaenviar.forEach(function(value, index) {
setTimeout(
function() {
$.ajax({
url: 'api.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("#Aprovada")) {
removelinha();
ap++;
aprovadas(resultado + "");
}else {
removelinha();
rp++;
reprovadas(resultado + "");
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(rp);
$('#cLive').html(ap);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cDie2').html(rp);
}
});
}, 500 * index);
});
}
function aprovadas(str) {
$(".aprovadas").append(str + "<br>");
}
function reprovadas(str) {
$(".reprovadas").append(str + "<br>");
}
function removelinha() {
var lines = $("#lista").val().split('\n');
lines.splice(0, 1);
$("#lista").val(lines.join("\n"));
}
code where the response will appear
<h6 style="font-weight: bold;" class="card-title">Declined - <span id="cDie2" class="badge badge-danger">0</span></h6>
<div id="bode2"><span id=".reprovadas" class="reprovadas"></span>
api.php
enter link description here
full code for index.php enter link description here

Related

How change display value/color td based on JSON

I'm working on an app where I get a json via an ajax call. This json contains objects where you get a certain status code per extension (1 = online, 2, is ringing, 3 = busy)
How can I ensure that the value that I get back is converted to the text (preferably with a different color of the )
So when I get a 1 back I want it to show Online, and with a 2 Ring etc
$.ajax({
type:'GET',
url: url,
dataType: 'json',
error: function(jqXHR, exception) {ajax_error_handler(jqXHR, exception);},
success: function(data){
// console.log(JSON.parse(data.responseText));
// console.log(JSON.parse(data.responseJSON));
console.log(data['entry']);
var event_data = '';
$.each(data.entry, function(index, value){
/* console.log(data['entry']);*/
event_data += '<tr>';
event_data += '<td>'+value.extension+'</td>';
event_data += '<td>'+value.status+'</td>';
<!--event_data += '<td>'+value.registration+'</td>';-->
event_data += '</tr>';
});
$("#list_table_json").append(event_data);
},
error: function(d){
/*console.log("error");*/
alert("404. Please wait until the File is Loaded.");
}
});
Thanks in advance!
I have change the code
function get_blf() {
$.ajax({
type:'GET',
url: url,
dataType: 'json',
error: function(jqXHR, exception) {ajax_error_handler(jqXHR, exception);},
success: function(data){
$.each(data.entry, (index, value) => {
const tableRow = document.createElement('tr');
const tdExtension = document.createElement('td');
extension.textContent = value.status;
const tdStatus = document.createElement('td');
if (value.status == 3) status.textContent = 'Busy';
if (value.status == 2) status.textContent = 'Ringing';
if (value.status == 1) status.textContent = 'Online';
tdStatus.classList.add(`status-${value.status}`);
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
}
});
}
}
and add the css, but now i can't get any values back. but now i can't get any values back. (sorry I'm fairly new to javascript)
Please use the DOM API
One way of getting colors would be to use CSS classes for the status:
// js
...
$.each(data.entry, (index, value) => {
const tableRow = document.createElement('tr');
const tdExtension = document.createElement('td');
extension.textContent = value.extension;
const tdStatus = document.createElement('td');
if (value.status == 3) status.textContent = 'Busy';
if (value.status == 2) status.textContent = 'Ringing';
if (value.status == 1) status.textContent = 'Online';
tdStatus.classList.add(`status-${value.status}`);
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
});
...
// css
.status-1 {
color: green;
}
.status-2 {
color: red;
}
.status-3 {
color: orange;
}
I finally got the script working. I am now trying to build in a polling, however I see that the ajax call is executed again and the array is fetched. However, the table is not refreshed but a new table is added, does anyone know a solution for this?
code I'm using now for the repoll is
function repoll(poll_request, poll_interval, param=null) {
if (poll_interval != 0) {
if (window.timeoutPool) {
window.timeoutPool.push(setTimeout(function() { poll_request(param); }, poll_interval));
}
else {
setTimeout(function() { poll_request(param); }, poll_interval);
}
}
else {
log_msg('Poll cancelled.');
}
}
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdNr);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
});
repoll(get_blf, poll_interval_blf);

Database mapping in Leaflet with (JSON, AJAX)

I get this JSON from DeviceNewController
public function index(Request $request)
{
$device_new = Device_new::with(['device']);
return Device_new::all()->toJson();
}
And when I wrote AJAX in view blade, it show me data from DB in console.
<script>
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
console.log(newdev.responseText);
};
newdev.send();
</script>
But I need to pass it in Leaflet script and write all data on map (coordinates, markers, device info)
When I set all in one script, there is no data in console, I can not fix it.
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
var coordinates = newdev.responseText;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
};
};
newdev.send();
Did i make a mistake somewhere, is this correct???
You miss understood Ajax. Ajax is a function from JQuery, a JS library.
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
You have to add the JQuery library to your source, then you can create a Ajax call.
https://www.w3schools.com/jquery/ajax_ajax.asp
$.ajax({url: "/devices_new", success: function(result){
//result = JSON.parse(result); // If your result is not a json Object.
var coordinates = result;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
}
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
});
I make it on this way, and its working.
<script>
$(document).ready(function() {
$.ajax({
/* the route pointing to the post function */
url: '/device_new',
type: 'GET',
data: {
message: $(".getinfo").val()
},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function(data) {
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
</script>

Which method is best to pass data from view to controller codeigniter?

I am using codeigniter 3 and I am new for codeigniter. I want to ask that which method is more suitable to pass data from view to controller, using jquery or <form action="controller/method">
I am trying to pass data using jquery but it does not giving any response and no error will be shown. Jquery code is given:
function registration()
{
var txtemail = document.getElementById("email").value;
$.post("<?php echo site_url('Home/registration'); ?>", {checkEmail: txtemail, action: "registerUser"},
function(data) {
var result = data + "";
if (result.lastIndexOf("Success") > -1) {
} else {
var txtUser = document.getElementById("username").value;
var txtContact = document.getElementById("contact").value;
var txtEmail = document.getElementById("email").value;
var txtpincode = document.getElementById("pincode").value;
var txtCity = document.getElementById('city').value;
var txtState = document.getElementById('state').value;
var txtCountry = document.getElementById("country").value;
var txtPackage = document.getElementById("package").value;
var registerMstData = new Array();
registerMstData[0] = txtUser;
registerMstData[1] = txtContact;
registerMstData[2] = txtEmail;
registerMstData[3] = txtpincode;
registerMstData[4] = txtCity;
registerMstData[5] = txtState;
registerMstData[6] = txtCountry;
registerMstData[7] = txtPackage;
$.post("<?php echo site_url('Home/registration') ?>", {pageData: registerMstData, action: "save"},
function(data) {
var result = data + "";
window.alert(result);
})
.fail(function(req, status, err) {
console.error('Error : ' + err + " status : " + status + " request " + req.toString());
alert('Error : ' + err + " status : " + status + " request " + req.toString());
});
}
});
}
What I am doing wrong I don't understand? Please help.
I personally think that AJAX should be used for displays updates and form submissions should be done via a page reload.
a form submission is synchronous and it reloads the page.
an ajax call is asynchronous and it does not reload the page.
It all depends on how you want it to be
Update
For ajax, you can use
$.ajax({
url: 'your url',
data: {
format: 'json'
},
error: function(err) {
// handle error here
},
data: yourData
success: function(data) {
// handle success here
},
type: 'POST'
});

Fb graph api permissions aren't working

I am using facebook login and its graph api to list all images of user to my website and the following code is working fine only for me that is the administrator and owner of the facebook app, it is not working for anyother person when he logged in the website using facebook login.
Explanation of code: When user logged in, a function named testAPI is called which gets user basic information and then it makes another call to FB.API for permission access and then finally for getting pictures.
The permission parameter "res" gets nothing for anyother user, but its working for me(administrator).
heres the code:
<div id="fb-root"></div>
<script>
// Additional JS functions here
window.fbAsyncInit = function() {
FB.init({
appId : MY_APP_ID, // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
login();
} else {
login();
}
});
};
function login() {
FB.login(function(response) {
if (response.authResponse) {
testAPI();
} else {
// cancelled
}
},{scope:'user_photos',perms:'user_photos'});
}
var id;
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
console.log(response);
id=response.id;
var link='/'+ id + '/permissions?access_token=FB_GENERATED_ACCESS_TOKEN';
FB.api(link,function(res){
console.log("permissons: ",res);
link='/'+ id + '/photos?fields=images';
FB.api(link, function(response) {
//placing all pictures
for(var i=0;i<response.data.length;i++)
{
var img="<img src="+response.data[i].images[0].source+" class='small' />";
$("#images").append(img);
}
console.log(response);
});
});
});}
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script></body>
<fb:login-button autologoutlink='true'
perms='email,user_birthday,status_update,publish_stream'></fb:login-button>
<div id="images"></div>
I got your actual problem,
<fb:login-button autologoutlink='true'
perms='email,user_birthday,status_update,publish_stream'></fb:login-button>
You missing out here , user_photos permission. your javascript function is not calling because fb:login-button do all stuff by self. your new code should be :
<fb:login-button autologoutlink='true'
perms='email,user_birthday,status_update,publish_stream,user_photos'></fb:login-button>
Instead of
var link='/'+ id + '/permissions?access_token=FB_GENERATED_ACCESS_TOKEN';
FB.api(link,function(res){
console.log("permissons: ",res);
link='/'+ id + '/photos?fields=images';
FB.api(link, function(response) {
//placing all pictures
for(var i=0;i<response.data.length;i++)
{
var img="<img src="+response.data[i].images[0].source+" class='small' />";
$("#images").append(img);
}
console.log(response);
});
Try this:
FB.api('/me/permissions', function (response) {
console.log("permissons: ", res);
var perms = response.data[0];
if (perms.user_photos) {
FB.api('/me/photos?fields=images', function (response) {
//placing all pictures
for (var i = 0; i < response.data.length; i++) {
var img = "<img src=" + response.data[i].images[0].source + " class='small' />";
$("#images").append(img);
}
console.log(response);
} else {
// User DOESN'T have permission. Perhaps ask for them again with FB.login?
login();
}
});

jQuery - google chrome won't get updated textarea value

I have a textarea with default text 'write comment...'. when a user updates the textarea and clicks 'add comment' Google chrome does not get the new text. heres my code;
function add_comment( token, loader ){
$('textarea.n-c-i').focus(function(){
if( $(this).html() == 'write a comment...' ) {
$(this).html('');
}
});
$('textarea.n-c-i').blur(function(){
if( $(this).html() == '' ) {
$(this).html('write a comment...');
}
});
$(".add-comment").bind("click", function() {
try{
var but = $(this);
var parent = but.parents('.n-w');
var ref = parent.attr("ref");
var comment_box = parent.find('textarea');
var comment = comment_box.val();
alert(comment);
var con_wrap = parent.find('ul.com-box');
var contents = con_wrap .html();
var outa_wrap = parent.find('.n-c-b');
var outa = outa_wrap.html();
var com_box = parent.find('ul.com-box');
var results = parent.find('p.com-result');
results.html(loader);
comment_box.attr("disabled", "disabled");
but.attr("disabled", "disabled");
$.ajax({
type: 'POST', url: './', data: 'add-comment=true&ref=' + encodeURIComponent(ref) + '&com=' + encodeURIComponent(comment) + '&token=' + token + '&aj=true', cache: false, timeout: 7000,
error: function(){ $.fancybox(internal_error, internal_error_fbs); results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); },
success: function(html){
auth(html);
if( html != '<span class="error-msg">Error, message could not be posted at this time</span>' ) {
if( con_wrap.length == 0 ) {
outa_wrap.html('<ul class="com-box">' + html + '</ul>' + outa);
outa_wrap.find('li:last').fadeIn();
add_comment( token, loader );
}else{
com_box.html(contents + html);
com_box.find('li:last').fadeIn();
}
}
results.html('');
comment_box.removeAttr("disabled");
but.removeAttr("disabled");
}
});
}catch(err){alert(err);}
return false;
});
}
any help much appreciated.
I believe you should be using val() and not html() on a textarea.
On a side note, for Chrome use the placeholder attribute on the textarea. You won't need a lot of this code.
<textarea placeholder="Write a comment"></textarea>