I have the following JavaScript that sends parameters to a PHP file:
function getOutput()
{
$.ajax({
url:'myPHPFile.php',
data:{APIKey:$APIKey,Password:$APIPass,Alias:$Alias,DataCenter:$DataCenter},
type:'POST',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function ()
{
$('#output').html('Bummer: there was an error!');
}
});
return response.responseText;
}`
Which changes the following HTML to the output of the PHP file:
test
Here is the PHP
<?php
// echo nl2br("\nIntializing api.php \n");
// DATA SECTION
$APIKey = $_POST["APIKey"];
$APIPass = $_POST["Password"];
$AccountAlias = $_POST["Alias"];
$dataCenter = $_POST["DataCenter"];
$data = array(
"APIKey" => $APIKey,
"Password" => $APIPass,
);
$url_send = 'https://api.ctl.io/REST/Auth/Logon/';
$json_data = json_encode($data);
function sendPostData($url, $post, $cook = null){
// echo "Beginning sendPostData($url, $post, $cook)";
$ch = curl_init($url);
$headers= array('Accept: application/json','Content-Type: application/json');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if (!empty($cook))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json','Cookie:'.$cook));
}
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
};
$myresult = sendPostData($url_send, $json_data);
// print_r ($myresult);
$decodedresult = json_decode($myresult);
// print_r ($decodedresult);
'/reply-(.*?)-private/';
preg_match_all('/Tier3(.*?)path=/', $myresult, $matches);
$cookies = array();
foreach($matches[0] as $item)
{
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
$prefix = 'Tier3.API.Cookie=';
$cookie = implode(" ",$matches[0]);
// Call the customer server list
$data = array(
'AccountAlias' => $AccountAlias,
'Location' => $dataCenter
);
$data_url = 'https://api.ctl.io/REST/Server/GetAllServersForAccountHierarchy/';
$data_string = json_encode($data);
$dataResult = sendPostData($data_url,$data_string, $cookie);
print_r($dataResult);
return $dataResult;
`
How can I get the $dataResult PHP array into a javascript variable so I can parse it? It is a big JSON response from an API.
Thanks.
Ajax calls are (normally) asynchronous, this means that the return response.responseText; will be executed immediately and should even raise an error related to response being undefined.
You'll have the response in the complete event of the ajax call and is inside there where you should go on with the execution of the script. jQuery will parse the JSON automatically and response will be the resulting object.
At the other side, the PHP script should just print the result of json_encode() and nothing else in order for the response to be valid JSON.
Related
I am working on a signup form with an integrated v2 reCAPTCHA and I ran into the issue that when submitting the form which includes the reCAPTCHA, it is reloading the page. I have a php function to validate the reCAPTCHA:
if (isset($_POST['g-recaptcha-response'])) {
function CheckCaptcha($userResponse) {
$fields_string = '';
$fields = array(
'secret' =>'secret_key',
'response' => $userResponse
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}
$result = CheckCaptcha($_POST['g-recaptcha-response']);
if ($result['success']) {
echo 'Success!';
} else {
echo 'Error';
}
}
When the form submits it gives a POST variable g-recaptcha-response to the page it's on as there is no action attribute to the form
So, I need to get the POST request but I can't let the page reload because that would get rid of other data on the page.
I tried using event.preventDefault(); when the form is submitted, but that also prevented the form from submitting the POST variable.
I have no idea how I would get the POST variable through javascript because the reCAPTCHA is not actually an input.
But if there was a way to get the value of the reCAPTCHA through javascript, then I could use ajax to send the POST request to the function.
If you include the query strings in the script url:
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
then you can use grecaptcha.getResponse as it says in the google reCAPTCHA documentation:
https://developers.google.com/recaptcha/docs/display
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
<script type="text/javascript">
var verifyCallBack = function(response) {
alert(response);
};
var widgetId;
var onloadCallback = function() {
widgetId = grecaptcha.render('recaptcha', {
'sitekey' : 's',
'theme' : 'light'
});
}
</script>
<form>
<div id="recaptcha"></div>
<input type="submit" name="submit" value="submit">
</form>
$('form').submit(function(e) {
e.preventDefault();
var response = grecaptcha.getResponse(widgetId);
$.ajax({
url: 'validate_captcha.php',
type: 'POST',
data: {'g-recaptcha-response': response},
success: function(data) {
alert(data);
},
error: function(error) {
alert(error);
}
});
});
And then in validate_captcha.php:
<?php
if (isset($_POST['g-recaptcha-response'])) {
function CheckCaptcha($userResponse) {
$fields_string = '';
$fields = array(
'secret' => 'secret_key',
'response' => $userResponse
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}
$result = CheckCaptcha($_POST['g-recaptcha-response']);
if ($result['success']) {
echo 'success';
} else {
echo 'error';
}
}
?>
So now in your javascript, you can use the data variable inside success:function(data) in an if statement:
if(data == 'success') {
registerUser(name, email, password); // not a real function, just an example
}
Here is my code, I keep on getting the same error response.
"{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}"
I can't figure it out. I'm using Eloqua APIs to get basic information such as total number of accounts, landing pages, users, images, etc. It's weird because I tried the API on POSTMAN application and it did work perfectly Screenshot of postman response to the API
PHP
$objetos = array("data/accounts", "data/contacts", "assets/emails", "assets/landingPages", "assets/images", "assets/forms", "system/users", "assets/microsites", "assets/customObjects");
for ($i = 0; $i < 9; $i++){
$url = 'http://secure.p03.eloqua.com/API/REST/1.0/' . $objetos[$i] . '?count=1';
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
$headers = array(
'Content-type: application/json',
'Authorization: BASIC "MY TOKEN"'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() ."/EloquaApi_lvl1.cer");
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
$data[$i] = curl_exec($ch);
curl_close($ch);
}
echo json_encode($data);
?>
JS
function getObjetos(){
$.get("objetos.php", function (data) {
console.log(data);
}, "json").done(function (data) {
console.log(data);
// rest of my code
}
Console
console.log response (click for image)
Try changing the url http://secure.p03.eloqua.com/API/REST/1.0/ to https
Use https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=KEY
My full PHP code here
$data = array();
$data['siteUrl'] = 'https://example.com';
$data['urlList'][] = 'https://example.com/news/1';
$ch = curl_init('https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=KEY');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'charset=utf-8',
'HTTP/1.1'
),
CURLOPT_POSTFIELDS => json_encode($data)
));
$response = curl_exec($ch);
So my problem is that I need to update some data from other site, and for calling that data I have php function where is the URL as parameter. ..So in JS I create a function that is in cycle with setInterval where I call that php function with URL parameter where are data stored, but it always return the same data..(data is actually playing track on stream, so data changed every +- 3 minutes) Data changes only on refresh page (f5) ..but I need update that data in background ..
this is the PHP function
function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
$data = str_replace(",,","},",$data);
$data = str_replace("}}]}}","}]}}",$data);
$data = str_replace("]}}","}]}}",$data);
$data = str_replace(",}}","}}}",$data);
$data = str_replace("}}]}}","}]}}",$data);
return $data;
In js I call in setInterval cycle only console.log to show result of php function..
console.log(<?php echo (get_content("http://server1.internetoveradio.sk:8809/status-json.xsl"));?>["icestats"]["source"])
Well, yeah. The PHP only gets called once in this case, the one time you echo out the contents of get_content();
If you want to get the content over and over again, use XmlHTTPRequest to call a PHP file which then returns the the result of get_content();
jQuery implements ajax ( XmlHTTPRequest ) to do exactly that.
jQuery.ajax({
url: "http://path.to/your_script.php",
method: "get",
complete: function( response ){
console.log(response);
}
});
edit:
Create a new .php file and paste this:
<?php
function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
$data = str_replace(",,","},",$data);
$data = str_replace("}}]}}","}]}}",$data);
$data = str_replace("]}}","}]}}",$data);
$data = str_replace(",}}","}}}",$data);
$data = str_replace("}}]}}","}]}}",$data);
return $data;
}
echo get_content("http://server1.internetoveradio.sk:8809/status-json.xsl");
In your html, add this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery.ajax({
url: "http://path.to/your_script.php",
method: "get",
complete: function( response ){
console.log(response);
}
});
});
</script>
This is the most rudimentory version, but it should point you in the right direction hopefully.
I need to call a jquery function from a php while loop
my code
$msg_body = "Test%20SMS";
while($mobList = mysql_fetch_array($resSet))
{
$mobile = $mobList['mobile'];
if($mobile)
{
?>
<script>
$(document).ready(function()
{
var mob = <?php echo $mobile;?>;
var msgBody = <?php echo $msg_body;?>
var url = "http://example.com/abc.php?msg=TEXT&sendTo="+mob+"&message="+msgBody+"&method=sendMessage";
$.get( url, function( data )
{
alert( "SMS SEND to : "+mob );
});
});
</script>
<?php
}
}
it is running for one time, ie if more than one mobile numbers are there it will execute once and send one sms,
Alert is not working.
I used CURL,
now its OK
if($scm_mobile)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
}
I'm trying to build a domain availability checker.
My PHP code is the following:
<?php
$domain = $_GET["domname"];
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data('http://freedomainapi.com/?key=XXXXXXX&domain=' . $domain);
echo $returned_content;
?>
When called as such: /domchek.php?domname=google.com
The JSON output is:
{"status":"success","domain":"google.com","available":true}
The JQuery im using to call the script is as follows:
$.get("domchek.php?domname=google.com", {data: "available"}, function(json) {
$("html").html(json);
});
I just want to return the availability not the entire JSON output. I have tried json.availability and a number of other things but can't figure it out. Also if there is a better method for this than .get() please suggest it.
UPDATE:
$.getJSON("domchek.php?domname=google.com", function(json) {
$("html").html(json.status);
});
The above works as does returning json.domain but trying to return json.available - which I require returns nothing..
Change this line:
$("html").html(json);
to:
$("html").html(json.status);
UPDATE: to force the GET request data type to JSON, change to:
$.get("domchek.php?domname=google.com", {data: "available"}, function(json) {
$("html").html(json);
}, 'json');