I am a complete newbie to programming and am working on a sample project. I am trying to send an AJAX request to Apple to get a video from a user-defined artist. However, I don't get any data returned to my function and nothing shows up in the console.
Index.php
<!DOCTYPE html>
<html>
<head>
<title>iTunes Video Search</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function() {
$.post($(this).attr('action'), $(this).serialize(), function(res) {
var htmlStr = '';
if (res.results.length !== 0) {
htmlStr += "<video controls src='" + res.results[0].previewUrl + "'></video>";
} else {
htmlStr += "Not Found";
}
$('#video').html(htmlStr);
}, 'json');
return false;
});
});
</script>
</head>
<body>
<h2>Enter Artist's Name</h2>
<form action="/videos/create" method="post">
<input type="search" name="artist_name" id="artist_name">
<input type="submit" value="Search">
</form>
<div id="video"></div>
</body>
</html>
Videos.php
<?php
class Videos extends CI_Controller {
public function index() {
$this->load->view('index');
}
public function create() {
$artist_name = str_replace(' ', '', $this->input->post('artist_name'));
$url = "https://itunes.apple.com/search?term=" . $artist_name . "&entity=musicVideo";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo $data;
}
}
?>
Any help is greatly appreciated!
Related
I'm making an auto SMS system. But SMS provider gave me post method form but I want it to modify with curl command by my own.
they provided me
<head>
<title>SMS</title>
</head>
<body>
<form name="sms" method="post" >
<input type="text" placeholder="send to number" name="to" /><br />
<input type="textarea" placeholder="sms" name="msg" /><br />
<input type="submit" value=" OK " />
</form>
<?php
$apikey='$2y$10$t..Yr.YDG0kXYiuLwQ78OecDgz6/qh.1xSWx77mXjczkk3AEKvTZe';
if (isset($_POST["msg"]) ) {
$sendto = $_POST["to"];
$fullNumber = '880' . substr(preg_replace('/\D/', '', $sendto), -10);
$msg = urlencode($_POST["msg"]);
// $masking='CITY PORTER';
// $masking=urlencode($masking);
// masking $url='http://example.com/smsapi/masking?api_key='.$apikey.'&smsType=text&maskingID='.$masking.'&mobileNo='.$fullNumber.'&smsContent='.$msg.'';
$url='http://example.com/smsapi/non-masking?api_key='.$apikey.'&smsType=text&mobileNo='.$fullNumber.'&smsContent='.$msg.'';
if ( !empty($_POST["to"]) && !empty($_POST["msg"])) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL =>$url,
CURLOPT_USERAGENT =>'My Browser'
));
$resp = curl_exec($curl);
echo $resp;
curl_close($curl);
}
else
{ echo "Field is empty";}
}
?>
</body>
I converted it to curl command but this is not still working. I just want to input multiple value without is set() 1 value.
$api_key = "$2y$10$mtW.yfKj18i2mTPe/0iCEuKdCfCGh9zOYYEU9AmnMrJyBb.h7fVcG";
$number = $row[mailing_no];
$message = "Dear Guardian, ". $row[name] . " has swiped his card right now";
$type= "text";
$params = array('api_key'=>$api_key, 'smsType'=>$type, 'mobileNo'=>$number, 'smsContent'=>$message);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/smsapi/non-masking?".http_build_query($params, "", "&"));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "Accept:application/json"));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close ($ch);
Try this i hope your problem will be solve
<div id="send_reply"></div>
<form name="sms" method="post" >
<input type="text" placeholder="send to number" name="to" id="phone" /><br />
<input type="textarea" placeholder="sms" name="msg" id="mess" /><br />
<input type="submit" value=" OK " id="send_btn" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#send_btn").click(function(){
var txt1=$("#phone").val();
var txt2=$("#mess").val();
$.ajax({
url : 'check.php',
method : 'GET',
data : {txt1:txt1,txt2:txt2},
success:function(dda){
$("#send_reply").html(dda);
}
});
});
});
</script>
I think we were missing double quotes for $row keys, try this:
$api_key = "$2y$10$mtW.yfKj18i2mTPe/0iCEuKdCfCGh9zOYYEU9AmnMrJyBb.h7fVcG";
$number = $row["mailing_no"];
$message = "Dear Guardian, ". $row["name"] . " has swiped his card right now";
$type= "text";
$params = array('api_key'=>$api_key, 'smsType'=>$type, 'mobileNo'=>$number, 'smsContent'=>$message);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/smsapi/non-masking?".http_build_query($params, "", "&"));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "Accept:application/json"));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close ($ch);
I am trying to connect to a web service with cURL and PHP. This is my code, along with the form for the user input.:
<?php
if (isset($_POST['submit'])) {
date_default_timezone_set('Europe/Sofia');
$hotelID = 1;
$userName = 'admin';
$password = 'admin';
$url = 'http://serviceurl.com/someservice/freerooms.svc';
$requestTime = date('d.m.Y H:m:s');
$tempFromDate = date_create($_POST['fromDate']);
$tempToDate = date_create($_POST['toDate']);
$fromDate = date_format($tempFromDate, 'd.m.Y H:m:s' );
$toDate = date_format($tempToDate, 'd.m.Y H:m:s' );
$data = array(
'fromDate' => $fromDate,
'toDate' => $toDate,
'hotelID' => $hotelID,
'requestTime' => $requestTime,
'userName' => $userName,
);
$token = md5(md5($password . $requestTime));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
echo $token . '<br>';
echo curl_setopt($ch, CURLOPT_HTTPHEADER, array('Bearer: ' . $token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
$response = curl_exec($ch);
if (!$response) {
$error = curl_error($ch);
}
curl_close($ch);
$result = json_decode($response,true);
print_r($result);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Site</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div id="wrapper" class="col-md-10 col-md-offset-1" style="position: absolute; top: 40%; left: 20%;">
<div id="form-messages">
<?php
if(isset($error)) {
echo '<b>Error: </b>' . $error;
} else {
$error = null;
}
?>
</div>
<form action="" method="post" class="form-inline" id="form">
<div class="form-group">
<input type="date" name="fromDate" required>
</div>
<div class="form-group">
<input type="date" name="toDate" required>
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
</body>
</html>
Problem is, I don't have access to the service from the back end. All the person that maintains it has told me, is the format of the data that should be submitted, and that the response will be in JSON format. This is for hotel room reservation. I am told that I should submit the data in the headers along with the token. When I submit this code, I get an empty response, with an error, stating that the token is INVALID. It's the first time I've been working with cURL and RESTful services, so any help is welcome.
I am using a PHP script to push messages onto android devices via GCM. I have an html form that takes in a text input as the message and then pushes this message to the android device.
Now when i tried it with two separate fields 1. Excerpt 2. Message
My android device receives a null message.
I need to know where am I going wrong.
This is my HTML Form
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>User:</label> <span><?php echo $row["id"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="excerpt" cols="10" class="txt_excerpt" placeholder="Type excerpt here"></textarea>
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
This is the ajax Script
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
$('.txt_excerpt').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
This is the Send_message.php code
if (isset($_GET["regId"]) && isset($_GET["message"]) && isset($_GET["excerpt"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
$excerpt = $_GET["excerpt"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("news" => $message, "exc" => $excerpt);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
This is the GCM.php Code
public function send_notification($registatoin_ids, $message, $excerpt) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
This is the android GCMIntentService Code
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("news");
String excerpt = intent.getExtras().getString("exc");
Log.i("Received ->", excerpt+" "+message);
if(message!=null)
{
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
}
All I see on my device is a blank notification whenever I push a message from the server.
I get 'json is null' as error
My php file:
<?php
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$url='https://www.googleapis.com/urlshortener/v1/';
$key='ApiKey';
$result= $url.($query).$key;
$ch = curl_init($result);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
}
?>
My html:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// when the user clicks the button
$("button").click(function(){
$.getJSON("shortner.php?query="+$('#query').attr("value"),function(json){
$('#results').append('<p>Id : ' + json.id+ '</p>');
$('#results').append('<p>Longurl: ' + json.longurl+ '</p>');
});
});
});
</script>
</head>
<body>
<input type="text" value="Enter a place" id="query" /><button>Get Coordinates</button>
<div id="results"></div>
Edited :
<?php
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$url='https://www.googleapis.com/urlshortener/v1/';
$key='Api';
$key2='?key=';
$result= $url.$query.$key2.$key;
$requestData= json_encode($result);
echo var_dump($query);
$ch = curl_init($requestData);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
}
?>
Worked for me:
<?php
$ch = curl_init("https://www.googleapis.com/urlshortener/v1/url?key=MYAPIKEY&shortUrl=http://goo.gl/fbsS");
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$res = curl_exec($ch);
if (!$res)
var_dump(curl_error($ch)); else
echo "Yay! I've got JSON result!";
curl_close($ch);
?>
Still there is bit.ly service with similar but more powerful functions. Here is the example on how to use it (works just perfectly):
<?php
if (array_key_exists("url", $_GET) && $_GET["url"] != "")
{
$u_name = "YOUR BIT.LY USERNAME";
$u_apikey = "YOUR BIT.LY API KEY";
$f = fopen("http://api.bit.ly/v3/shorten?login=" . $u_name . "&apiKey=" . $u_apikey . "&longUrl=" . rawurlencode($_GET["url"]) . "&format=json", "r");
header("Content-Type: application/json");
ob_start();
echo stream_get_contents($f);
fclose($f);
ob_end_flush();
exit;
}
?>
<html>
<head>
<title>jCarousel Examples</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("[name=send]").click(function() {
$.getJSON("index.php?url=" + $('[name=url]').val(), function(f) {
$('[name=res]').append('<p>Shorten: ' + f.data.url + '</p><br/ >');
});
});
});
</script>
</head>
<body>
<input type="text" name="url" size="30" />
<input type="button" name="send" value="shorten!" />
<br /><div name="res"></div>
</body>
</html>
UPD: To get your bit.ly API Key, register on the bit.ly website and go to your account (in the top) -> Settings.
I have the following code, but it doesn't update my status (the username and password has been removed for this snippet) and it throws the error eeek. Any ideas why it's not working?
EDIT:
Apparently Twitter NEEDS OAuth instead now. I have been following this tutorial here: http://ditio.net/2010/06/07/twitter-php-oauth-update-status/
I have registered my App and copied both the Library and Tokens over.
BUT I'm not sure how to get this working with my current code, ie. what needs changing/adding/removing.
My Updated code:
<?php
function postToTwitter($username,$password,$message)
{
require_once 'TwitterOAuth.php';
define("CONSUMER_KEY", "???");
define("CONSUMER_SECRET", "???");
define("OAUTH_TOKEN", "???");
define("OAUTH_SECRET", "???");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('account/verify_credentials');
$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
// GET the API url via web authentication
// add 'status' param to send a message to Twitter
$host = "http://api.twitter.com/1/statuses/update.xml?status=".urlencode(stripslashes(urldecode($message)));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
// Go for it!!!
$result = curl_exec($ch);
// Look at the returned header
$resultArray = curl_getinfo($ch);
// close curl
curl_close($ch);
//echo "http code: ".$resultArray['http_code']."<br />";
if($resultArray['http_code'] == "200"){
echo "<br />OK! posted to http://twitter.com/".$username."/<br />";
} else {
echo "eek! yegads! error posting to Twitter";
}
// debug the result
// echo "<pre>";
// print_r($resultArray);
// echo "</pre><hr>";
// $sResult = htmlentities($result);
// $sResult = str_replace("><","><br /><",$sResult);
// echo "<pre>";
// print $sResult;
// echo "</pre>";
}
if(isset($_POST['submit']))
{
$textmessage = $_POST['message'];
postToTwitter("whiningwall","u0558234",$textmessage);
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=1024">
<title></title>
<link rel="stylesheet" type="text/css" href="master.css" media="screen" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<form id="post" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<label for="textArea">What's on your mind?</label>
<textarea id="textArea" name="message" maxlength="140"></textarea>
<div class="submit">
<span class="charsRemaining"></span>
<input type="submit" name="submit" value="Share" />
</div>
</fieldset>
</form>
<script type="text/javascript" src="jquery.maxlength.js"></script>
<script type="text/javascript">
$('#textArea').focus();
</script>
</body>
</html>
I believe that CURLOPT_USERPWD is for Apache's basic authentication, which Twitter does not use. I don't know much about the Twitter API but I think you'll be better off using OAuth to tell Twitter who you are.
Edit to add: There's GPL twitter library at http://code.google.com/p/php-twitter/ that you might try looking at (or even using).