PHP and javascript POST - php

I have the following code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript">
</script>
<script type="text/javascript">
function displayTweet(){
var i = 0;
var limit = $("#twitter-results > div").size();
var myInterval = window.setInterval(function () {
var element = $("#twitter-results div:last-child");
$("#twitter-results").prepend(element);
element.fadeIn("slow");
i++;
if(i==limit){
window.setTimeout(function () {
clearInterval(myInterval);
});
}
},2000);
}
$("form#twittersearch").submit(function() {
twitterq = $('#twitterq').attr('value');
$.ajax({
type: "POST",
url: "search.php",
cache: false,
data: "twitterq="+ twitterq,
success: function(html){
$("#twitter-results").html(html);
displayTweet();
}
});
return false;
});
});
</script>
</head>
<div class="twitter_container">
<form id="twittersearch" method="post" action="">
<input name="twitterq" type="text" id="twitterq" />
<button type="submit">Search</button>
</form>
<div id="twitter-results"></div>
</div>
</html>
/***************THIS IS search.php***************************/
<?php
include('twitterapi.php');
if($_POST['twitterq']){
$twitter_query = $_POST['twitterq'];
$search = new TwitterSearch($twitter_query);
$results = $search->results();
foreach($results as $result){
echo '<div class="twitter_status">';
echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
$text_n = toLink($result->text);
echo $text_n;
echo '<div class="twitter_small">';
echo '<strong>From:</strong> <a href="http://www.twitter.com/'.$result->from_user.'">'.$result->from_user.'</a&glt;: ';
echo '<strong>at:</strong> '.$result->created_at;
echo '</div>';
echo '</div>';
}
}
?>
Why is it that when I do a var_dump($_POST['twitterq']) it is always NULL?
UPDATE:
firebug gave me this, not sure how to fix it though:

That is because you are not providing the data properly. It should be:
data: ({twitterq: twitterq}),
You are sending data in the form of JSON. You are not using URL parameters , so there is no need of '='. if you have more than one parameters, you will simply separate them with commas.

Related

Showing the result of my controller on the page

I would like to show the result from controller to view page in ajax codeigniter. This is my code I have used in my project. How to edit to show the result as table in the page. will you please help me to edit the code
<head>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content=' + textcontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
}
else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/Ajaxcontroller/getAttendence",
data: dataString,
cache: true,
success: function (html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="container">
<div class="main">
<form method="post" name="form" action="">
<textarea style="width:500px; font-size:14px; height:60px; font-weight:bold; resize:none;" name="content" id="content"></textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
</div>
</body>
this is my controller
public function getAttendence()
{
if($this->input->post() && $this->input->is_ajax_request()){
$credentials=array(
'category' => $this->input->post('content'),
);
$this->load->model('Ajaxmodel');
if($this->Ajaxmodel->selectAttendence($credentials)){
$data['result']=$this->Ajaxmodel->selectAttendence($credentials);
echo json_encode($data);
}
}
else{
$this->load->view('Salarycontrol');
}
}
$data['result'] = "here is your model";
Then send it to view:
$this->load->view('your_view_here', $data);
I saw that your controller echoed a json_decoded php array:
echo json_encode($data);
So your output is a json string. So in your success you have to use that JSON string. Convert that JSON string to a JavaScript object.
success: function (html) {
var res = JSON.parse(html);
// now your result contains exactly the same things as the php array `$data` you decoded in the controller
}
Note that I’m assuming that json_encode($data) is the only thing being printed by the controller.
If something else is printed, JSON.parse() will give you error.
In controller you have to use "echo" statement to show HTML in our view page.
For example:
//Ajax example with my code
$('#suppliers').change(function()
{
var sup_id = $(this).val();
if(sup_id != ''){
$.ajax({
url:BASE_URL+"orders/get_suppliers_details",
type:'POST',
data:{sup_id : sup_id},
success:function(result)
{
if(result){
$("#show").html(result);
}else{
echo "something went wrong.";
}
}
});
}
});
public function get_suppliers_details(){
$sup_id = $this->input->post('sup_id');
$sup_address = $this->orders_model->get_supplier_address_byId($sup_id);
echo $sup_address[0]['address']."_".$sup_address[0]['supplier_type'];
exit;
}
this will displayed at " id show div"
another way:
public function get_suppliers_details()
{
$sup_id = $this->input->post('sup_id');
$data['result'] = $this->orders_model->get_supplier_address_byId($sup_id);
echo $this->load->view('orders/get_details.php',$data);
}
get_detail.php
<table>
<tr>
<td>Address</td><td><?php echo $result['address']; ?></td>
</tr>
</table>
you can do what ever you want in get_details.php , It will displayed at "show div";
Sorry for my English.
Thank you.!

Post data with ajax or ajax(json) to php in same page

I'm trying message application. My goal is get sender id and receiver id with a click on one button.
After then post this datas with ajax or ajax(json) to php in same page.
I will use the incoming data in php with mysql_query. I tryed many examples. But never get result. My example code at below.
Little Note: Success alert comes but doesn't print any data on screen.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<button type="button" onclick="myFunc()">Get ID</button>
<script>
function myFunc()
{
var id = 'example';
jQuery.ajax({
url:'index.php',
type: "POST",
data: {'name':id},
success: function(data)
{
alert("success");
}
});
};
</script>
<?php
if(isset($_POST['name']))
{
$value = $_POST['name'];
echo $value;
}
else
{
echo "don't work.";
}
?>
</body>
</html>
<?php
if(isset($_POST['name']))
{
echo json_encode(array(
'value' => $_POST['name']
));
exit();
}
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<button type="button" onclick="myFunc()">Get ID</button>
<script>
function myFunc()
{
var id = 'example';
jQuery.ajax({
url:'index.php',
type: "POST",
data: {'name':id},
dataType : 'json',
success: function(data)
{
alert("success");
}
});
};
</script>
</body>
</html>

Not getting jquery Ajax data using dynamic id selector

My PHP code looks like this -
for ($i=0;$i<=10;$i++) {
?>
<div id="">
<input type="text" id="GetCommentText-<?php echo $i;?>"></input>
<input type="hidden" id="GetPostID-<?php echo $i;?>" value="<?php echo $i;?>">
<button type="button" id="SelectPostComment-<?php echo $i;?>" >Submit</Submit>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
I want to get the data of these <input> elements using jquery dynamic id selectors. My jQuery looks like -
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("[id^=SelectPostComment-]").click(function(){
var $td = $(this).closest('input').next();
var CommentText = $td.find("[id^=GetCommentText-]").val();
var PostID = $td.find("[id^=GetPostID-]").val();
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: CommentText, PostID: PostID},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>
But I'm not getting value of ajax data CommentText and PostID in my test1.php file when i click <button>. Not sure what mistake I'm making. Please help.
try this:
for ($i=0;$i<=10;$i++) {
?>
<div id="">
<input type="text" id="GetCommentText-<?php echo $i;?>" />
<input type="hidden" id="GetPostID-<?php echo $i;?>" value="<?php echo $i;?>">
<button type="button" id="SelectPostComment-<?php echo $i;?>" >Submit</button>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
and js part:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('[id^="SelectPostComment-"]').click(function(){ // changed here
var $td = $(this).parent(); // changed here
var CommentText = $td.find('[id^="GetCommentText-"]:first').val(); // changed here
var PostID = $td.find('[id^="GetPostID-"]:first').val(); // changed here
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: CommentText, PostID: PostID},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>
Or You could use more efficient way (no need to make garbages in DOM Tree):
<?php
for ($i=0;$i<=10;$i++) {
?>
<div data-postId="<?php echo $i; ?>">
<input type="text" name="commentText" value="" />
<button type="button" class="submit-comment">Submit</button>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
and js part:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.submit-comment').click(function(){
var $parent = $(this).parent();
var postId = $parent.data('postId');
var commentText = $parent.find('input[name="commentText"]:first').val();
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: commentText, PostID: postId},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>

how to submit the form without refreshing the page

this is my html code when i click on submit button it displays alert and then when i open the retrieveform.php it does not show me the value please solve this mystery
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function () {
alert('helllo');
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text"name="t1">
<input type="submit"name="s1"value="submit">
</form>
</body>
</html>
and my retrieveform.php is
<?php
if($_POST['t1'])
{
echo $_POST['t1'];
}
else
{
echo "hekllojjio";
}
?>
Is it possible that the element "t1" is present since it's part of your form, but empty or just empty characters .. perhaps check if this is the case?
<?php
if($_POST['t1'] && !empty($_POST['t1'])) {
echo "You submitted t1 of: ".$_POST['t1'];
} else {
echo "t1 is empty";
}
?>
Also of note is you may want to use something like firebug to view the ajax page loaded and its results. The echo statement on the ajax loaded page will not display on the parent page unless you set the contents of the response into the page:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$('.form').on('submit', function (e) {
tValue = $(this).find(input[type=text]:first).val();
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function (response) {
alert('helllo');
$('#placeholder').html(response);
$('#placeholder2').html(tValue);
}
});
});
});
</script>
</head>
<body>
<?PHP for ($i = 1; $i <= 10; $i++) { ?>
<form class="form" name="form_<?PHP echo $i; ?>" id="form_<?PHP echo $i;?>">
<input type="text" id="t<?PHP echo $i; ?>" name="t<?PHP echo $i; ?>">
<input type="submit" name="s<?PHP echo $i; ?>" value="submit">
</form>
<?PHP } ?>
<div id="placeholder"></div>
<div id="placeholder2"></div>
</body>
</html>
with this your ajax loaded page's echo will be put on the page in the "placeholder" div.

chat app with user typing partly working

This code works very well for chatting. I have added ajaxcall.php for real time notification. The problem is; instead of displaying a typing notification when other users are typing, it will be displaying myself whenever am typing.please how do i make it to show other users typing.
index.php
<?php
ob_start();
?>
<?php
session_start();
?>
<!doctype>
<html>
<head>
<title>Chat</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="jscolor.js"></script>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
complete: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
success: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
}
});
var $container = $("#messages");
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
var refreshId = setInterval(function()
{
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
}, 3000);
$("#userArea").submit(function() {
$.post('ajaxPost.php', $('#userArea').serialize(), function(data) {
$("#messages").append(data);
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
document.getElementById("output").value = "";
});
return false;
});
});
</script>
<!--Ajax Server Call-->
<script>
function getAjaxFromServer(str){
if (str.length==0){
document.getElementById("ajaxResponse").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("ajaxResponse").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",'ajaxcall.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>',true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="chatwrapper">
<!--display-->
<!--http://www.youtube.com/watch?v=FyXeOX-uYMc-->
<div id="messages"></div>
<!--post-->
<form id="userArea">
<div id="usercolor">
<input name="reciever" type="hidden" value="<?php echo htmlentities($_GET['id'], ENT_QUOTES, "UTF-8");?>"><br>
<input name="text" class="color" id="text" maxlength="6" value="000000" />
</div>
<div id="messagesntry">
<textarea id="output" name="messages" placeholder="Message" onkeyup="getAjaxFromServer(this.value)"/></textarea>
</div>
<div id="messagesubmit">
<input type="submit" value="Post message" id="submitmessage" />
</div>
</form>
</div>
</body>
</html>
ajaxload.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
include('connect.php');
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM messages ORDER BY id ASC");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
echo '<div style="color:'.$row['textcolor'].'">' .$row['user'] . ' : '. $row['message'] .'</div>';
}
?>
ajaxcall.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
$txt=strip_tags($_GET['id']);
$txt1=strip_tags($_SESSION['SESS_MEMBER_ID']);
echo $txt;
echo " is typing ";
?>
The idea is to store a flag on a database and have an a .setTimeOut on your script on which will run whenever your field flag turns from 0 to 1
here is the code snippet to try
$('#txt_message').keyup(function(){
// Start a flag loop with an id of 'loop' and a counter.
var i = 1;
var dataString = 'flag='+ i ;
$.ajax({
type: "POST",
url: "notif.php",
data: dataString,
cache: false,
success: function(url){
}
});
this snippet will update your database whenever you type on your text field
var timer;
function AjaxRetrieve()
{
$.get("type_on.php?flag=0",function(data)
{
window.clearTimeout(timer);
$("#typing_on").html(data);
timer=window.setTimeout(function(){AjaxRetrieve()},3100);
});
}
timer=window.setTimeout(function(){AjaxRetrieve()},1300);
this snippet will be the one to update your flag after a few seconds

Categories