I'd like to post some content from a database on an html page. I'm not sure what the best way to do this is but my guess would be something that resembles the code below. Please let me know if there is a better way.
HTML:
$(document).ready(function(){
$.ajax({
type : "POST",
url : 'tablepageload.php',
data : 'test',
success: function(data) {
$('#echobox').html(data);
}
});
});
PHP:
if (isset($_POST['test'])) {
$sendtable = "SELECT `timein` FROM `timestamp` WHERE id='" . $latestrow . "' LIMIT 1";
$result = mysqli_query($link, $sendtable);
$row = mysqli_fetch_array($result);
echo $row['timein'];
};
Your workflow seems fine to me.
In essence, as already mentioned the work flow for what you're trying to achieve is:
Make request (your initial ajax call)
Process the request send response (your php script)
Handle the reponse (your 'success' callback)
Looking at your code i have some pointers.
Considering using the jquery .load() function.
If your ajax call is to do nothing more than populate a div you may aswell use this.
In terms of your sql query, i would recommend looking at:
Prepared statements (http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)
PDO (http://php.net/manual/en/book.pdo.php)
And if you want your latest row, order by 'id' DESC LIMIT 1.
Hope this proves helpful
EDIT: Also noticed a problem with your ajax call:
$.ajax({
type : "POST",
url : 'tablepageload.php',
//data : 'test',
//$_POST['test'] = "some_value",
//$_POST['another'] = "test"
data : {test:'some_value', another:'test'},
success: function(data) {
$('#echobox').html(data);
}
});
Related
Fists off, I'm new to JavaScript, so please excuse my ignorance.
I have a function that accepts a parameter specified by each button.
I am trying to use PHP and AJAX to successfully query the MySQL database.
This is what I have so far:
function reply_click(clicked_id) {
var Type = clicked_id;
$.ajax({
type:'post',
url:'PHP_markAtype.php',
data: {type: Type},
success: function(data, textStatus, jqXHR) {
console.log(data);
}
});
}
<button class="click" name="rowID" type="submit" onClick="reply_click('dog')">Make it a dog</button>
Then on the server side PHP (on page PHP_markAtype.php) I have:
$idAnim = $_GET["Site"];
mysql_select_db($dbname, $con);
// update type
$query = "UPDATE tableA SET Atype = '$idAnim'";
mysql_query($query);
Now from all the examples I have seen, this should work but I get a blank page back.
What am I doing wrong?
What am I doing wrong?
Well...
Using the deprecated mysql_* functions instead of mysqli_* functions.
Trying to access posted data with $_GET.
Leaving yourself vulnerable to SQL injections by not using parametised queries.
Now the answer.
You weren't far off the mark.
The PHP should look like this:
$idAnim = $_POST["animal"];
$query = $con->prepare("UPDATE tableA SET Atype = ?");
$query->bind_param("s", $idAnim);
$query->execute();
echo "Successfully updated data to $idAnim";
?>
Note that I haven't done any error checking here, I have left that for you.
Make sure that the $_POST was sent, that bind_param didn't fail, and that execute was successful.
Now for the HTML and JavaScript (JS).
function reply_click(clicked_id) {
$.ajax({
type: "POST",
url: "PHP_markAtype.php",
data: {animal: clicked_id},
success: function(data, textStatus, jqXHR) {
$("#test").html(data);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="click" name="rowID" type="submit" onClick="reply_click('dog')">Make it a dog</button>
<div id="test"></div>
I have altered the JS to change a new <div> contents the PHP message if the data is successful.
Additionally, I have removed the pointless variable assignment of the parameter.
I hope this works for you, but please take into consideration the comments at the top of this answer.
There are some serious security issues in using mysql_* and printing the variable straight into the string.
change
$_GET["type"];
to
$_POST["type"];
Debated whether to put this on WordPress.SE or here; decided that since it's primarily a jQuery question I'd post it here with the note that it occurred during WordPress development for context.
Long story short, following a guide on how to use AJAX in WordPress to the letter—including pasting in the same code excerpts to see if they run—doesn't work on my dev server. The designated PHP function is never executed, and the call just returns a 0 when I dump the response to a an output div.
I added an error: field to the AJAX call and that triggered, but other than revealing that there was an error, I couldn't figure out what was actually at issue.
Here's a look at the AJAX call, as shown in the guide.
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery("#vote_counter").html(response.vote_count)
}
else {
alert("Your vote could not be added")
}
}
})
Remembering having had this problem before, I decided to review an old project from a year ago, and found the following workaround, which seems to do the same thing, but actually returns the proper response from the script.
Functional workaround, does what is expected
var ajaxurl = '<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php';
var data = {action: "my_user_vote", post_id : post_id, nonce: nonce};
// Handle any returned values
jQuery.post(ajaxurl, data, function(response) {
if(response.type == "success") {
jQuery("#vote_counter").html(response.vote_count)
}
else {
alert("Your vote could not be added")
}
});
Ostensibly, it seems that the latter is just a longwinded way of executing the former, but for some reason only the latter works. What could be causing the error on the first block?
EDIT: It seems this may be a WordPress problem after all. I've already sent the code I was working on the other night to production, so to reproduce it I put it into a plugin and tried to run it on the default theme. It's working on the front end, but it's not working when I take it to a back-end page (which is what I was working on at the time). According to the console, it appears to be an issue with enqueueing the scripts on the back end.
To mitigate that issue, I dumped the following on an otherwise blank back-end page:
This post has <div id='vote_counter'>0</div> votes<br>
<div id="output">Test</div>
<script>
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php",
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
jQuery("#output").html(response)
jQuery("#vote_counter").html(5)
},
error: function(response) {
jQuery("#output").html(response)
jQuery("#vote_counter").html(10)}
})
})
})
</script>
<?php
$link = admin_url('admin-ajax.php?action=my_user_vote');
echo '<a class="user_vote" href="' . $link . '">vote for this article</a>';
Long story short: There is no longer any external script to enqueue, the link is coded directly into it, and the count should update to 5 on success or 10 on failure (since this is a back-end page and therefore there's no page_id to check for). All extraneous data fields have been dropped, since they won't be used in this form.
To simplify generating the response, I trimmed the code back to just the following:
function my_user_vote() {
$result = array(
'status' => 'success',
'count' => 5
);
$result = json_encode($result);
echo $result;
die();
}
What now happens is we get redirected to a blank page with the JSON response dumped on it. Tried dropping in the .post() method from above and that's doing the same thing for some reason.
TL;DR: This probably needs a move to wp.se.
I want to send data from php to a browser using JSON. I think I understand the process - see my example code below. But someone told me this is not the right way to do it. I have been researching for three days but because my English is poor I am not confident that I have found an answer.
What I am hoping for is a sample of code that will receive the JSON and pour it into html elements such as a div, and give it style via CSS, etc.
I really just want an example of how to do this so that I can learn from it and expand it myself for my own needs, but I am unconfident that this approach is correct and do not want to write more bad code.
Thanks
Javascript
$(document).ready(function() {
$.ajax({
type : 'POST',
url : 'server.php',
dataType:"json",
success : function (data) {
$("#orders").html(JSON.stringify(data));
}
});
});
PHP
<?php
$db = new PDO('mysql:host=localhost;dbname=Contact', 'root', '');
$statement=$db->prepare("SELECT * FROM myfeilds");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
$(document).ready(function() {
$.ajax({
type : 'POST',
url : 'server.php',
dataType:"application/json",
success : function (data) {
var jsns=JSON.parse(data);
$("#orders").html("");//clear the div
for(var i in data)
{
var id = data[i].id;
var name = data[i].name;
$("#orders").append("<span>"+id+"-"+name+</span>);//append each element
}
}
});
});
Since your server side php is already returning json.. you can just loop through the array of objects after converting it into JSON and then do DOM manipulation.
The best way to do it would be to use some templating engine like underscore.js
Hello: I am working on a project where I am going to have divisions from a league listed as buttons on a page. And when you click on a button a different team list shows for each division. All divisions and teams are stored in a mysql database and are linked together by the "div_id". The plan was have the buttons use javascript or Jquery to send the 'div_id" to a function; which would then use ajax to access an external php file and then look up all the teams for that division using the div_id and print them on the page. I have been piecing this all together and getting the various pieces to work. But when I put it all together; it seems like the ajax part - does not pull in fresh data from the database if the data is changed. In fact, if I change the PHP file to echo some more data or something, it keeps using the original unaltered file. So, if the data is changed that is not updated, and if the file is changed that is not updated. I did find if I actually copied the file with a new name and then had my ajax call use that file instead; it would run it with new code and the new data at that time. But then everything is now locked in at that point and cannot get any changes.
So - I do not know much about ajax and trying to do this. I am not sure if this is totally normal for what I am using and for a dynamic changing team list, it cannot be done this way with ajax calling a PHP file.
OR - maybe there is something wrong with the ajax code and file I have which is making it behave this way? I will paste in the code of my ajax code and also the php file…
here is the ajax call:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
and here is the script.php file that it calls (removed db credentials):
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
$div_id=$answer;
echo "div id is: " . $div_id . "<br/>";
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$result_g1 = mysql_query("SELECT * FROM teams WHERE div_id=$div_id");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$team_id=$row[team_id];
$team_name=$row[team_name];
echo $team_id . " " . $team_name . "<br/>";
}
}
?>
So - to sum up - is there something wrong with this making it do this? Or is what it is doing totally normal and I have to find a different way?
Thanks so much...
Most likely your browser is caching.
Try adding cache: false as such:
$.ajax({
cache: false,
type: 'GET',
...
The jQuery documentation explains that by doing so, it simply adds a GET parameter to make every request unique in URL.
It works by appending "_={timestamp}" to the GET parameters.
I believe this is caused by your browser's cache mechanism.
Try adding a random number to the request so the browser won't cache the results:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php?r=' + Math.random(),
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
Or turning jQuery's caching option off by:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
},
cache: false
});
Or (globally):
$.ajaxSetup({ cache: false });
I know this question has been asked a lot as I have been googling since morning but I just can't think what's going on in my code.
I have a index.php (which is my website) that uses forms to receive information from user, then invokes a javascript file separately which in turn invokes another backend php file (this backend php file queries a database using mysql and does some stuff).
The problem is I am not sure what information is getting passed to the backend php from my js. I have just learnt jQuery and Ajax so I really don't know what is that small mistake I am making.
From my understanding, the backend php does its stuff and passes the value to javascript to be displayed on the web page. But my data is not getting sent / displayed. I am getting a error 500 internal server error.
Here are the pieces of code that are currently is question:
Javascript:
var data1 = {week:week, group:grp_name};
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
success : function(response){
alert ("success !");
},
error : function(response){
console.log(response);
alert("fail!");
}
})
});
PHP backend (remindUsers.php):
<?php
if (isset($_POST['week'])) {
$week = $_POST['week'];
}
if (isset($_POST['group'])) {
$group_name = $_POST['group'];
}
echo $week;
?>
I am ommiting out the sql code pieces because they work fine.
Edit: Now my status code is 200, response text is also ok . My response text shows a weird "enter' sign next to the actual response text expected. Is this normal ? And it is still going into the error block , not the success block of code.
I can not fully answer your question because I need more debug information about whats going on but theres 2-3 things about your code bugging me a little that might fix your bug.
First, use isset in your backend like this:
if (isset($_GET['your_input_name'])) {
$someData = $_GET['your_input_name'];
}
The isset part is very important here. Set it up and try it again. If you stop having a 500 error. Its probably because your data was never send to your backend or because your not checking the good input name.
Second, About input name. I can see in your code that you send:
var data1 = {week:week, group:grp_name};
So in your backend you should use the name of the value like this to retrieve your data:
$week = $_POST("week");
Third, I am not a json pro but maybe your json is not valid. Even if he is ok I suggest you build a "cleaner" one like this:
var data = [
{ 'name' : 'week', 'value' : week}
];
And finally, if you are using forms to send data to php then you can use something like that :
var myForm = $("#myForm").serializeArray();
$.ajax({
url: 'yourUrl',
type: "GET",
data: myForm,
dataType: 'json',
success: function(res){
//your success code
},
error: function(){
//your error code
}
});
I hope this helps.
You can't have these tags <body>,... in your PHP response over json.
It must be only:
<?php
$week = $_POST("data");
$json = json_decode($week);
echo json_encode($json);
?>
Remove the comment on
//data : {week :week}
And set a variable week with a valid value:
data : {week :week}
and so:
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
data : {week :week} ,
success : function(response){
console.log(response);
},
In order to see what is the shape of response.
You are doing a couple things wrong. First, you don't want to stringify your data before sending it to the server. You want to send JSON, so your commented line is the correct one. There is also a problem with the PHP. The data going to the server will look like:
{week: "Something"}
So in your PHP, you want to access the data like:
$_POST["week"];
USE THIS
PHP
$week = $_POST['data'];
$json = json_encode($week);
echo $json;
JS
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php"
//data : {week :week} ,
data: {data:{week:'week', group:'grp_name'}} ,
success : function(response){
alert ("success !");
},
error : function(response){
alert("fail!");
}
})
I would say wrap the php in a function and echo the json. Also its good to check if there was POSTed data, and if not return an error message. This is not tested, but will hopefully point you in the right direction.
<?php
function getJSON() {
if (isset($_POST["data"] && !empty($_POST['data']) ) {
$week = $_POST["data"];
$json = json_decode($week);
echo $json;
} else {
echo "There was a problem returning your data";
}
}
getJSON();
?>
Actually as I write this, I realized you could try these headers in your AJAX POST:
accepts: 'application/json',
contentType: 'application/json',
dataType: 'json'
Hope that helps.
It worked. I figured out the answer thanks to another SO post.
TIL : Even if server response is ok, the error condition will be triggered because the data returned to javascript from php is not json,since i had explicitly mentioned dataType: "json" in the ajax request.
Link here:
Ajax request returns 200 OK, but an error event is fired instead of success
Thanks folks for helping me and steering me in the right direction. Cheers!