how to get json/array from ajax responseText in to javascript array - javascript

I am using codeigniter in my project.When I am trying to get array element from encoded array, something id going wrong.How can I get encoded json array in my javaScript?
index.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function sendMessage(){
var message=document.getElementById('chatInput').value;
var receverID=document.getElementById('id').value;
if(message==''){
alert("please enter message");
}
new Ajax.Request('index.php', {
method:'get',
evalJSON: true,
parameters: {
message: message,
id: receverID
},
onSuccess: function(transport){
var data= transport.responseText;
console.log(data);
},
onError: function() {
alert('Error');
},
onComplete: function() {
}
});
}
</script>
</head>
<body>
<textarea name="chatInput" id="chatInput" cols="60" rows="3"></textarea><br />
<input type="button" name="send_message" onclick="sendMessage()" Value="Send"/>
<input type="hidden" id="id" name="id" value="5">
</body>
</html>
index.php
<?php
header('Content-type: application/json');
$data['message'] = $_GET['message'];
$data['sender_id'] = $_SESSION['id'];
$data['user_id'] = $_GET['id'];
$this->model_users->setMessage($data);
echo json_encode($data);
?>

Based on your comment, it seems that you have a HTML in your response. It's a good practice to put exit after json_encode call when you expect JSON response.
Try to put this in your index.php and it should works:
echo json_encode($data);
exit; // terminate the current script

Related

json increments one id but displays all ids

i am using json for like button. when users clicks it correctly increases the like count and stores in database for corresponding id but it shows increment for all ids in browser which is wrong. i want to display for only id where users has liked but it shows for all.
test url is http://way2enjoy.com/app/check/test/indexp.php
indexp.php file is
<?php
include('/home/xxx/con.php');
$query="Select * from users_jokes order by id desc limit 10";
$result=mysql_query($query);
?>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
var url = $(formEl).attr('action');
var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden").value;
$.ajax({
url: url,
data:{
'action':'addComment',
'comment':comment,
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
console.log(result);
$.ajax({
url: url,
data:{
'action':'getLastComment',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
$('#jokes_comment').val("");
console.log(result[0].description);
$("#header ul").append('<li>'+result[0].description+'</li>');
},
error: function(){
alert('failure');
}
});
},
error: function(){
alert('failure');
}
});
// return false so the form does not actually
// submit to the page
return false;
}
var ajaxLike=function()
{
var joke_id=document.getElementById("joke_id_hidden").value;
// setup the ajax request
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'increment_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'display_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
console.log(result);
$("label[for='like_counter']").text(result.likes);
},
error: function(result)
{
alert("error 2");
},
});
},
error: function()
{
alert('failure');
}
});
return false;
}
</script>
<p>commnet list</p>
<div id="header">
<ul id="commentlist" class="justList">
<?php
$query="Select * from comment where joke_id='2'";
$result=mysql_query($query);
while($data = mysql_fetch_array($result)){
$cont = $data['description'];
?>
<li><?php echo $cont;
?></li>
<?php
}
?>
</ul>
</div>
<?php
?>
<form method="post" action="processkk.php" onSubmit="return ajaxSubmit(this);">
<input type=text id="jokes_comment" name="jokes_comment">
</input>
<input type="submit" value="comment">
</form>
</body>
</html>
<?php
while($data = mysql_fetch_array($result)){
$id = $data['id'];
$cont = $data['content'];
$likes = $data['likes'];
?>
<p><?php echo $cont;?></p>
<input type="hidden" value="<?php echo $id ;?>" id="joke_id_hidden">
<p><button onClick="ajaxLike();">Like</button> <label for="like_counter"><?php echo $likes;?></label></p>
<?php }
?>
</body>
</html>
likeskk.php
<?php
include('/home/xxxxxxx/con.php');
$action=$_POST['action'];
if($action=="increment_like")
{
$joke_id=$_POST['joke_id'];
$query="update users_jokes set likes =likes+1 where id='".$joke_id."'";
$result=mysql_query($query);
// setup our response "object"
$retVal=array("Success"=>"true");
print json_encode($retVal);
}
if($action=="display_like")
{
$joke_id=$_POST['joke_id'];
$query = "select likes from users_jokes where id = '$joke_id'";
$qry = mysql_query($query);
while($rows = mysql_fetch_array($qry)){
$likes = $rows['likes'];
}
header('Content-Type: application/json');
// print json_encode(array('foo' => 'bar'));
print json_encode(array('success'=>'true','likes'=>$likes));
}
?>
when i click on one like all like increases. when i post comment on one id it appended and displays in all id
Copy and paste it.
<html>
<head>
<script>
function clickCounter(element)
{
element.value = parseInt(element.value) + 1;
}
</script>
</head>
<body>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
</body>
</html>
Because you are using the same id. id must be unique
<input type="hidden" value="4638" id="joke_id_hidden">
Rather than using a hidden input for each entry you could use a dataset on the button itself with the corresponding ID. When the button is clicked the javscript function could read that dataset value and use that in the ajax POST request. So, as an example:
<!doctype html>
<html>
<head>
<title>Like the jokes...</title>
</head>
<body>
<form id='bttns'>
<?php
/* pseudo generate some jokes with buttons and labels to emulate your page */
for( $i=1; $i < 20; $i++ ){
$random=rand(1,20);
echo "
<p>Funny joke...[{$i}]</p>
<input type='button' value='Like' data-id='$i' />
<label class='counter'>{$random}</label>";
}
?>
</form>
<script type='text/javascript'>
var col=document.querySelectorAll('#bttns input[type=\"button\"]');
for( var n in col )if(col[n].nodeType==1)col[n].onclick=function(e){
var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;
var label=el.nextSibling.nextSibling;
var id=el.dataset.id;
label.innerHTML=parseInt( label.innerHTML )+1;
alert( 'use ajax to POST this id: '+id );
}
</script>
</body>
</html>
I should add perhaps that the ajax callback function would be the place to update the value of likes for each joke rather than as here - it's just example code showing how you could do away with hidden fields and the problem of duplicate ids.

Posting html form data to php and accessing that through javascript

I'm trying to post some data to an html form, then that form sends the data to php, and finally javascript takes the data from that php.
This is my html form:
<form action="search.php" method='POST'>
<input id="movie_name" name="movie_name" type="text">
<input name="myBtn" type="submit" value="Submit Data">
</form>
This is my php file which is called search.php:
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo '<script>', 'hello();', 'var movie = '$movie_name';', '</script>';
}
?>
Finally my js script which is in the same file as the php one:
function hello(){
console.log('<?php echo $movie_name?;>');
}
What happens when I load this is that my html redirects ok and then for some in search.php nothing happens, the page goes white and the only thing the console says is "Resource interpreted as Script but transferred with MIME type text/html..."
What exactly you want is not clear. But i suggest you to use jQuery ajax like this:
<input id="movie_name" name="movie_name" type="text">
<input id="myBtn" name="myBtn" type="button" value="Submit Data">
$('#myBtn').click(function(e){
var movie_name = $('#movie_name').val();
$.ajax({
url: "search.php",
type: "POST",
data: {
'movie_name': movie_name
},
beforeSend : function() {
},
success : function(response) {
console.log(response);
},
error : function()
{
},
complete : function() {
}
});
});
in your search.php
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo $movie_name;
}
?>
This is better way from my point of view.
This should work:
<?php
if (isset($_POST['movie_name'])){
$movie_name = $_POST['movie_name'];
}
?>
<script type="text/javascript">
function hello(){
console.log('<?php echo $movie_name; ?>');
}
</script>
<?php
echo '<script> alert("'.$movie_name.'"); hello(); </script>';
?>

How to send data via ajax?

I'm trying to learn how does Ajax work and how I can send data by Ajax. I'm getting no error and nothing is being echoed.
index.html
<input id="name" type="text" /><input id="button" type="button" value="Load" />
<div id="feedback"></div>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="ajax.js"></script>
page.php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
}
?>
ajax.js
$('#button').click(function(){
var name = $('#name').val();
$.ajax({
url: 'page.php',
data: 'name='+name,
success: function(data){
$('#feedback').html(data);
}
});
});
I appreciate any help
You are missing an echo in your page php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
echo $name;
}
?>
also in your javascript send an object like this
data : { name : name}
should work
data : { name : 'John'}
you can check the success method is invoked or not invoked.
Also you need to echo something from php.
echo $name

How to call output of a php page in an html page in a specific div?

This is my html code
<html>
<body>
<form name="form1" action="php1.php" method="post">
<input type="text" name="text1">
<input type="submit" name="submit1">
</form>
<div id="div1">
</div>
</body>
</html>
This is my php1.php code
<?php
if(isset($_POST['submit1']) && ($_POST['text1'])=="text"){
echo "hello";
}
?>
If I want to call the output of php1.php i.e., hello, in html div1 what to do ?
#Uzumaki, I've edited my html code like this, but its not working, here is my code.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
$("form#postit").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "hello.php",
type: 'POST',
data: formData,
async: false,
success: function (data)
{
// $("#div1").append(data); // or
$("#div1").html(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
</head>
<body>
<form name="form1" method="post" id="postit">
<input type="text" name="text1">
<input type="submit" name="submit1">
</form>
<div id="div1">
</div>
</body>
</html>
Since you didn't mention via jquery or ajax I am assuming you are going with a simpler old fashioned way So here is the code
SEND YOUR MESSAGE BACK TO HTML PAGE LIKE THIS
$msg = "hello"
header("Location: your_html_page.html?msg=".$msg);
IN HTML DO THIS
<div id="div1">
<?php
error_reporting(0);
echo $_GET['msg'];
?>
</div>
USING JQUERY :
Post the data to php
$.post("your_php_page.php",{data:data},function(returned_data_from_php){
$("#div1").append(returned_data_from_php); // or
$("#div1").html(returned_data_from_php);
});
Using Ajax
$("form#postit").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "your_php_page.php",
type: 'POST',
data: formData,
async: false,
success: function (returned_data_from_php)
{
$("#div1").append(returned_data_from_php); // or
$("#div1").html(returned_data_from_php);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
PHP
what ever you want to return from php it should be echo and there are many ways to do that
(Single string) echo "Success";
(Multiple Strings) echo $msg1.$msg2;
(Array data)
for example ...
$data = array();
$i = 0;
while($numbs = mysql_fetch_array($result))
{
$row_numb = $numbs['id'];
$data[$i] = $row_numb;
$i++;
}
echo json_encode($data);
// this will pass a json type object to the java script
When you get to javascript you want to access all the elements of the array one by one well that's easy too
JAVASCRIPT
parsed_it = JSON.parse(data); // data is the json type you got from your php
so parsed_it[0],parsed_it[1],parsed_it[2] and so on you can access all the data
hope it helps !!
Put the PHP into your HTML file where you want the result. Be sure your file is named something.php and that you have a PHP processor on the server.
<html>
<body>
<form name="form1" action="php1.php" method="post">
<input type="text" name="text1">
<input type="submit" name="submit1">
<div id="div1">
<?php
if(isset($_POST['submit1']) && ($_POST['text1'])=="text"){
echo "hello";
}
?>
</div>
</body>
</html>
You may use AJAX to dynamically load script output:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get
You may also consider using jQuery to simplify your code:
http://api.jquery.com/jquery.get/

Using AJAX to post form data to PHP page

I am simply trying to use the data submitted in a search form to query the database and bring back results similar to the search. My form looks like this:
<div id="searchform">
<form method="get">
<form id="submitsearch">
<input id="shop" name="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="submit" value="Go"/>
</form>
</form>
<div id="searchresults">
</div>
</div>
the Javascript I've got is:
$("#submitsearch").submit(function(event) {
event.preventDefault();
$("#searchresults").html('');
var values = $(this).serialize();
$.ajax({
url: "external-data/search.php",
type: "post",
data: values,
success: function (data) {
$("#searchresults").html(data);
}
});
});
return false;
I have also tried...
$("#submitbutton").click(function(){
var form_data = $("#submitsearch").serialize();
$.ajax({
url: "external-data/search.php",
type: 'POST',
data: form_data,
success: function (data) {
$("#searchresults").html(data);
}
});
return false;
});
And this seems to work slightly as it shows results, the first doesn't do anything. It's not sending the data to the PHP page but the PHP I've got is:
<?php
$str_shops = '';
$shop = $_POST['form_data'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE name LIKE '%$shop%'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<strong>" . $row['name'] . "</strong><br>" .
$row['address'] . "<br><br>";
}
mysqli_free_result($result);
echo $str_shops;
mysqli_close($db_server);
?>
Any help would be greatly appreciated! Thanks in advance.
You have two form tags. This won't work. You want one form tag with two attributes
<form method="get">
<form id="submitsearch">
to
<form method="get" id="submitsearch">
you can do it without using html form.
first you call the php page and then display a data within html.
this is what I do?!
<div>
<input id="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="button" value="Go"/>
</div>
<div id="searchresults">
</div>
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function(){
try
{
$.post("root/example.php",
{
'shop':$("#shop").val().trim()
}, function(data){
data=data.trim();
$("#searchresults").html(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>

Categories

Resources