I have some divs with class content-full which are created according to the data stored in a MySQL table. For example, if I have 3 rows there will be 3 divs.
When I click on any of the divs then the data associated with the ID for that div should be displayed inside div content-full. However, the content associated with the last div appears when I click on any of the divs because I am not passing any kind of variable ID that can be used to specify the clicked div.
<script type="text/javascript">
$(document).ready(function() {
$(".content-short").click(function() { //
$.ajax({
type: "GET",
url: "content.php", //
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
});
</script>
content.php
<?php
include "mysql.php";
$query= "SELECT Content FROM blog limit 1";
$result=mysql_query($query,$db);
while($row=mysql_fetch_array($result))
{
echo $row['Content'];
}
mysql_close($db);
?>
Is there an alternate way to do this or something that I need to correct for it to work?
Thanks
First off, you will have to pass actual data to the your PHP script. Let's first deal with the JavaScript end. I am going to assume that your HTML code is printed using php and you are able to create something like the following: <div class=".content-short" data-id="2" />:
$(".content-short").click(function() {
// get the ID
var id = $(this).attr('data-id');
$.ajax({
type: "post",
url: "content.php",
data: 'id=' + id
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
Next up is reading the value you passed in using the script:
<?php
include "mysql.php";
// Use the $_POST variable to get all your passed variables.
$id = isset($_POST["id"]) ? $_POST["id"] : 0;
// I am using intval to force the value to a number to prevent injection.
// You should **really** consider using PDO.
$id = intval($id);
$query = "SELECT Content FROM blog WHERE id = " . $id . " limit 1";
$result = mysql_query($query, $db);
while($row=mysql_fetch_array($result)){
echo $row['Content'];
}
mysql_close($db);
?>
There you go, I have modified your query to allow fetching by id. There are two major caveats:
First: You should not use the mysql_ functions anymore and they are deprecated and will be removed from PHP soon if it has not happened yet!, secondly: I cannot guarantee that the query works, of course, I have no idea what you database structure is.
The last problem is: what to do when the result is empty? Well, usually AJAX calls send and respond with JSON objects, so maybe its best to do that, replace this line:
echo $row['Content'];
with this:
echo json_encode(array('success' => $row['Content']));
Now, in your success function in JS, you should try to check if there a success message. First of, change dataType to json or remove that line entirely. Now replace this success function:
success: function(response){
$(".content-full").html(response);
}
into this:
success: function(response){
if(response.success) $(".content-full").html(response);
else alert('No results');
}
Here the deprecation 'notice' for the mysql_ functions: http://php.net/manual/en/changelog.mysql.php
You can look at passing a parameter to your script, generally like an id by which you can search in the db.
The easiest way to achieve this is by get parameters on the url
url: "content.php?param=2",
Then in php:
<?php $param = $_GET['param'];
...
Related
Basically, on my HTML display page, mainHTML.php I include a PHP file called phpFunctions.php with some of the PHP functions I made and call these functions. One of them in particular gets information from a SQL database and makes a table from it.
On mainHTML.php, I have an ajax script that gets the value from a select box that is on same page, on change.
<script>
$(document).ready(function() {
$('select[name="selectBox"]').change(function(){
var value = $(this).val();
$.ajax({
type: 'POST',
url: 'ajaxScript.php', //if bug change to ajaxScript.php
data: {valueChange: value },
dataType: 'html'
}).done(function(response){
$('.response-holder').html(response);
});
});
});
</script>
My ajaxScript looks like so. At the moment, all I can get it to do is echo something based on the value of the select box.
<?php
$status = $_POST['valueChange'];
if($status == 'height'){
echo "ORDER BY height";
}
if($status == 'weight'){
echo "ORDER BY weight";
}
?>
All of this works fine but then I come into a problem. I don't know how I can append the SQL string present in a function in phpFunctions.php so that it may be modified based on the ajaxScript.php condition.
Thanks in advance.
I'm working on a project where I have an HTML file with 2 different divs: "product" and "price". The text inside these divs must come from a row into a database. I can easily access these text values with a php file. I'm also able to get just one of them using AJAX and I can put it inside one of the divs. The problem is I don't know how I can get both product and price and put them inside the divs. I've found some very similar questions but none of the answers have worked for me.
Here is the JS code that I have:
$.ajax({
type: "GET",
url: "url to the php file",
dataType: "html",
success: function(response){
$("#product").html(response);
}
});
Here is the php (the columns I have are just id, product and price):
mysqli_query($link, $query);
$query = "SELECT * FROM products WHERE id = 1";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
echo "{$row['product']}";
}
}
As I said, the code above works, but only for "product". I want to get both "product" and "price". I really appreciate any help you can provide.
You need to use JSON. Here is a simple example:
$.ajax({
type: "GET",
url: "url to the php file",
dataType: "html",
success: function(response){
$("#name").html(response.name);
$("#shoes").html(response.large);
},
dataType: 'json'
});
And then in the PHP to return back JSON use this approach:
$array = array('name' => 'Bob', 'shoes' => 'large');
echo json_encode($array);
You can amend my PHP so you return back whatever you query from your database.
Can some body help me get the current value from this option tag
to account.php as a session variable or anything ..
// loadsubcat.php This code is for dependent dropdown
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
var javascriptVariable = $('#sub_cat').val();
I know this can be solve using ajax but I don't know how.
I will use the javascript variable as a reference for a couple of checkboxes under it but first must be passed as a php variable.
you ajax will look like this,
$.ajax({
type: 'POST',
url: "account.php",// path to ajax file
data: {javascriptVariable:javascriptVariable},// you can pass values here in key value pairs.
success: function(data) {
alert(data);
}
});
You can send n number of key => value pairs.
like
parent_cat:100
Next:
echo $_POST['javascriptVariable']; // <--- grabbing ajax data here
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
what ever echoed in php file will come in ajax success data,
alert(data) will alert what you had echoed in php. you can use that in your html file.
I have a form with 17 checkboxes. When one of these changes, JavaScript should submit the values to the server (running PHP).
I want to use JSON, because the checkboxes give two arrays which have to be seperated in PHP
In JS, I create an JSON-String, which I want to submit via POST and read and decode in PHP.
The String looks like this atm: [["2015-06-26","2015-06-27"],["2","3","4","5","6","7","8","9","10","11","12","13","14"]] - This is what I want it to be.
This is, what my AJAX-function looks like:
var fullArray = [dateArray, trackArray];
var jsonFullString = JSON.stringify(fullArray);
//jsonFullString == [["a","b","c"],["d","e","f","g"]]
$.ajax({
type:'POST',
url:'shownitems.php',
data: jsonFullString,
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
When I get it to PHP, and search for $_POST[0] the success function in JS doesn't show anything. When I search for $_POST, I get "Array.." back.
This is, what my PHP looks like (This is my test snippet):
<?php
echo $_POST;
echo ".";
echo $_POST[0];
echo ".";
echo $_POST[0][0];
$array = array();
?>
I am also using jQuery.
In your JS:
/* dateArray and trackArray must be variables with values */
$.ajax({
method: "POST",
url: "shownitems.php",
data: { date: dateArray, track: trackArray }
}).done(function(response) {
alert(response);
});
In your PHP:
<?php
var_dump('Date: '.$_POST['date']);
var_dump('Track: '.$_POST['track']);
?>
You should get your request content instead the $_POST variables.
Something like this would
$json = file_get_contents('php://input');
$obj = json_decode($json); //Will contain your array of two arrays
In case you wanted to get your post variables like you are doing, you could change your AJAX request and use:
$.ajax({
type:'POST',
url:'shownitems.php',
data: {
data: jsonFullString
},
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
And your PHP would be:
$json = $_POST["data"];
$obj = json_decode($json); //Will contain your array of two arrays
Hi I'm trying dynamically remove database entries using JS and AJAX without refreshing whole page.
Here is my data.php file:
<?php
require_once('db.php');
if (isset($_GET['list'])) {
$query = "SELECT * FROM message";
mysql_query("SET NAMES 'UTF8'");
$qq=mysql_query($query);
$i = 1;
echo '<div id="rezult">';
while($ff = mysql_fetch_array($qq)){
echo '<div id="id'.$ff['id'].'">'.$i++.'. Name: '.$ff['name'].' Message:'.$ff['message'].'</div>';
}
echo '</div>';
}
?>
With this code I'm retrieving a data from mysql table:
index.php
function list() {
$.get('data.php?list=1', function(o) {
$('#list').html(o);
});
}
How to dynamically delete desired entry without refreshing a page?
tried to add this code below as a link to the entry, but it getting cut javascript:$.post( like that.
<a href="javascript:$.post('delete_post.php', { id: '$ff[id]' } );" class='delete_post' title='delete post'>delete post</a>
Thanks for advices
Be careful!, if someone make a call to your php file data.php?list=ANYNUMBER he will be able to delete any row, be sure you are using security tools to avoid that.If you use ajax and Jquery I think it will be easier.
try something like this:
$.ajax({
type: "POST",
url: "list.php",
data: { list: "1", session_id: session_ID }
}).done(function( msg ) {
alert( "Data deleted: " + msg );
});
where session_id is the value of the field (in your example is 1), session_id is when someone go to your page you assign him a SESSION_ID, after he click the delete button, you compare if the session ID that you assign is equal to the the session_id from the server (you avoid people from another site to call your list.php). If session_id from the ajax is equal to session session_id on the server allow to delete take a look to this: PHP Session Security