I have a login form with recaptcha 3 script.
When user type his right details he login in successfully. But if he wrong the recaptcha doesn't allow him to try again and print my error: 'recaptcha_error(2)'
How can i fix it?
HTML - form + recaptcha script
<form id="login-form" action="#" >
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
<input type="hidden" name="action" value="validate_captcha">
<input type="text" name="email">
<input type="password" name="password">
<button type="submit">SEND</button>
</form>
<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('MY_SITE_KEY', {action:'validate_captcha'})
.then(function(token) {
// add token value to form
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
My php part (in my ajax file)
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
} else {
$captcha = false;
}
if (!$captcha) {
$msg = 'recaptcha_error(1)';
} else {
$secret = 'MY_SERVER_KEY';
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
);
$response = json_decode($response);
if ($response->success === false) {
$msg = 'recaptcha_error(2)';
}
}
how to Getting error when submitting a form by ajax to page msg.php
file 1 = msg.php
<?php
$id = $_SESSION['id'];
$touser = htmlspecialchars($_GET['iduser']);
$postid = htmlspecialchars($_GET['post']);
?>
<div id="send">
<div id="title">صندوق المحادثة</div>
<form id="my-form" method="post" enctype="multipart/form-data">
<textarea id="_text" name="text" required=""></textarea>
<input id="_from" name="from" type="hidden" value="<?php echo $id; ?>"/>
<input name="to" type="hidden" value="<?php echo $touser; ?>"/>
<input name="post" type="hidden" value="<?php echo $postid ?>" />
<div class="file">
<li>ملفات .zip فقط</li>
<input class="up" type="file" name="up" />
</div>
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token_madmoun']; ?>" />
<button class="submit">ارسال الان</button>
</form>
<script>
$( '#my-form' )
.submit( function( e ) {
$.ajax({
url: 'chat_a.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
document.getElementById("my-form").reset();
});
</script>
</div>
chat_a.php
<?php
include "config.php";
if(!$user->is_logged_in()){
header('Location: unregistered.php');
exit();
}
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token_madmoun']) {
$id = $_SESSION['id'];
$data = date('Y-m-d');
$time = time();
$post = htmlspecialchars($_POST['post']);
$to = htmlspecialchars($_POST['to']);
$file_name = $_FILES['up']['name'];
$file_size = $_FILES['up']['size'];
$FileType = pathinfo($file_name,PATHINFO_EXTENSION);
if(!empty($_POST['text'])){
if(empty($FileType)) {
$sqladdcontent = $db->prepare("INSERT INTO chat_a SET _from = :_from, _to = :_to, _post = :_post, _data = :_data, _time = :_time, _text = :_text");
$sqladdcontent->bindParam(':_from', $id);
$sqladdcontent->bindParam(':_to', $to);
$sqladdcontent->bindParam(':_post', $post);
$sqladdcontent->bindParam(':_data', $data);
$sqladdcontent->bindParam(':_time', $time);
$sqladdcontent->bindParam(':_text', htmlspecialchars($_POST['text']));
$sqladdcontent->execute();
}else {
if($FileType != "zip" && $FileType != "ZIP") {
$error = "<center><div id='no-ok'>قم برفع ملفات بصيغة .zip فقط</div></center>";
}else {
if ($file_size > 104857600) {
$error = "<div id='no'>ممنوع حجم الملف اكبر من 100 ميجا</div>";
}else {
$time_digit = time() . '_';
$new_file_name = $time_digit.'.zip';
move_uploaded_file($_FILES['up']['tmp_name'], "upload-msg/".$new_file_name);
$sqladdcontent = $db->prepare("INSERT INTO chat_a SET _from = :_from, _to = :_to, _post = :_post, _data = :_data, _time = :_time, _text = :_text, _file = :_file");
$sqladdcontent->bindParam(':_from', $id);
$sqladdcontent->bindParam(':_to', $to);
$sqladdcontent->bindParam(':_post', $post);
$sqladdcontent->bindParam(':_data', $data);
$sqladdcontent->bindParam(':_time', $time);
$sqladdcontent->bindParam(':_text', htmlspecialchars($_POST['text']));
$sqladdcontent->bindParam(':_file', $new_file_name);
$sqladdcontent->execute();
}
}
}
}
}
?>
how to Getting error when submitting a form by ajax to page msg.php
The name of the variable is the error = $error
collect errors in php script as $errors array, then finaly ouput it as JSON:
print json_encode($errors);
and process it in success event handler
<script>
$( '#my-form' )
.submit( function( e ) {
$.ajax({
url: 'chat_a.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(msg)
{
json = $.parseJSON(msg);
if (json.error[1] != "") //
$("#div-error-1").html(json.error[1]);
if (json.error[2] != "") //
$("#div-error-2").html(json.error[2]);
// and so on. Or you can use foreach construction. it will make code more universal
}
} );
e.preventDefault();
document.getElementById("my-form").reset();
});
</script>
I'm making a game and to use it, you must register. So I'm trying to append a username and password that has been entered into a form to my JSON file which looks like:
{
"LogIns":[
{
"Username":"mikehene",
"password":"123"
},
{
"Username":"mike",
"password":"love"
}
]
}
My PHP reads:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
array_push($json, $username, $password);
$jsonData = json_encode($json);
file_put_contents('logins.json', json_encode($json));
?>
AJAX:
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "reg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
}
HTML:
<fieldset>
<legend>Please register before playing</legend>
<form>
Username: <br>
<input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
Password: <br>
<input type="password" placeholder="Enter a password" id="password" name="password"><br>
<input type="submit" value="Submit" onclick="return checkLogin();">
</form>
</fieldset>
<div id="PHPid"><div>
<script>
var usernamePassed = '';
var userPassword = "";
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
userPassword = document.getElementById("password").value;
console.log(usernamePassed);
console.log(userPassword);
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "reg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
</script>
So for example if I inputted username: mike, password:123 into the HTML field it should update my json file but my json file is not changing.
I'm running it on localhost and I have checked the permissions, which are set to read and write for all users.
Any ideas why?
Thanks in advance
The problem here is that you are missing a closing brace } for your callAJAX() function.
Having looked at your developer console, you would have seen the following:
SyntaxError: missing } after function body
Fixed script code:
<script>
var usernamePassed = '';
var userPassword = "";
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
userPassword = document.getElementById("password").value;
console.log(usernamePassed);
console.log(userPassword);
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "reg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
}
</script>
- Using a code editor with bracket/brace matching, would have helped ;-)
You are already using one as pointed out in comments.
What I tested this with was:
<fieldset>
<legend>Please register before playing</legend>
<form>
Username: <br>
<input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
Password: <br>
<input type="password" placeholder="Enter a password" id="password" name="password"><br>
<input type="submit" value="Submit" onclick="return checkLogin();">
</form>
</fieldset>
<div id="PHPid"><div>
<script>
var usernamePassed = '';
var userPassword = "";
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
userPassword = document.getElementById("password").value;
console.log(usernamePassed);
console.log(userPassword);
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById("PHPid").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "reg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
}
</script>
and
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
array_push($json, $username, $password);
$jsonData = json_encode($json);
file_put_contents('logins.json', json_encode($json));
?>
I've just set up the new google recaptcha with checkbox, it's working fine on front end, however I don't know how to handle it on server side using PHP. I've tried to use the old code below but the form is sent even if the captcha is not valid.
require_once('recaptchalib.php');
$privatekey = "my key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
$errCapt='<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>';}
Private key safety
While the answers here are definately working, they are using a GET request, which exposes your private key (even though https is used). On Google Developers the specified method is POST.
For a little bit more detail: https://stackoverflow.com/a/323286/1680919
Verification via POST
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '[YOUR SECRET KEY]',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
Array Syntax: I use the "new" array syntax ( [ and ] instead of array(..) ). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).
Return Values: This function returns true if the user is valid, false if not, and null if an error occured. You can use it for example simply by writing if (isValid()) { ... }
this is solution
index.html
<html>
<head>
<title>Google recapcha demo - Codeforgeek</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<h1>Google reCAPTHA Demo</h1>
<form id="comment_form" action="form.php" method="post">
<input type="email" placeholder="Type your email" size="40"><br><br>
<textarea name="comment" rows="8" cols="39"></textarea><br><br>
<input type="submit" name="submit" value="Post comment"><br><br>
<div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
</form>
</body>
</html>
verify.php
<?php
$email; $comment; $captcha;
if(isset($_POST['email']))
$email=$_POST['email'];
if(isset($_POST['comment']))
$comment=$_POST['comment'];
if(isset($_POST['g-recaptcha-response']))
$captcha=$_POST['g-recaptcha-response'];
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == false)
{
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else
{
echo '<h2>Thanks for posting comment.</h2>';
}
?>
http://codeforgeek.com/2014/12/google-recaptcha-tutorial/
I'm not a fan of any of these solutions. I use this instead:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'secret' => $privatekey,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
]);
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
// Success
} else {
// failure
}
I'd argue that this is superior because you ensure it is being POSTed to the server and it's not making an awkward 'file_get_contents' call. This is compatible with recaptcha 2.0 described here: https://developers.google.com/recaptcha/docs/verify
I find this cleaner. I see most solutions are file_get_contents, when I feel curl would suffice.
Easy and best solution is the following.
index.html
<form action="submit.php" method="POST">
<input type="text" name="name" value="" />
<input type="text" name="email" value="" />
<textarea type="text" name="message"></textarea>
<div class="g-recaptcha" data-sitekey="Insert Your Site Key"></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
submit.php
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])){
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
//your site secret key
$secret = 'InsertSiteSecretKey';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success){
//contact form submission code goes here
$succMsg = 'Your contact request have submitted successfully.';
}else{
$errMsg = 'Robot verification failed, please try again.';
}
}else{
$errMsg = 'Please click on the reCAPTCHA box.';
}
}
?>
I have found this reference and full tutorial from here - Using new Google reCAPTCHA with PHP
I liked Levit's answer and ended up using it. But I just wanted to point out, just in case, that there is an official Google PHP library for new reCAPTCHA: https://github.com/google/recaptcha
The latest version (right now 1.1.2) supports Composer and contains an example that you can run to see if you have configured everything correctly.
Below you can see part of the example that comes with this official library (with my minor modifications for clarity):
// Make the call to verify the response and also pass the user's IP address
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess()) {
// If the response is a success, that's it!
?>
<h2>Success!</h2>
<p>That's it. Everything is working. Go integrate this into your real project.</p>
<p>Try again</p>
<?php
} else {
// If it's not successful, then one or more error codes will be returned.
?>
<h2>Something went wrong</h2>
<p>The following error was returned: <?php
foreach ($resp->getErrorCodes() as $code) {
echo '<tt>' , $code , '</tt> ';
}
?></p>
<p>Check the error code reference at <tt>https://developers.google.com/recaptcha/docs/verify#error-code-reference</tt>.
<p><strong>Note:</strong> Error code <tt>missing-input-response</tt> may mean the user just didn't complete the reCAPTCHA.</p>
<p>Try again</p>
<?php
}
Hope it helps someone.
To verify at server side using PHP. Two most important thing you need to consider.
1. $_POST['g-recaptcha-response']
2.$secretKey = '6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V';
$verifydata = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
$response= json_decode($verifydata);
If you get $verifydata true, You done.
For more check out this
Google reCaptcha Using PHP | Only 2 Step Integration
In the example above. For me, this if($response.success==false) thing does not work. Here is correct PHP code:
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--your_key--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
// everything is ok!
} else {
// spam
}
it is similar with mattgen88, but I just fixed CURLOPT_HEADER, and redefine array for it work in domain.com host server. this one doesn't work on my xampp localhost. Those small error but took long to figure out. this code was tested on domain.com hosting.
$privatekey = 'your google captcha private key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 'Content-Type: application/json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'secret' => $privatekey,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
// Success
echo 'captcha';
} else {
// failure
echo 'no captcha';
}
Here you have simple example. Just remember to provide secretKey and siteKey from google api.
<?php
$siteKey = 'Provide element from google';
$secretKey = 'Provide element from google';
if($_POST['submit']){
$username = $_POST['username'];
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$response = json_decode($response);
if($response->success){
echo "Verification is correct. Your name is $username";
} else {
echo "Verification failed";
}
} ?>
<html>
<meta>
<title>Google ReCaptcha</title>
</meta>
<body>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Write your name"/>
<div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div>
<input type="submit" name="submit" value="send"/>
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
Source Tutorial Link
V2 of Google reCAPTCHA.
Step 1 - Go to Google reCAPTCHA
Login then get Site Key and Secret Key
Step 2 - Download PHP code here and upload src folder on your server.
Step 3 - Use below code in your form.php
<head>
<title>FreakyJolly.com Google reCAPTCHA EXAMPLE form</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php
require('src/autoload.php');
$siteKey = '6LegPmIUAAAAADLwDmXXXXXXXyZAJVJXXXjN';
$secret = '6LegPmIUAAAAAO3ZTXXXXXXXXJwQ66ngJ7AlP';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$gRecaptchaResponse = $_POST['g-recaptcha-response']; //google captcha post data
$remoteIp = $_SERVER['REMOTE_ADDR']; //to get user's ip
$recaptchaErrors = ''; // blank varible to store error
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp); //method to verify captcha
if ($resp->isSuccess()) {
/********
Add code to create User here when form submission is successful
*****/
} else {
/****
// This variable will have error when reCAPTCHA is not entered correctly.
****/
$recaptchaErrors = $resp->getErrorCodes();
}
?>
<form autcomplete="off" class="form-createuser" name="create_user_form" action="" method="post">
<div class="panel periodic-login">
<div class="panel-body text-center">
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_user_name" required="">
<span class="bar"></span>
<label>Username</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_phone_number" required="">
<span class="bar"></span>
<label>Phone</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="password" autcomplete="off" class="form-text" name="new_user_password" required="">
<span class="bar"></span>
<label>Password</label>
</div>
<?php
if(isset($recaptchaErrors[0])){
print('Error in Submitting Form. Please Enter reCAPTCHA AGAIN');
}
?>
<div class="g-recaptcha" data-sitekey="6LegPmIUAAAAADLwDmmVmXXXXXXXXXXXXXXjN"></div>
<input type="submit" class="btn col-md-12" value="Create User">
</div>
</div>
</form>
</body>
</html>
In response to #mattgen88's answer ,Here is a CURL method with better arrangement:
//$secret= 'your google captcha private key';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.google.com/recaptcha/api/siteverify",
CURLOPT_HEADER => "Content-Type: application/json",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => FALSE, // to disable ssl verifiction set to false else true
//CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array(
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
));
$response = json_decode(curl_exec($curl));
$err = curl_error($curl);
curl_close($curl);
if ($response->success) {
echo 'captcha';
}
else if ($err){
echo $err;
}
else {
echo 'no captcha';
}
Check below example
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
function get_action(form)
{
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
else
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
</script>
<form autocomplete="off" method="post" action=submit.php">
<input type="text" name="name">
<input type="text" name="email">
<div class="g-recaptcha" id="rcaptcha" data-sitekey="site key"></div>
<span id="captcha" style="color:red" /></span> <!-- this will show captcha errors -->
<input type="submit" id="sbtBrn" value="Submit" name="sbt" class="btn btn-info contactBtn" />
</form>
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.