When doing an ajax-request for an autocomplete I get an undefined error:
View:
<input type="text" name="" id="search">
<ul>
<div id="result"></div>
</ul>
Javascript:
$("#search").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo base_url(); ?>index.php/admin/ajaxPro",
dataType: 'json',
type: 'POST',
data: req,
success: function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
select: function(event, ui) {
$("#result").append(
"<li>"+ ui.item.value + "</li>"
);
},
});
Controller:
public function ajaxPro()
{
$term = $this->input->get('term');
$this->db->like('business_name', $term);
$data = $this->db->get("user_table")->result();
header('Content-Type: application/json');
echo json_encode($data);
}
Database:
this is the table
There is no error in the console, Data is showing the network preview but it is not showing on the view page I do not know what the problem is Can you help
The Problem:
Return value: undefined
Change your Controller code to something like this:
public function ajaxPro()
{
$term = $this->input->get('term');
$this->db->like('business_name', $term);
$data = $this->db->get("user_table")->result();
$ajaxData = array();
foreach($data as $row) {
$ajaxData[] = array( // Set "label"+"value" for autocomplete for each result
'label' => $row['name'], // <- change this to your column name
'value' => $row['id'] // <- this should be the ID-Value
);
}
header('Content-Type: application/json');
echo json_encode(
'status' => 'success',
'data' => $ajaxData
);
}
And your ajax success callback:
success: function(r){
if(typeof r.status != "undefined" && r.status == "success"){
response(r.data); // lets autocomplete build response list
} else {
console.log(r); // error occured
}
},
(I changed your response variable from data to r to clearify this is not just the actual data, but a response in a variable that can contain much more than just the data from your sql-find result. It usually holds data exactly in the format you give in json_encode() )
Explanation:
In this line:
if(data.response =="true"){
You are asking for a value/key response that does not exist.
Tips on Debugging and Troubleshooting:
To see what your ajax-response look like, you can open the Dev-Tools in your Browser (ususally F12 and go to the Tab that shows your network requests. There you can find your ajax-request and see the headers you sent and the final response.
Furthermore if you add debugger; in this line, you can debug your javascript and see all variables available in the current scope:
success: function(r){
debugger; // this is a breakpoint equivalent and will halt your code execution when dev tools are open!
Related
I'm trying to make a like/dislike button in ajax. The ajax is sending my data to a separate file where it is saved in a database and that file sends back the successful response {"status":"success","message":"Like has been saved.","data":{"like":"1"}} that I got from the chrome network response window. However the code in $ajax(...).done isn't working
I have console.logged and var.dumped every bit of code i possibly could. my data IS being sent to my database which should mean that the SQL and the like class is correct. I've also tried simply console.log 'ging the response "res" and putting the rest in comments, but that again gives me nothing
<div>
Like
Dislike
<span class='likes' data-id="<?php echo $post->id ?>"><?php echo $post->getLikes(); ?></span> people like this
</div>
$("a.like, a.dislike").on("click",function(e){
var postId = $(this).data("id");
if($("a.like")){
var type = 1;
}else if($("a.dislike")){
var type = 0;
}
var elLikes = $(this).siblings(".likes");
var likes=elLikes.html();
$.ajax({
method: "POST",
url: "ajax/postlike.php",
data: {postId: postId, type:type},
dataType: "json",
})
.done(function( res ) {
console.log(res);
if(res.status=="succes"){
console.log(res);
if(res.data.like=="1"){
likes++;
elLikes=html(likes);
$("a.like").css("display","none");
$("a.dislike").css("display","inline-block");
} else if(res.data.like=="0"){
likes--;
elLikes=html(likes);
$("a.dislike").css("display","none");
$("a.like").css("display","inline-block");
}
}
});
e.preventDefault();
});
if(!empty($_POST)){
try {
$postId=$_POST['postId'];
$type=htmlspecialchars($_POST['type']);
$userId=$_SESSION['user_id'];
$l = new Like();
$l->setPostId($postId);
$l->setUserId($userId);
$l->setType($type);
$l->save();
$res = [
"status" => "success",
"message" => "Like has been saved.",
"data" =>[
"like" => $type
]
];
}catch (trowable $t) {
$res = [
'status' => 'failed',
'message' => $t->getMessage()
];
}
echo json_encode($res);
var_dump($res);
}
what I expected to happen was that Ajax sent the JSON data to the php code, that put it in a database, which works. Then gives a successful response to the Ajax, also works. The Ajax would then switch out the like/dislike buttons whilst adding or taking 1 like from the span "likes". It however does absolutely nothing
I'm almost 100% certain that the problem is something stupid that I'm overlooking, but i really can't find it.
Typo in 'success' in on line: if(res.status=="succes"){
you can try with this:
error: function(xhr, status, error) {
console.log(error)
},
success: function(response) {
console.log(response)
}
in your Ajax function, to know what happen in the server side with the response.
If you specify a return data type for the ajax request to expect, and the actual returned value isn't what you specified, then your error/fail function will be triggered if you have one. This is because adding dataType: "json" causes you're ajax try and parse your return value as json and when it fails, it triggers your error handler. It's best to omit the dataTaype and then add a try catch with JSON.parse in your done function, to get around this.
E.G
.done(function (string_res) {
console.log(string_res);
try {
var json_obj = JSON.parse(string_res);
console.log(json_obj);
} catch (e) {
console.log('failed to parse');
}
// do work/operations with json_obj not string_res
})
.fail(function (jqXHR, textStatus) {
console.log('failed')
});
I noticed that the following code doesn't work. When I remove , "json"); at the end of it, it works but i just get failure. I followed it to jquery spec on the site. Any idea why the $.post method won't work/enter?
The reason i know it wont enter $.post is because alert(form.serialize()); doesnt get called.
In my PHP i am returning the following when it posts:
$arr = array('status' => 'SUCCESS');
echo json_encode($arr);
exit();
This is my ajax below:
var form = $('#lines');
$.post('', form.serialize(), function(json) {
alert(form.serialize());
if(json.status === 'SUCCESS') {
alert(json);
console.log('success');
} else {
alert(json);
console.log('failure');
}
}, "json");
If I remove the json part at the end, it just returns the entire HTML of the page.
Your response is probably not json. If you remove ,"json", it works but post return string datas so your code can't work (json.status on string won't work). If you put ,"json", then it won't probably work if return is not proper json.
What you can do : leave "json" in the end, as this is what you want, add console.data(json) ; and console.data(typeof json) ; just at start of your success function.
Forget about alert, first it stop your script, and it's not as precise as console. Use console when you can.
I can suggest you to write it like this to make it more readable :
console.log('form.serialize()',form.serialize()) ;
var post = $.ajax({
method : 'POST',
url : '',
data : form.serialize(),
dataType : "json"
});
post.done(function(json){
console.log('success',json) ;
console.log('typeof json',typeof json) ;
if(json.status === 'SUCCESS') {
console.log('success');
} else {
console.log('failure');
}
}) ;
post.fail(function(data){
console.log('fail',data) ;
alert('post fail') ;
}) ;
Here is my complete php file index.php. Structure should looks like your one. Just note the top part where i make sure than when i have post data, i echo only the json and returns, so nothing else is sent (like your exit).
<?php
if ( isset($_POST['name']) )
{
echo json_encode(array('status' => 'SUCCESS')) ;
return false ;
}
?>
<form>
<input type="text" name="name" />
<input type="button" />
</form>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
jQuery('input[type="button"]').on('click',function(){
var form = jQuery(this).closest('form') ;
console.log('form.serialize()',form.serialize()) ;
var post = $.ajax({
method : 'POST',
url : '',
data : form.serialize(),
dataType : "json"
});
post.done(function(json){
console.log('success',json) ;
console.log('typeof json',typeof json) ;
if(json.status === 'SUCCESS') {
console.log('success');
} else {
console.log('failure');
}
}) ;
post.fail(function(data){
console.log(this) ;
console.log('fail',data) ;
alert('post fail') ;
}) ;
}) ;
</script>
You need to specify the headers in your php code and tell jQuery that a "json" response is on the way.. here is the correct php code
header('Content-Type: application/json');
$arr = array('status' => 'SUCCESS');
echo json_encode($arr);
exit();
notice the line that sends json headers, try it now and it'll work
here is my php code which would return json datatype
$sql="SELECT * FROM POST";
$result = mysqli_query($conn, $sql);
$sJSON = rJSONData($sql,$result);
echo $sJSON;
function rJSONData($sql,$result){
$sJSON=array();
while ($row = mysqli_fetch_assoc($result))
{
$sRow["id"]=$row["ID"];
$sRow["fn"]=$row["posts"];
$sRow["ln"]=$row["UsrNM"];
$strJSON[] = $sRow;
}
echo json_encode($strJSON);
}
this code would return
[{"id":"1","fn":"hi there","ln":"karan7303"},
{"id":"2","fn":"Shshhsev","ln":"karan7303"},
{"id":"3","fn":"karan is awesome","ln":"karan7303"},
{"id":"4","fn":"1","ln":"karan7303"},
{"id":"5","fn":"asdasdas","ln":"karan7303"}]
But how can I access this data in html, that is, I want particular data at particular position for example i want to show 'fn' in my div and 'ln' in another div with another id
Before trying anything else I tried this
$.ajaxSetup({
url: 'exm1.php',
type: 'get',
dataType: 'json',
success: function(data){
console.log(data);
}
});
but it shows that data is undefined I don't know what I am doing wrong
What you've got should kind-of work if you swapped $.ajaxSetup (which is a global configuration method) with $.ajax. There are some significant improvements you could make though.
For example, your PHP does some odd things around the value returned by rJSONData. Here's some fixes
function rJSONData($result) {
$sJSON = array();
while ($row = mysqli_fetch_assoc($result)) {
$sJSON[] = array(
'id' => $row['ID'],
'fn' => $row['posts'],
'ln' => $row['UsrNM']
);
}
return json_encode($sJSON);
}
and when you call it
header('Content-type: application/json');
echo rJSONData($result);
exit;
Also make sure you have not output any other data via echo / print or HTML, eg <html>, etc
In your JavaScript, you can simplify your code greatly by using
$.getJSON('exm1.php', function(data) {
console.info(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR, textStatus, errorThrown);
});
Use $.ajax instead of $.ajaxSetup function.
Here is a detailed answer from another SO post how to keep running php part of index.php automatically?
<script>
$.ajax({
// name of file to call
url: 'fetch_latlon.php',
// method used to call server-side code, this could be GET or POST
type: 'GET'
// Optional - parameters to pass to server-side code
data: {
key1: 'value1',
key2: 'value2',
key3: 'value3'
},
// return type of response from server-side code
dataType: "json"
// executes when AJAX call succeeds
success: function(data) {
// fetch lat/lon
var lat = data.lat;
var lon = data.lon;
// show lat/lon in HTML
$('#lat').text(lat);
$('#lon').text(lon);
},
// executes when AJAX call fails
error: function() {
// TODO: do error handling here
console.log('An error has occurred while fetching lat/lon.');
}
});
</script>
I want to send this AJAX request:
function sumMonthly() {
var cur_month = $('#month option:selected').attr("value");
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
data: {action: ["get_sum_income", "get_sum_expense", "get_cash_remaining"], cur_month:cur_month}
});
request.done(function(response){
$('#sum_income').html('<h1 class="positiveNum float-right">$' + response.get_sum_income + '</h1>');
$('#sum_expense').html('<h1 class="float-right">$' + response.get_sum_expense + '</h1>');
});
request.fail(function(jqxhr, textStatus){
alert("Request failed: " + textStatus);
});
};
and somehow access the return response, but I'm not sure how to access only a certain part of the response and put it in one div, then put another part in another div. Here's some of my PHP:
if(isset($_POST['action']) && in_array("get_sum_income", $_POST['action'])) {
//do stuff here, put result in $i;
if(!empty($i)) {
echo $i;
} else {
echo '$0.00';
};
};
This is not a real "answer" to your problem, but I can't write what I want in a comment.
You'll need to work on your PHP to consolidate the code and make an array something like this:
$json = array
(
'varname1' => $variable1,
'varname2' => $variable2,
'varname3' => $variable3,
'varname4' => $variable4,
'varname5' => $variable5
);
$jsonstring = json_encode($json);
echo $jsonstring;
Then on client side you can do something like:
.done(function(response) {
$('#div1').text(response.varname1);
$('#div2').text(response.varname2);
$('#div3').text(response.varname3);
$('#div4').text(response.varname4);
$('#div5').text(response.varname5);
});
Again, this is not a specific solution, but it should get you started.
I always write my php, then run it without the client, grab the output on the screen and submit it to jsonlint.com to make sure it's json.
Page elements are defined like this.
<div id="readf" class="tabbertab">
<h2>First Reading</h2>
<div id='titlefe' class='rtitle'>
</div>
<div id='readfe' class='rtext'>
</div>
</div>
I make an ajax call to a php script to add data to these page elements.
<script>
$('#readings').ready(function(){
$.ajax({
url: "loadenglish.php",
type: "GET",
data: { },
cache: false,
async: true,
success: function (response) {
if (response != '')
{
alert (response);
}
},
error: function (request, status, error) {
alert ("status "+status+" error "+error+"responseText "+request.responseText);
},
});
});
</script>
The php script gets the data and does a script echo to add the data.
<?php
$titlefe = 'text 1';
$readfe = 'text 2';
echo "<script type='text/javascript'> $('#titlefe').append('".$titlefe."'); $('#readfe').append('".$readfe."'); </script>";
?>
The alert statements shows that the php script gets the right information. But the page elements are not updated. Is there a different way to add $titlefe to element id titlefe?
In addition to what MK_Dev posted you can use PHP function json_encode();
<?php
//loadenglish.php
$params = array(
'titlefe' => 'text 1',
'readfe' => 'text 2',
);
echo json_encode($params);
Also there is a jQuery function $.getJSON(), which is a shortcut for $.ajax() function usage like yours.
Try eval(response); after your alert in the success callback.
Returning javascript methods is not a good idea. You should return data in JSON format and use javascript on the client side to perform the actual update.
Your PHP return statement should look like:
echo "{ 'titlefe': '" + $titlefe + "', 'readfe': '" + $readfe + "' }";
and your success call back should look like this:
success: function(response) {
$('#titlefe').text(response.titlefe);
$('#readfe').text(response.readfe);
}
If you insist on returning JavaScript, you should be using getScript() instead of an Ajax get.