Display the results in the HTML - php

I am working on my code to fetch the data to output them in the HTML. I have got a problem with display the data in the html source outside of the PHP because I have received an error:
Warning: Invalid argument supplied for foreach() in /home/username/public_html/check_score.php on line 150
Here is the line 150:
foreach($score->rules AS $rule) {
echo '<div name="test-row" style="margin-top:-1px">
<div name="description" style="float: left; width:470px;">' . $rule->description . '</div>';
echo '<div name="scores" style="float: right">' . $rule->score . '</div>';
echo '</div><br><hr>';
}
Here is the full code:
<?php
if(isset($_POST['btn1']))
{
sleep(1);
$ch = curl_init('http://example.com/check_score');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$message = "hey chris";
$header = "Delivered-To: example#gmail.com
Received: by 2002:a0c:938a:0:0:0:0:0 with SMTP id f10csp5715121qvf;
Sun, 2 Dec 2018 06:07:45 -0800 (PST)
the long list of the header goes here...
Hey rob,
How you doing?";
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('email' => $header, 'options'=>'long')));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
$score = json_decode($response);
?>
<script type="text/javascript">
$(document).ready(function() {
$('#myModal').modal('show');
});
</script>
<?php
}
?>
<form action="" method="post">
<div class="container">
<div class="form-group">
<button name="btn1" id="btn1" type="submit" class="btn btn-primary btn-block button-size">Check for score
</button>
</div>
</div>
</form>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="height:600px;">
<div class="modal-header" style="margin-bottom: 10px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">SpamScore</h3>
</div>
<div class="modal-body" style="height: 77%;">
<?php
echo '<p><b>SpamScore points: <span id="bbb"></span>' . $score->score . '</b></p><hr>';
foreach($score->rules AS $rule) {
echo '<div name="test-row" style="margin-top:-1px">
<div name="description" style="float: left; width:470px;">' . $rule->description . '</div>';
echo '<div name="scores" style="float: right">' . $rule->score . '</div>';
echo '</div><br><hr>';
}
?>
</div><br>
<div class="modal-footer">
</div>
</div>
</div>
</div>
I have checked the results for the $score in the PHP which it show:
stdClass Object ( [success] => 1 [score] => 0.2 [rules] => Array ( [0] =>
stdClass Object ( [score] => 0.1 [description] => Message has a DKIM or DK
signature, not necessarily valid ) [1] => stdClass Object ( [score] => 0.1
[description] => DKIM or DK signature exists, but is not valid ) ) [report]
=> pts rule description ---- ---------------------- ------------------------
-------------------------- 0.1 DKIM_SIGNED Message has a DKIM or DK
signature, not necessarily valid 0.1 DKIM_INVALID DKIM or DK signature
exists, but is not valid )
When I have put the $score in the HTML, the results will show as empty.
It was working fine yesterday but today here it is not working. I dont really understand why the variable $score show as empty in the HTML when I can be able to fetch the data in PHP with no problem. I tried to find the answer on google but I can't find it anywhere.
Can you please help me with how I can be able to display the data in the HTML using the variable $score?
Thank you.

I just noticed something here. I'm not sure if it'll fix the error, but it may be a starting point. The first echoed line within your loop doesn't have a trailing semicolon:
foreach($score->rules AS $rule) {
echo '<div name="test-row" style="margin-top:-1px">
<div name="description" style="float: left; width:470px;">' . $rule->description . '</div>';
echo '<div name="scores" style="float: right">' . $rule->score . '</div>';
echo '</div><br><hr>';
}
Give this a shot:
foreach($score->rules AS $rule) {
echo '<div name="test-row" style="margin-top:-1px">;
<div name="description" style="float: left; width:470px;">' . $rule->description . '</div>';
echo '<div name="scores" style="float: right">' . $rule->score . '</div>';
echo '</div><br><hr>';
}

Your $score variable fill on form submit, So you can't allow to $score variable after form post in the modal view.
Can you try following code instead of your codes,
UPDATED
My answer is changed for correct solution.
curl.php;
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['submit'])
{
sleep(1);
$ch = curl_init('http://example.com/check_score');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$message = "hey chris";
$header = "Delivered-To: example#gmail.com
Received: by 2002:a0c:938a:0:0:0:0:0 with SMTP id f10csp5715121qvf;
Sun, 2 Dec 2018 06:07:45 -0800 (PST)
the long list of the header goes here...
Hey rob,
How you doing?";
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('email' => $header, 'options'=>'long')));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
} else {
$response = json_encode(array('success' => false));
}
echo $response;
exit;
?>
form.html;
<form action="" method="post">
<div class="container">
<div class="form-group">
<button name="btn1" id="btn1" type="submit" class="btn btn-primary btn-block button-size">Check for score
</button>
</div>
</div>
</form>
<script type="text/javascript">
$('form').on('submit', function(e){
e.preventDefault(0);
$.ajax({
url: 'curl.php',
data: {
submit: true
},
success: function(data) {
$('.modal-body').html('');
var data = JSON.parse(data);
console.log(data);
if(data.success){
$('#myModal').modal('show');
$('.modal-body').append('<p><b>SpamScore points: <span id="bbb"></span>' + data.score + '</b></p><hr>');
$.each(data.rules, function(key, value){
$('.modal-body').append('<div name="test-row" style="margin-top:-1px"><div name="description" style="float: left; width:470px;">' + value.description + '</div><div name="scores" style="float: right">' + value.score + '</div></div><br><hr>');
});
}
},
type: 'POST'
});
});
</script>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="height:600px;">
<div class="modal-header" style="margin-bottom: 10px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">SpamScore</h3>
</div>
<div class="modal-body" style="height: 77%;"></div><br>
<div class="modal-footer"></div>
</div>
</div>
</div>
I do not able to test above codes, but it's must be work.

Related

How do you use PHP and SQL to submit table data to another table

I have a table of flights and I am using a loop to print out the flights information along with a submit button, the button that is clicked is the data that is submitted, what is the best way to go about this as this does not work. It knows what button is clicked but the SQL is not performed to insert the data to my basket
<?php
$dbQuery=$db->prepare("select * from flights");
$dbQuery->execute();
$index = 1;
while ($dbRow=$dbQuery->fetch(PDO::FETCH_NUM)) {
echo "<div>".
"<div class=\"col-md-3 col-sm-6 hero-feature\">".
"<div class=\"thumbnail\">".
"<img src=\"img/aeroplane.png\" alt=\"\">".
"<div class=\"caption\">".
"<h3>$dbRow[1] to $dbRow[2]</h3>".
"<p>£$dbRow[3]</p>".
"<p>".
"<form method=\"post\" action=\"\">".
"<input type=\"hidden\" name=\"action\" value=\"submit\" />".
"<input type=\"submit\" class=\"btn btn-primary\" id=\"$index-submit\"type=\"submit\" name=\"submit\" value=\"$index\">".
"</form>".
"</p>".
"</div>".
"</div>".
"</div>".
"</div>";
if(isset($_POST['action'])){
//echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
$dbQuery=$db->prepare("insert into basket values (null, :userID, :flightTo to :flightFrom, :flightPrice, 'N')");
$dbParams = array('userID'=>$userID,'fightTo'=>$dbRow[1],'fightFrom'=>$dbRow[2],'flightPrice'=>$dbRow[3]);
$dbQuery->execute($dbParams);
}
$index++;
}
You repeated your insertion code in while loop, this doesn't look good, I just wrote an approach using ajax can solve your problem. you can follow this code, I have written it very clearly.
main page
<!-- generate html rows as your requirement in php -->
<div class="container">
<div class="row">
<div class="col1 col-md-1">test1</div>
<div class="col2 col-md-1">test2</div>
<div class="col3 col-md-1">test3</div>
<div class="col4 col-md-1">test4</div>
<div class="col-md-1"> <button type="button" class="use-address" >Save</button></div>
</div>
<div class="row">
<div class="col1 col-md-1">test5</div>
<div class="col2 col-md-1">test6</div>
<div class="col3 col-md-1">test7</div>
<div class="col4 col-md-1">test8</div>
<div class="col-md-1"> <button type="button" class="use-address" >Save</button></div>
</div>
<div class="row">
<div class="col1 col-md-1">test9</div>
<div class="col2 col-md-1">test10</div>
<div class="col3 col-md-1">test11</div>
<div class="col4 col-md-1">test12</div>
<div class="col-md-1"> <button type="button" class="use-address" >Save</button></div>
</div>
</div>
<script src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type="text/javascript">
$(document).ready(function(){
$(".use-address").click(function() {
var val1 = $(this).parent('div').parent('div').find('.col1').text();
var val2 = $(this).parent('div').parent('div').find('.col2').text();
var val3 = $(this).parent('div').parent('div').find('.col3').text();
var val4 = $(this).parent('div').parent('div').find('.col4').text();
$.ajax({
type:'POST',
url:'service.php',
data:{val1:val1,val2:val2,val3:val3,val4:val4,action:'saveData'},
success:function(response){
alert(response);
}
});
});
})
</script>
service.php
<?php
if($_POST['action'] == 'saveData'){
echo $_POST['val1'],", ",$_POST['val2'],", ",$_POST['val3'],", ",$_POST['val4'];
//write here your mysql insertion code and return successfull message
}

Firebase Cloud Messaging using PHP

I'm trying to use PHP to send a notification from my localhost server. But I cannot get it to work. I previously received curl error. I solved it. But now it doesn't yield any errors. I can successfully send notifications from the Firebase console.
I have created FirebaseCloudMessaging.php to send the messages using curl.
<?php
/**
* Created by PhpStorm.
* User: Isuru
* Date: 18/11/2016
* Time: 16:47
*/
class FirebaseCloudMessaging {
// this methods send messages to a single device
public function send($to, $message){
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// Send message to topic subscribers
public function sendToTopic($to, $message){
$fields = array(
'to' => '/topics/'. $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// Send push message to multiple devices
public function sendToMultipleDevices($registrationIds, $message){
$fields = array(
'to' => $registrationIds,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// CURL request to Firebase Platform
private function sendPushNotification($fields){
require_once __DIR__ . '/config.php';
// POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . FIREBASE_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);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
// Disable SSL Certificate Support temporary
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));
}else{
json_decode($result);
}
// Close connection
curl_close($ch);
return $result;
}
}
And PushNotification.php is a model class for the messages.
<?php
/**
* Created by PhpStorm.
* User: Isuru
* Date: 17/11/2016
* Time: 01:32
*/
class PushNotification{
// push message title, message and image
private $title;
private $message;
private $image;
// data payload
private $data;
// flag indicating whether to
// show the push notification
private $is_background;
function _construct(){
}
public function setTitle($title){
$this->title = $title;
}
public function setMessage($message){
$this->message = $message;
}
public function setImage($imageUrl){
$this->image = $imageUrl;
}
public function setDataPayload($data){
$this->data = $data;
}
public function setIsBackground($is_background){
$this->is_background = $is_background;
}
public function getPushNotification(){
$res = array();
$res['data']['title'] = $this->title;
$res['data']['is_background'] = $this->is_background;
$res['data']['message'] = $this->message;
$res['data']['image'] = $this->image;
$res['data']['payload'] = $this->data;
$res['data']['timestamp'] = date('Y-m-d G:i:s');
return $res;
}
}
Following index.php shows the form and process the form submission.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Firebase Cloud Messaging</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">
/*Panel tabs*/
.panel-tabs {
position: relative;
bottom: 30px;
clear: both;
border-bottom: 1px solid transparent;
}
.panel-tabs > li {
float: left;
margin-bottom: -1px;
}
.panel-tabs > li > a {
margin-right: 2px;
margin-top: 4px;
line-height: .85;
border: 1px solid transparent;
border-radius: 4px 4px 0 0;
color: #ffffff;
}
.panel-tabs > li > a:hover {
border-color: transparent;
color: #ffffff;
background-color: transparent;
}
.panel-tabs > li.active > a,
.panel-tabs > li.active > a:hover,
.panel-tabs > li.active > a:focus {
color: #fff;
cursor: default;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
background-color: rgba(255, 255, 255, .23);
border-bottom-color: transparent;
}
.input_width {
width: 520px;
}
</style>
</head>
<body>
<br>
<div class="container">
<?php
// Enabling error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
require_once __DIR__ . '/FirebaseCloudMessaging.php';
require_once __DIR__ . '/PushNotification.php';
$firebaseCloudMessaging = new FirebaseCloudMessaging();
$pushNotification = new PushNotification();
// optional payload
$payload = array();
// notification title
$title = isset($_GET['title']) ? $_GET['title'] : '';
// notification message
$message = isset($_GET['message']) ? $_GET['message'] : '';
// push type - single user / topic
$push_type = isset($_GET['push_type']) ? $_GET['push_type'] : '';
$pushNotification->setTitle($title);
$pushNotification->setMessage($message);
$pushNotification->setIsBackground(FALSE);
$pushNotification->setDataPayload($payload);
$json = '';
$response = '';
if ($push_type == 'topic') {
$json = $pushNotification->getPushNotification();
$response = $firebaseCloudMessaging->sendToTopic('news', $json);
} else if ($push_type == 'individual') {
$json = $pushNotification->getPushNotification();
$regId = isset($_GET['regId']) ? $_GET['regId'] : '';
$response = $firebaseCloudMessaging->send($regId, $json);
}
?>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="fl_window">
<br/>
<?php if ($json != '') { ?>
<label><b>Request:</b></label>
<div class="json_preview">
<pre><?php echo json_encode($json) ?></pre>
</div>
<?php } ?>
<br/>
<?php if ($response != '') { ?>
<label><b>Response:</b></label>
<div class="json_preview">
<pre><?php echo json_encode($response) ?></pre>
</div>
<?php } ?>
</div>
<div class="panel-heading">
<h3 class="panel-title">Firebase Cloud Messaging</h3>
<span class="pull-right">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="active">Single Device</li>
<li>Send To Topic 'News'</li>
</ul>
</span>
</div>
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<form class="pure-form pure-form-stacked" method="get">
<fieldset>
<div class="form-group">
<div class="input_width">
<input
class="form-control input-lg" type="text"
placeholder="Enter Firebase Registration ID" id="redId" name="regId"
placeholder="Enter Firebase Registration ID">
</div>
</div>
<div class="form-group">
<div class="input_width">
<input
class="form-control input-lg" type="title"
placeholder="Enter Title" id="title" name="title">
</div>
</div>
<div class="form-group">
<div>
<textarea class="input_width input-lg" rows="5" name="message" id="message"
placeholder="Notification message!"></textarea>
</div>
</div>
<div class="form-group">
<div>
<input name="include_image" id="include_image" type="checkbox"> Include
image
</div>
</div>
</fieldset>
<input type="hidden" name="push_type" value="individual"/>
<div class=" text-center">
<input type="submit" class="btn btn-primary" value="SUBMIT"/>
</div>
</form>
</div>
<div class="tab-pane" id="tab2">
<form class="pure-form pure-form-stacked" method="get">
<fieldset>
<div class="form-group">
<div class="input_width">
<input
class="form-control input-lg" type="text"
placeholder="Enter Title" id="title1" name="title"
placeholder="Enter Title">
</div>
</div>
<div class="form-group">
<div>
<textarea class="input_width input-lg" rows="5" name="message" id="message"
placeholder="Notification message!"></textarea>
</div>
</div>
<div class="form-group">
<div>
<input name="include_image" id="include_image" type="checkbox"> Include
image
</div>
</div>
</fieldset>
<input type="hidden" name="push_type" value="topic"/>
<div class=" text-center">
<input type="submit" class="btn btn-primary" value="Send to Topic Subscribers"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
And config.php stores the web API. Is there a way to debug the code? For example to check whether Google accepts my request? Any suggestion is appreciated.
Thank you!
Change your $fields array like this
$fields = array (
'registration_ids' => array (
$registrationIds
),
'notification' => array (
"title" => "Title here",
"text" => $message
));
It's work for me

User view count in yii

I created a button to generate a popup which shows some events.And past few days I was trying to show the count of users which visted the events.
I tried some of the extensions too...Like
Counter
pcviewcounter
etc,
But I need to store the ip address ,eventid and time in my database.
Can anyone please help me with this???
View for button
<div class="modal fade" id="detailsOffeEve" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>
<script>
function showdetails(id)
{ // alert(id);
$('#detailsOffeEve').load('<?php echo Yii::app()->baseUrl; ?>/offerEvents/popup/'+id);
}
</script>
And action popup
public function actionPopup($id)
{
//$this->render('/offerEvents/Details',array(
//'model'=>OfferEvents::model()->findByAttributes(array('id'=>$id)), ));
$OfferEventsList = OfferEvents::model()->findAllByAttributes(array('id' => $id));
foreach($OfferEventsList as $Listdata)
{ $titnw=$Listdata['title']; $details=$Listdata['description'];
$discountper=$Listdata['discountper']; $discountperamt=$Listdata['discountperamt'];
$strdaate=$Listdata['startdate']; $enddaate=$Listdata['enddate']; $evoftype=$Listdata['type']; }
$cmuserid=$Listdata['createdby'];
if($Listdata['createdby']==0){ $createdbyname="Admin"; } else { $createdbyname=$Listdata->company->companyname; }
$locationnw=$Listdata->location;
$offrimage=$Listdata->image;
if($offrimage!=""){ $imgUrls=$offrimage; } else { $imgUrls='image-not-available.png'; }
$infowinimgpaths='theme/images/OfferEvents/orginal/'.$imgUrls;
if (file_exists($infowinimgpaths)) { $infowinimgpathSrcs=Yii::app()->baseUrl.'/'.$infowinimgpaths; } else
{ $infowinimgpathSrcs=Yii::app()->baseUrl.'/theme/images/OfferEvents/image-not-available.png'; }
if (Yii::app()->user->id!='' && Yii::app()->user->id!=1){
$subcribeemailid=Yii::app()->user->email; $logsts=1;
$countsubscribe = Newsfeeds::model()->countByAttributes(array('emailid' => $subcribeemailid,'cuserid' => $cmuserid));
} else { $subcribeemailid=''; $countsubscribe=0; $logsts=0; }
$PopupdetailText='<div class="modal-dialog-1">
<div class="modal-content">
<div class="modal-header login_modal_header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="modal-title" id="myModalLabel">'.$titnw.' </h2>
</div>
<div class="container-1">
<div class="row">
<div class="col-sm-7 detail-text">
<h2 class="title"> ';
if($evoftype==0){ $PopupdetailText.='Offer Price: '.$discountperamt.'
<font style="font-size: 15px;">[ Up To '.$discountper.'% Discount ]</font>'; }
$PopupdetailText.='</h2><p>Details: </p>
<p>'.$details.'</p>
<p>Location: '.$locationnw.'</p>
<p>Expires in: '.$enddaate.'</p>';
if($countsubscribe==0){
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success btn-xs" Onclick="subcribefeed('.$logsts.','.$cmuserid.')" >Subscribe NewsFeed</button></p>';
} else {
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success disabled btn-xs" >Already Subscribed NewsFeed</button></p>';
}
$PopupdetailText.='<div class="form-group" id="subcribefrm" style="display:none;background-color: #eee; padding: 12px; width: 82%;">
<input type="text" id="subemailid" placeholder="Enter EmailID here" value="'.$subcribeemailid.'" style="width: 100%;" class="form-control login-field">
<br/>
Subscribe Feeds </div> ';
// if($evoftype==0){ $PopupdetailText.='<p>Offer Price:<b> $'.$discountperamt.'</b></p>'; }
$PopupdetailText.='<p>';
$PopupdetailText .= $this->renderPartial('/comments/share', array('postid' => $id),TRUE);
$PopupdetailText.='<img src="'.Yii::app()->baseUrl.'/theme/site/images/comments.png"/>Comments
<img src="'.Yii::app()->baseUrl.'/theme/site/images/share.png"/>Share</p>
<br/>';
$userComment = new Comments;
$PopupdetailText .= $this->renderPartial('//comments/_form', array('model' => $userComment,'id'=>$id),TRUE,TRUE);
// $PopupdetailText .= $this->renderPartial('//comments/view', array('model' => $userComment,'id'=>$id),TRUE);
$PopupdetailText.='</div>
<div class="col-sm-5">
<img src="'.$infowinimgpathSrcs.'" width="100%"/>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="modal-footer login_modal_footer">
</div>
</div>
</div>
<script>
function subcribefeed(staus,cid)
{
if(staus==0){
$("#subcribefrm").toggle(); }
else { subcribefeedAdd(cid); }
}
function subcribefeedAdd(cid)
{
subusremail=$("#subemailid").val();
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if (subusremail == "" || !re.test(subusremail))
{ alert("Invalid EmailID ."); }
else {
postData ={
"email" :subusremail,
"cid" :cid
}
$.ajax({
type: "POST",
data: postData ,
url: "'.Yii::app()->baseUrl.'/newsfeeds/create",
success: function(msg){
if(msg=="Success"){ showdetails('.$id.'); alert("news feed subscribe successfully."); }
else if(msg=="available"){ alert("Already subscribe News Feed for this Commercial user."); }
else { alert("Error ."); }
}
});
}
}
</script> ';
echo $PopupdetailText;
}
I just got the answer.I dont know whether the answer is in right method.
I just added the foolwiong code after my action.
**
$view = new Viewcount;
$viewip = Yii::app()->request->getUserHostAddress();
$viewdate = date('Y-m-d');
$view->ipadd = $viewip;
$view->ofrevntid = $id;
$view->visitdate = $viewdate;
$viewlist = Viewcount::model()->findByAttributes(array('ipadd'=>$viewip,'ofrevntid'=>$id,'visitdate'=>$viewdate));
$viewcount = count($viewlist);
if ($viewcount == 0){
$view->save();
}
**

How to have a URL based off a username PHP

The question may seems vague and I apologise fully, so I'll try and explain it better here. Basically, I have 2 .php files, the index.php and php.php. On index.php a user will enter their username into the form where they would then submit the input, php.php then grabs the username (using the $_POST[] method.) and display the data on that page. The URL at this point looks like this;
http://minecraftnamespy.esy.es/php.php.
How would I do it so that the username the user types would be added onto the URL? E.g;
User inputs: _scrunch as username.
URL now changes from http://minecraftnamespy.esy.es/php.php to
http://minecraftnamespy.esy.es/php?=_scrunch
I should like to point out that I am working with the Mojang API here.
My php.php code is:
<?php
//error_reporting(E_ALL & ~E_NOTICE);
// Load the username from somewhere
if (
$username = $_POST["username"]
) {
//do nothing
} else {
$username = "notch";
}
//allow the user to change the skin
$skinChange = "<a href='https://minecraft.net/profile/skin/remote?url=http://skins.minecraft.net/MinecraftSkins/$username.png' target='_blank' </a>";
//grabbing the users information
if ($content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username))
) {
$userSkin = "<img src='https://mcapi.ca/skin/3d/$username' />";
} else {
$content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username) . '?at=0');
if( $http_response_header['0'] == "HTTP/1.1 204 No Content") {
echo "Not a valid Minecraft Username! <a href='index.php'><button>Search Again?</button></a>";
die;
}
$json = json_decode($content);
foreach ($json as $currentName) {
$currentName = $currentName;
}
$userSkin = "<img src='https://mcapi.ca/skin/3d/$currentName' />";
}
// Decode it
$json = json_decode($content);
// Check for error
if (!empty($json->error)) {
die('An error happened: ' . $json->errorMessage);
}
// Save the uuid
$uuid = $json->id;
// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');
// Decode it
$json = json_decode($content);
$names = array(); // Create a new array
foreach ($json as $name) {
$input = $name->name;
if (!empty($name->changedToAt)) {
// Convert to YYYY-MM-DD HH:MM:SS format
$time = date('Y-m-d H:i:s', $name->changedToAt);
$input .= ' (changed at ' . $time . ')';
}
$names[] = $input; // Add each "name" value to our array "names"
}
//url to users 2D head (avatar)
$usersAvatar = "https://mcapi.ca/avatar/2d/$input/55";
//user's Avatar as favivon
$usersFavicon = "<link rel='shortcut icon' href='$usersAvatar' type='image/png' />";
//use $uuid tp grab UUID of the user - ---- - - - use $names to get name history of the user.
?>
<html>
<head>
<?php echo $usersFavicon;?>
<title><?php echo $username?>'s Information</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Find a player skin!</title>
<style>
body {
background-image: url(http://minecraftnamespy.esy.es/grad.jpg);
background-position: bottom;
background-repeat: no-repeat;
background-size: 100% 500px;
}
#content {
margin-left: auto;
margin-right: auto;
width: 60%;
}
img.logo {
margin-right: auto;
margin-left: auto;
display: block;
padding: 30px;
max-width: 100%;
height: auto;
width: auto\9;
}
.center {
margin-left: auto;
margin-right: auto;
}
.footer {
text-align: center;
}
p.responsive {
word-wrap: break-word;
}
</style>
</head>
<body>
<img style="position: absolute; top: 0; right: 0; border: 0;" src="http://minecraftnamespy.esy.es/source.png" alt="View Source on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png">
<!--debug -->
<?php ?>
<div id="content">
<div class="col-md-12">
<img class="logo" src="http://minecraftnamespy.esy.es/logo.png">
</div>
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s UUID</h3>
</div>
<div class="panel-body">
<p class="responsive"><?php echo $uuid;?></p>
</div>
</div>
</div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s Name History (Oldest to Most Recent)</h3>
</div>
<div class="panel-body">
<?php echo implode(', <br>', $names) ;?>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s Avatar</h3>
</div>
<div class="panel-body">
<div class="center">
<?php echo $userSkin;?>
</div>
<p><?php echo $skinChange;?>Change this skin to yours!</a></p>
</div>
</div>
</div>
<div class="col-md-12">
<div class="btn-group pull-right" role="group" aria-label="">
<button type="button" class="btn btn-default">Search another Username?</button>
</div>
</div>
<div class="footer">
<span>Created by _scrunch</span> •
<span>©2015</span> •
<span>Find me on PMC</span>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="Y8MWQB9FCUTFJ">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
</div>
</body>
</html>
Here's the form that is used to submit the username on index.php.
<form action="php.php" method="GET">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter username">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
You want a GET request, which are visible in the URL in the form of http://example.com/index.php?username=_scrunch
A POST request is invisible (i.e, it does not appear in the URL) and are commonly used to send sensitive data (though a POST is not enough for data security!).
Converting your POST into a GET is a simple matter of changing from
$username = $_POST["username"]
to
$username = $_GET["username"]
You can use this, note the additional inclusion of
if (!$_GET["username"]) {
exit;
}
which causes your page to exit loading and protects against misuse of the page if username is not present.
<?php
//error_reporting(E_ALL & ~E_NOTICE);
// Load the username from somewhere
if (!$_GET["username"]) {
exit;
}
if (
$username = $_GET["username"]
) {
//do nothing
} else {
$username = "notch";
}
//allow the user to change the skin
$skinChange = "<a href='https://minecraft.net/profile/skin/remote?url=http://skins.minecraft.net/MinecraftSkins/$username.png' target='_blank' </a>";
//grabbing the users information
if ($content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username))
) {
$userSkin = "<img src='https://mcapi.ca/skin/3d/$username' />";
} else {
$content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username) . '?at=0');
if( $http_response_header['0'] == "HTTP/1.1 204 No Content") {
echo "Not a valid Minecraft Username! <a href='index.php'><button>Search Again?</button></a>";
die;
}
$json = json_decode($content);
foreach ($json as $currentName) {
$currentName = $currentName;
}
$userSkin = "<img src='https://mcapi.ca/skin/3d/$currentName' />";
}
// Decode it
$json = json_decode($content);
// Check for error
if (!empty($json->error)) {
die('An error happened: ' . $json->errorMessage);
}
// Save the uuid
$uuid = $json->id;
// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');
// Decode it
$json = json_decode($content);
$names = array(); // Create a new array
foreach ($json as $name) {
$input = $name->name;
if (!empty($name->changedToAt)) {
// Convert to YYYY-MM-DD HH:MM:SS format
$time = date('Y-m-d H:i:s', $name->changedToAt);
$input .= ' (changed at ' . $time . ')';
}
$names[] = $input; // Add each "name" value to our array "names"
}
//url to users 2D head (avatar)
$usersAvatar = "https://mcapi.ca/avatar/2d/$input/55";
//user's Avatar as favivon
$usersFavicon = "<link rel='shortcut icon' href='$usersAvatar' type='image/png' />";
//use $uuid tp grab UUID of the user - ---- - - - use $names to get name history of the user.
?>
<html>
<head>
<?php echo $usersFavicon;?>
<title><?php echo $username?>'s Information</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Find a player skin!</title>
<style>
body {
background-image: url(http://minecraftnamespy.esy.es/grad.jpg);
background-position: bottom;
background-repeat: no-repeat;
background-size: 100% 500px;
}
#content {
margin-left: auto;
margin-right: auto;
width: 60%;
}
img.logo {
margin-right: auto;
margin-left: auto;
display: block;
padding: 30px;
max-width: 100%;
height: auto;
width: auto\9;
}
.center {
margin-left: auto;
margin-right: auto;
}
.footer {
text-align: center;
}
p.responsive {
word-wrap: break-word;
}
</style>
</head>
<body>
<img style="position: absolute; top: 0; right: 0; border: 0;" src="http://minecraftnamespy.esy.es/source.png" alt="View Source on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png">
<!--debug -->
<?php ?>
<div id="content">
<div class="col-md-12">
<img class="logo" src="http://minecraftnamespy.esy.es/logo.png">
</div>
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s UUID</h3>
</div>
<div class="panel-body">
<p class="responsive"><?php echo $uuid;?></p>
</div>
</div>
</div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s Name History (Oldest to Most Recent)</h3>
</div>
<div class="panel-body">
<?php echo implode(', <br>', $names) ;?>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s Avatar</h3>
</div>
<div class="panel-body">
<div class="center">
<?php echo $userSkin;?>
</div>
<p><?php echo $skinChange;?>Change this skin to yours!</a></p>
</div>
</div>
</div>
<div class="col-md-12">
<div class="btn-group pull-right" role="group" aria-label="">
<button type="button" class="btn btn-default">Search another Username?</button>
</div>
</div>
<div class="footer">
<span>Created by _scrunch</span> •
<span>©2015</span> •
<span>Find me on PMC</span>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="Y8MWQB9FCUTFJ">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
</div>
</body>
</html>

How can I return multiple data using ajax and json

I'm trying to return a multiple data from database, then I'll pass it to jquery using ajax & json but the problem is its not working. Can anyone help me to fix it? Here is my code.
Jquery
$('.highlight').click(function() {
var y = $(this).find("td").eq(0).find('input[type="hidden"]').val();
var x = $(this).find("td").eq(1).text();
var z = $(this).find("td").eq(2).text();
//$('#ClassModal').modal('show');
$("#spanclass").text(x);
$("#spanclass2").text(z);
$('#ClassModal').modal('show');
$.ajax({
type:"GET",
url: 'db_loadStud.php',
data: 'year='+x+'&subject='+z,
dataType: 'json',
success: function(data){
for(var x=0;x<data.length; x++){
$(".studname").find("span").text(data[0]+", "+data[1]);
}
}
});
return false;
});
PHP
<?php
session_start();
include("db_conf.php");
$fid = $_SESSION['fid'];
$year = $_GET['year'];
$sub = $_GET['subject'];
$sql = "SELECT si_lname, si_fname, si_mname,si_studentno FROM `student_info` a";
$sql .= " INNER JOIN (SELECT * FROM student_enrolled WHERE se_active='True') b ON a.si_studentno=b.se_id";
$sql .= " INNER JOIN tblcourses c ON b.se_level=c.c_level WHERE c_level='$year' AND c_subject='$sub' AND c_teacher = '$fid'";
$result = mysql_query($sql);
$arr;
while($array = mysql_fetch_row($result)){
echo json_encode($array);
}
?>
HTML
<div class="modal fade" id="ClassModal" style="margin-left:-400px;margin-right:auto;" tabindex="-1" role="dialog" aria-labelledby="ClassModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="width:1000px;">
<div class="modal-header" style="background-color:#0a4595;color:#fff">
<h4 class="modal-title" id="myModalLabel"><center>Landstand of Knowledge Learning School, Inc. [ <span id="spanclass"></span> - <span id="spanclass2"></span> ]</center></h4>
</div>
<div class="modal-body" style="height:470px;">
<div style="float:left;border:1px solid #0a4595;width:200px;height:435px;">
<div style="width:100%;height:30px;border-bottom:1px solid #0a4595;background-color:#0a4595;padding:5px;font-size:12;color:#fff">
<center>STUDENTS</center>
</div>
<div class="studname" style="width:100%;height:30px;border-bottom:1px solid #0a4595;padding:5px;font-size:12;">
<span id="studname"></span>
</div>
</div>
</div>
<div class="modal-footer" >
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
thank you in advance
In the for loop, you are always overriding the contents of the span instead of adding contents to the existing one so only the last item in the array will be visible
$(".studname").empty();
for (var x = 0; x < data.length; x++) {
$(".studname").find("span").append(data[x][0] + ", " + data[x][1]+'<br />');
}

Categories