Updating a page element in a php script - php

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.

Related

Autocomplete does not work in CodeIgniter

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!

my ajax call is getting correct response but isn't doing anything

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')
});

ajax to php $variable

I try to pass this value to my php code, but I do not know how to do it. post method does not work. (I do not know why).
<script>
var val = localStorage.getItem('sumalist');
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function () {
console.log(val);
}
});
</script>
and in my php code, value is not set.
if (isset($_POST["value"])) {
echo "Yes, value is set";
$value = $_POST["value"];
}else{
echo "N0, value is not set";
}
PS: My php code is in the same file in js code.
Check if this works
<?php
if(!empty($_POST)) {
$value = (isset($_POST["value"])) ? $_POST["value"] : NULL;
$return = ($value != NULL) ? "Yes, value is: ".$value : "N0, value is not set";
echo $return;
exit;
}
?>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
var val = 'value sent';
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function (ret) {
console.log(ret);
}
});
</script>
Open console for result
Please use console if you're using chrome then open console and try debugging,
And first you run that ajax function in jquery ready function like this
$(document).ready(function (){ $.ajax( replaced for ajax function ) }
If you want to use the response in callback success function, use this:
success: function (ret) {
console.log(ret); //Prints 'Yes, value is set' in browser console
}
In your browser you have Developer Tools - press F12 to open, go to Network tab (FireFox, Chrome, IE - all the same), then reload your page and you will see the line for your AJAX call (if it is performed on load, or trigger your call if this is not the case), select it and right hand you'll see a extra frame where you can see all the details of your request, including request params, headers, response headers, the actual response and many other.
That's the best solution to check your AJAX request without asking uncompleted questions and seeking for the answers in case someone can assemble your full case in his mind.
Believe me - this is the best solution for you and not only for this case!
Of course your JS should be performed when DOM is ready so you have to wrap it in
${function() {
// your code here
});
in case you want to be executed on load.

how can I access json data from another url inside a html page

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>

Why is my php variable made with ajax keeping empty?

First, precisions : I'm using MAMP and Brackets, and Chrome to test.
Here's what I have :
<ul>
<li class="brick" data-pseudo="one">Some text or elements</li>
<li class="brick" data-pseudo="two">Some text or elements</li>
<li class="brick" data-pseudo="three">Some text or elements</li>
</ul>
li.bricks are just rectangle articles "linking" to Work1, Work2 and Work3, and generated by a PHP function from an array.
I'm trying to get the "pseudo" data of the clicked .brick to put it in a PHP variable and use it to call another array in another php function, in order to generate the HTML elements of Work1, Work2,...
I found I had to use AJAX and managed to get that code :
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
$('.brick').click(function(){
//some code
pseudo = $(this).data('pseudo');
sendPseudo(pseudo); //calling sendPseudo() function
});
And here's my testing PHP function :
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
... I'm calling in my HTML document :
<section class="site">
<div class="left">
<?php loadWork() ?>
</div>
<div class="right">
//some other content
</div>
</section>
And so I have two problems. Firstly, when a .brick is clicked, the alert pops up but it's empty, absolutely nothing appears in it, but when I console.log the var pseudo, I see "one", "two"... And secondly, the echo in testing PHP function does not generate the paragraph with the pseudo.
Pleeeaaase, help me to find out what I'm doing wrong, it's making me go crazy !
Thank you !
I think there is some confusion in your order. loadWork(), as you say, is part of an html file gets called as soon as the browser reads the html file and it's only called once. If loadWork() hasn't been defined yet (or exists in another file as your AJAX request suggests based on it's call to my_php_function_page.php) then it won't output anything. In other words, loadWork() needs its post data to exist when the browser requests the html.
You can put the php in the same file as the html that is being called on, but it looks like you might be trying to get the results of loadWork() inserted into a div that already exists. Change your ajax function so that if(data!="") changes the inner html of your div to include the data:
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
$('.left').html(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
I think you have missed calling your function loadWork() in my_php_function_page.php, this code may be fix your empty alert issue.
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
data=data.trim(); // to remove the unwanted space around the string
success: function (data) { //testing the success
if(data!="")
{
alert(data);
$(".right").html(data); // This adds your AJAX success data to the class left inside your DIV
}
else
{
alert("You're wrong !");
}
},
});
}
my_php_function_page.php
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
loadWork();
I'm not sure why, but sometimes data function is not working, so I always use attr('data-pseudo') in your case.
so it would be like this:
pseudo = $(this).attr('data-pseudo');

Categories