Unable to send api key (authorisation token) in GET (JQUERY AJAX) - php

Using AJAX I am trying to initiate a GET request to a rest API. I am passing access token in the header. The whole setup is working very fine in the localhost (Xampp).
PHP code used in API is working fine as I have checked it with postman.
Then I tried it on a web host (000webhost.com) and I am getting 400 error. On further investigation I found that the api is returning "API Key is missing"
GET https://alientechno.000webhostapp.com/step_muzic/v1/get_owner_main_page?_=1519553873190 400 ()
<script>
var status = checkLoginStatus();
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (2*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
$(document).ready(function() {
//var api = getCookie("api_key");
//alert(api);
//if(status==true)
var api = getCookie("api_key");
$.ajax({
type:'GET',
url :'https://alientechno.000webhostapp.com/v1/get_owner_main_page',
result: "{}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
headers: {"Authorization": api},
success: function(result) {
var output="";
var output_school="";
for (var i in result.MF)
{
output+="<tr><td>" + result.MF[i].id + "</td><td>" + result.MF[i].name + "</td><td>" + result.MF[i].net_royalty +"</td><td>"+ result.MF[i].royalty_to_owner +"</td></tr>";
}
output+="<tr><td style='background-color:#aabb05;text-color:white;box-shadow:2px 2px;'>TOTAL</td><td></td><td style='background-color:#aabb05;color:white;'>"+result.total_mf_royalty+"</td><td style='background-color:#aabb05;color:white;'>"+result.total_mf_royalty_to_owner+"</td></tr>";
for(var i in result.Schools){
output_school += "<tr><td>" + result.Schools[i].id + "</td><td>" + result.Schools[i].name + "</td><td>" + result.Schools[i].credit+"</td><td>"+ result.Schools[i].debit+"</td><td>"+result.Schools[i].net_income+"</td><td>"+result.Schools[i].royalty_to_owner+"</td><td>"+result.Schools[i].royalty_other+"</td></tr>";
}
output_school+="<tr><td style='background-color:#aabb05;text-color:white;box-shadow:2px 2px;'>TOTAL</td><td></td><td style='background-color:#aabb05;color:white;'>"+result.total_school_credit+"</td><td style=''></td><td style=''></td><td style='background-color:#aabb05;color:white;'>"+result.total_school_royalty_to_owner+"</td><td style='background-color:#aabb05;color:white;'>"+result.total_school_royalty_other+"</td></tr>";
$('#mfTable').append(output);
$('#schoolTable').append(output_school);
},
error:function(exception){alert('Exeption:'+exception);}
//var tokenString = ;
});
});

Related

Jquery Scroll Loading All The Rows At Once And Should Only Load 5 At A Time

I am using the following script to load more, 5 rows at a time from the database, on scroll. All the rows are loading at once on scroll after the initial loads correctly. In realtime, the first 5 load. Then on scroll the last 14 load at once. Like it rushes to the end instead of incrementally loading 5 at a time. I use the same code for a load more button and it works fine. Same PHP file for both. No issue with that. Can anyone see why all the rows are being loaded on scroll instead of 5 at a time.
<script>
//SET NUMBER OF ROWS TO DISPLAY AT A TIME
rowsPerPage = 5;
$(document).ready(function() {
// GETTING DATA FROM FUNCTION BELOW
getData();
window.onscroll = function() {
if ($(window).scrollTop() >= $('#load-container').offset().top + $('#load-container').outerHeight() - window.innerHeight) {
$('#load-more').html('Loading...');
var rowID = Number($("#row-id").val());
var allCount = Number($("#count").val());
rowID += rowsPerPage;
if (rowID <= allCount) {
$("#row-id").val(rowID);
getData();
} else {
$('#load-more').html('End Of Data');
//$('#load-more').html('');
}
}
}
/* REQUEST DATA */
function getData() {
var rowID = $("#row-id").val();
var allCount = $("#count").val();
$('#load-more').html('Loading...');
$.ajax({
url: 'promotions/newest-load-scroll-data-invalid.php',
type: 'post',
data: {
rowID: rowID,
rowsPerPage: rowsPerPage
},
dataType: 'json',
success: function(response) {
setTimeout(function() {
loadData(response)
}, 1000);
},
});
}
/* LOAD DATA TO PAGE */
function loadData(data) {
var dataCount = data.length;
for (var i = 0; i < dataCount; i++) {
if (i == 0) {
var allCount = data[i]['allcount'];
$("#count").val(allCount);
} else {
var promoID = data[i]['promoid'];
var promoNameNewest = data[i]['promoname'];
var promoNameNewestVideo = data[i]['promoname'];
var promoRefNum = data[i]['promorefnum'];
var promoType = data[i]['promotype'];
var theBanner = data[i]['thebanner'];
var email = data[i]['email'];
var customerType = data[i]['customerType'];
if (email == "") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="visitor-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="visitor-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
if (customerType == "p") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="advertiser-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="advertiser-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
}
$('#load-more').html('Loading...');
}
}
});
</script>
I was able to utilize flags to make it work right with a couple other small changes. Appreciate the input, Taplar.

ajax function doesn't work when referred to from instagram

My function seems to return nothing for the destination element when the link is referred to from Instagram. It works fine if I directly visit the page.
function getTeamsByLeague(league) {
//console.log("League Set: " + league);
$.ajax({
url: "<?php echo SITE_BASE_URL; ?>json.php",
data: {method: "getteamsbyregion", league: league},
success: function (data) {
if (data && data.length > 0) {
$("#destination").empty();
var selected = "";
$.each(data, function (index, item) {
if (item.team == teamSelected) {
selected = " selected";
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
} else {
selected = "";
}
$("#destination").append('<option ' + selected + ' value="' + item.lat + ',' + item.lng + '">' + item.team + '</option>');
if (index == 0) {
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
}
});
}
},
type: "GET",
dataType: "json"
});
}

Unable to figure out why AJAX is not triggering

I am spinning my wheels trying to figure out what is wrong in my code below. The function identified by ".func2" is triggering just fine and doing what it is supposed to do. However while the ".func1" function is being triggered all right (that window.alert 'I am here' is showing up), that AJAX call in ".func1"is not triggering. The "func2_email.php .... " is not being invoked.
Both of these functions are being invoked from the same PHP page.
Any ideas why this is happening?
<script type="text/javascript">
$(function () {
$(“.func1").on("click", function () {
var fromEmail = $("#fromEmail").val();
var toEmail = $("#to_Email").val();
var transid = $("#refTransid").val();
var repid = $("#initiatedby").val();
var feed = $("#refFeed").val();
var message = $("#to_message").val();
var toName = $("#to_Name").val();
var shareid = $("#shareid").val();
// window.alert(“I am here”);
$.ajax({
type: 'GET',
url: “func2_email.php?fromEmail=" + fromEmail + "&toEmail=" + toEmail + "&toName=" + toName + "&message=" + message + "&shareId=" + shareid + "&transid=" + transid + "&repid=" + repid + "&feed=" + feed,
dataType: "html",
success: function (data) {
$("#msg").html("<p class='successmsg'>" + toName + " has been notified");
}
});
});
$(“.func2").on("click", function () {
var email = $(this).attr("email");
var userid = $(this).attr("userid");
var transid = $("#transid").val();
var repid = $("#repid").val();
var feed = $("#feed").val();
var name = $(this).text();
$.ajax({
type: 'GET',
url: “func1_email.php?userid=" + userid + "&feed=" + feed + "&transid=" + transid + "&repid=" + repid + "&email=" + email,
dataType: "html",
success: function (data) {
var scrollTop = $(document).scrollTop();
var top = parseInt(scrollTop+260);
$("#msg").html("<p class='successmsg'>" + name + " has been notified </p>");
}
});
});
});
</script>
Code for func2_email.php
<?php
session_start();
require_once("classes/autoload.php");
$db = new Database();
//$fromEmail = $_GET["fromEmail"]; // If client wants to use their internal user names
$fromEmail = "admin#mydomain.com"; //Central email address
$toEmail = $_GET["toEmail"];
$toName = $_GET["toName"];
$message = $_GET["message"];
$shareId = $_GET["shareId"];
$transid = $_GET["transid"];
$repid = $_GET["repid"];
$feed = $_GET["feed"];
$host = $db->getDbHost();
$companyname = $db->getFieldValue("companyname", "apphost", $host, "appsettings");
$body = "Dear ".$toName."," ."</br>".$message."</br>Please click on the link below to view the page”."displaytransaction.php?transid=".$transid."&id=".$shareId."&requestor=".$repid."&feed=".$feed."<br></br>Sincerely, </br>Customer Operations</br>".$companyname;
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "smtp.mailgun.org"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 2020; /
$mail->Username = “postmaster#mydomain.com"; // SMTP account username
$mail->Password = "d2e3d568bb45ea649661d86d6a553cf"; // SMTP account password
$mail->AddAddress($email);
$mail->SetFrom($fromEmail);
$mail->Subject = "Requesting you to join a live video sharing session on transaction #". $transid;
$mail->MsgHTML($body);
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
I've checked in my editor and tried to run this code in my local environment. Ajax call is made. Please try it, and than you can modify it according to your needs.
html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button class="func1 func2">test button</button>
<script type="text/javascript">
$(function () {
$(".func1").on("click", function () {
var fromEmail = 1;
var toEmail = 2;
var transid = 3;
var repid = 4;
var feed = 5;
var message = 6;
var toName = 7;
var shareid = 8;
$.ajax({
type: 'GET',
url: "func2_email.php?fromEmail=" + fromEmail + "&toEmail=" + toEmail + "&toName=" + toName + "&message=" + message + "&shareId=" + shareid + "&transid=" + transid + "&repid=" + repid + "&feed=" + feed,
dataType: "html",
success: function (data) {
$("#msg").html("<p class='successmsg'>" + toName + " has been notified");
}
});
});
$(".func2").on("click", function () {
var email = 11;
var userid = 12;
var transid = 13;
var repid = 14;
var feed = 15;
var name = 16;
$.ajax({
type: 'GET',
url: "func1_email.php?userid=" + userid + "&feed=" + feed + "&transid=" + transid + "&repid=" + repid + "&email=" + email,
dataType: "html",
success: function (data) {
var scrollTop = $(document).scrollTop();
var top = parseInt(scrollTop + 260);
$("#msg").html("<p class='successmsg'>" + name + " has been notified </p>");
}
});
});
});
</script>
</body>
</html>
func 1
<?php
echo '<h1>FUNC 1</h1>';
func 2
<?php
echo '<h1>FUNC 2</h1>';

passing parameters to a php from javascript

I've done this before but for some reason the parameters are being passed oddly.
I have a javascript function that I've used to pass parameters, I've ran some tests and in the function the variables are correct.
These are just a few snippets of the js that relate to the issue:
var tdes = document.getElementById("taskDescription1").value;
var tnam = document.getElementById("taskName1").value;
var shif = document.getElementById("shift1").value;
var ttyp = document.getElementById("taskType1").value;
var date = document.getElementById("datepicker").value;
var ooc = document.getElementById("ooc1").value;
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
xmlhttp.open("GET","subTask.php?q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true);
I ran a web console and this is what is actually getting passed...
http://***************/****/********/subTask.php?taskName1=test+taskname+works&taskDescription1=test+des&shift1=All&ooc1=Open&taskType1=normal&datepicker=06%2F28%2F2013
I'm not sure what's going on in between the xmlhttp.open and the GET method in php. None of these variables are getting passed.
Why not use jQuery - very straightforward format (I prefer POST...):
$(document).ready(function() {
var tdes = $("#taskDescription1").val();
var tnam = $("#taskName1").val();
var shif = $("#shift1").val();
var ttyp = $("#taskType1").val();
var date = $("#datepicker").val();
var ooc = $("#ooc1").val();
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
$.ajax({
type: "POST",
url: "subTask.php",
data: "q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true),
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready()
Notice how easy the success callback function is to write... anything returned by subTask.php will be available within that function, as seen by the alert() example.
Just remember to include the jQuery library in the <head> tags:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
Also, add this line to the top of your subTask.php file, to see what is happening:
<?php
$q = $_POST["q"];
$w = $_POST["w"];
die("Value of Q is: " .$q. " and value of W is: " .$w);
The values of q= and w= will be returned to you in an alert box so that (at least) you can see what values they contained when received by subTask.php
Following script should help:
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
var ajax = ajaxObj("POST", "subTask.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
console.log( ajax.responseText )
}
}
ajax.send("u="+tdes+"&e="+tnam+ ...... pass all the other 'n' data );

Very basic PHP array issue

I am creating a form where the user selects check boxes of "services" that they might be interested in, then the form gets emailed to me. The problem is weather a box is checked or not, all of the results are being filled in. How do I properly do this?
There are about 25, but here is just a few:
$services = array();
if($_POST['master_planning']) {$services[] = "Master planning";}
if($_POST['snow_plowing']) {$services[] = "Snow plowing";}
if($_POST['fine_gardening']) {$services[] = "Fine Gardening";}
if($_POST['deer_protection']) {$services[] = "Deer Protection";}
$interested = implode(", ", $services);
I know it is a very basic thing, but I can't seem to solve it on my own
HTML is like:
<li><label for="planting"><input type="checkbox" name="planting" id="planting" value="x" /> Planting</label></li>
Ok, I figured (I think) out why all the values are returning true, even if the checkboxes arent clicked, now how do I solve it....
I guess I should of mentioned that this is page 2 of the form (process.php), the actual form is index.php, and I am using an ajax script to pass values.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var master_plan = $('input[name=master_plan]');
var front_foundation = $('input[name=front_foundation]');
var backyard_plan = $('input[name=backyard_plan]');
var specialty_garden = $('input[name=specialty_garden]');
var lawn_cutting = $('input[name=lawn_cutting]');
var lawn_plant_health_care = $('input[name=lawn_plant_health_care]');
var organic_property_care = $('input[name=organic_property_care]');
var seasonal_clean_ups = $('input[name=seasonal_clean_ups]');
var pruning = $('input[name=pruning]');
var fine_gardening = $('input[name=fine_gardening]');
var deer_protection = $('input[name=deer_protection]');
var snow_plowing = $('input[name=snow_plowing]');
var planting = $('input[name=planting]');
var walk = $('input[name=walk]');
var terrace = $('input[name=terrace]');
var wall = $('input[name=wall]');
var outdoor_kitchen = $('input[name=outdoor_kitchen]');
var fireplace = $('input[name=fireplace]');
var driveway = $('input[name=driveway]');
var fencing = $('input[name=fencing]');
var pergola = $('input[name=pergola]');
var swimming_pool = $('input[name=swimming_pool]');
var irrigation = $('input[name=irrigation]');
var lighting = $('input[name=lighting]');
var grading_drainage = $('input[name=grading_drainage]');
var newsletter = $('input[name=newsletter]');
var comments = $('textarea[name=comments]');
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&master_plan=' + master_plan.val()+
'&front_foundation=' + front_foundation.val()+
'&backyard_plan=' + backyard_plan.val()+
'&specialty_garden=' + specialty_garden.val()+
'&lawn_cutting=' + lawn_cutting.val()+
'&lawn_plant_health_care=' + lawn_plant_health_care.val()+
'&organic_property_care=' + organic_property_care.val()+
'&seasional_clean_ups=' + seasional_clean_ups.val()+
'&pruning=' + pruning.val()+
'&fine_gardening=' + fine_gardening.val()+
'&deer_protection=' + deer_protection.val()+
'&snow_plowing=' + snow_plowing.val()+
'&planting=' + planting.val()+
'&walk=' + walk.val()+
'&terrace=' + terrace.val()+
'&wall=' + wall.val()+
'&outdoor_kitchen=' + outdoor_kitchen.val()+
'&fireplace=' + fireplace.val()+
'&driveway=' + driveway.val()+
'&fencing=' + fencing.val()+
'&pergola=' + pergola.val()+
'&swimming_pool=' + swimming_pool.val()+
'&irrigation=' + irrigation.val()+
'&lighting=' + lighting.val()+
'&grading_drainage=' + grading_drainage.val()+
'&newsletter=' + newsletter.val() +
'&comments=' + encodeURIComponent(comments.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
if (html==1) {
$('.form').fadeOut('slow');
$('.done').fadeIn('slow');
} else alert('Sorry, unexpected error. Please try again later.');
}
});
return false;
});
});
</script>
Could this be why every result is displaying?
The check you have is incorrect. Lets assume you have this HTML code for the checkbox inside your form:
<input type="checkbox" name="master_planning" value="yes" />
Then on your PHP you want do the check like this:
if(isset($_POST['master_planning']) && $_POST['master_planning'] == 'yes'){
array_push($services, "Master planning"];
}
The function array_push adds the given element or elements at the end of the array, so that would be an easy way to "dynamically" populates an array.

Categories