Retrieving data from PHP using AJAX to send to different PHP file - javascript

Ok so I have:
A PHP file that queries a database and displays the results of the query,
a HTML file that displays the results using AJAX and
another PHP file that I need to send the data from the first PHP file to.
How can I do this?
My first PHP file displays:
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div class='result'><a id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></a>";
}
So the AJAX brings this in and displays it in the HTML. Is there a way of sending the ID field when the link is clicked so that it can be used in another PHP file to display the data for that specific ID.
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: $("#hiddenid"),
success: function (data) {
$("#individualshop").load("external-data/shop.php");
}
});
So that the data from the #hiddendiv ($row ['ID']) will be sent to the new PHP file. This isn't working.
shop.php has the code:
//get shop ID
$shopid = $_POST['ID'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE ID='$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='searchresult'><strong>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div>";
}
But I'm not sure how to retrieve the ID?
Basically I need to be able to click on each search result and have another PHP file bring in specific data associated with the ID of the search result. Any suggestions??
Thanks in advance!

I'm not 100% sure this is what you want but this is one way.
This is your first php file. I've added an onclick listener to it so when a user clicks a row it will fire a JavaScript passing the $row['id'] variable.
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div onclick='someFunction(" . $row['id'] . ")' class='result'><div id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></div>";
}
Then add this script to the header of the page.
<script>
function someFunction(d){
var response = httpGet("http://yourdomain.com/newphpfile.php?page_id=" +d);
document.getElementById('someResultArea').innerHTML = response;
}
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", theUrl, false );
xmlHttp.send();
return xmlHttp.responseText;
}
</script>
Then your new php file should do something like this.
newphpfile.php
<?php
session_start();
$page_id = strip_tags($_GET['page_id']);
$processResult = 'handle your result';
echo $processResult;
?>
I hope this helps you out.

Use this;
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: "ID=" + $("#hiddenid"),
success: function (data) {
$("#individualshop").html(data);
}
});
});
Note: Do not forget to return html in shop.php

You can fetch the clicked element id by using either javascript or jquery, and put it in the GET parameters on the php link
the ajax target would be ajax.php?id=test
Then get the value of id via $_GET['id']

Related

Updating a mysql db with php ajax request

I have this php code that updates a row in my MySQL database, based on 3 variables sent with ajax but that returns a http 500 error:
<?php
$dbname = 'xxxxxxxxxx';
$dbuser = 'xxxxxxxxxxxx';
$dbpass = 'xxxxxxxxxxxxx';
$dbhost = 'xxxxxxxxx';
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$topparent = $_POST['name'];
$column = $_POST['column'];
$value = $_POST['value'];
$sql = "UPDATE reloaded SET" . $column . " = '" .$value . "'WHERE top_parent = '" . $name ."';
$retval = mysql_query( $sql, $link );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
echo "success\n";
mysql_close($link);
?>
My jquery js is this. The variables get passed correctly (tried with alert):
function updatedb(a,b,c){
$.ajax({
url: "updatedb.php",
type: 'POST',
data: ({name:a,column:b,value:c}),
success: function(msg) {
alert('DB updated');
}
});
};
Any idea why it returns an error? I have spent some time going over the code, trying different variations but can't seem to figure it out.
There is a PHP syntax error in the SQL query statement.
You have missed to end the " and hence the 500 error.
The corrected code:
$sql = "UPDATE reloaded SET " . $column . " = '" .$value . "' WHERE top_parent = '" . $name ."'";
Edit
Adding to that, there is no space after the SET keyword.
Fixing this will update your db properly.

Not receiving dynamically generated form data

i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>
The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter

How using ajax can update mysql database from dropdown menu

As the question suggest can you tell me how i can update mysql database using a dropdown menu with the help of ajax. I want to update my database with out reloading my whole webpage.When a user click edit button the selected option from the drop down list is updated. After searching a while i found some tutorials for this method and took ajax codes from there. But when i tried those in my database; it didn't worked out. Below is the sample code for my php script, parent file contains both ajax script and php code in a single php file called samefile.php. Below script only contains the problematic codes, some html and php codes are intentionally removed.
//THIS AJAX SCRIPT FETCHES VALUES FROM THE SELECTED DROPDOWN
<script>
function get_da(str){
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:$("#dropdown").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
}
);
</script>
///////////////////////////////FIRST BLOCK//////////////////
<?php
//THIS PHP SCRIPT GENERATES DROP DOWN VALUES FROM DATABASE
echo "<select name='dropdown' onChange='get_da(this.value)'>";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
/////////////////////////////SECOND BLOCK//////////////////////////////
//THIS PHP SCRIPT VALIDATES THE SELECTED DROPOWN VALUE AND PASS THOSE VALES FOR FURTHER PROCESSING.
if(isset($_REQUEST['dropdown1']))
{
$name=get_the_selected_dropdown_name; //i dont know how to fetch name from dropdown menu
$sql = "UPDATE table SET name = '$name' WHERE id =10";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
//////////////////////////////THIRD BLOCK////////////////////////////////////
?>
I believe this is how my above script works. when a user select a particular option from the drop down menu this function onChange='get_da(this.value)' sends the value (both id and name) to ajax query. in ajax query the drop down values are collected (both id and name) and renames as dropdown1 (data: { dropdown1:$("#dropdown").val()}) and pass it to php script inside the same file. Php script confirms the request from ajax using this if(isset($_REQUEST['dropdown1'])) and the script inside will be executed.
Please forgive me if i made a mess of my code. I suck at java script and ajax so am not sure whether my coding is right for those scripts. if possible can you suggest any other scripts for updating mysql database using ajax drop down list.
EDITED
ID DROPDOWN VALUE
1 ROY
2 TOM
3 CHASE
4 THOMAS
5 GEORGE
6 MICHAEL
have tried by printing the value you are sending in ajax request. You are passing this.value to your function get_da(str). But I think you are using it anywhere , In ajax post you are sending the value like
data: {dropdown1:$('#dropdown').val()}
But this will not post your selected vaule from dropdown, Try like this:
<script>
function get_da(this){
var id = $("#dropdown option:selected").val();
var selectedName = $("#dropdown option:selected").text();
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:id, name:selectedName}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
//drawVisualization();
},
});
}
</script>
Hope this will work.
Your dropdown script should be like this:
<?php
echo "<select name="dropdown" onchange="get_da()" id="dropdown">";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
This will send your selected value from drop down to your samefile.php.And also you are not doing good with your php script it should be like:
if(isset($_REQUEST['dropdown1']))
{
$id=$_REQUEST['dropdown1'];
$name=$_REQUEST['name'];
$sql = "UPDATE table SET name = '$name' WHERE id ='$id'";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
?>

Executing javascript in an an AJAX response - Codeigniter

I am using Codigniter to redo a website. I have the following controller code:
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
foreach ($topics as $val) {
echo "<pre id = \"pre_" . $val['id'] . "\">";
echo $val['formula'];
echo "<br />";
// generate a unique javascript file.
$f = "file_" . $val['id'] . ".js";
if (!file_exists($f));
{
$file = fopen($f,"w");
$js = "\$(\"#button_" . $val['id'] . "\").click(function(){\$(\"#pre_" . $val['id'] . "\").hide();});";
fwrite($file,$js);
fclose($file);
}
echo "<script src=\"file_" . $val['id'] . ".js\"></script>";
echo "<button id=\"button_" . $val['id'] . "\">Hide</button>";
echo "</pre>";
}
}
The basic idea to make an AJAX call to the function to retrieve a list of formulas.
The purpose of the javascript is to be able to hide any of the formulas by
hiding the <pre> </pre> tag that surrounds them The js file (i.e. file_1.js) I generate looks like:
$("#button_1").click(function(){$("#pre_1").hide();});
and the button code is:
<button id="button_1">Hide</button>
The problem is that it doesn't work. The files get generated, but clicking on the "Hide"
button does nothing. The puzzling part is that the exact same code works on the original website where I just make an AJAX call to a PHP file that generates the same code.
Any ideas what could be going on here?
Edit:
On my old website I used:
$query = "SELECT * FROM topics WHERE term LIKE '%" . $term . "%'";
$result = mysql_query($query);
while ($val = mysql_fetch_array($result))
{
echo "<pre id = \"pre_" . $val['id'] . "\">";
etc.
etc.
}
and everything works fine. If I now put the results of the while loop into to an array and then do a foreach loop on that, the results are very intermittent. I'm wondering if the foreach loop is the problem.
i think you can return list buttons in json response
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
$response = array('buttons' => $topics);
header('Content-Type: application/json');
echo json_encode( $arr );
}
so client can parse which button element to be hide.
<script type="text/javascript">
$(document).ready(function(){
$('somEL').on('submit', function() { // This event fires when a somEl loaded
$.ajax({
url: 'url to getTopics() controller',
type : "POST",
data: 'input_data=' + $(this).val(), // change this based on your input name
dataType: 'json', // Choosing a JSON datatype
success: function(data)
{
for (var btn in data.buttons) {
$(btn).hide();
}
}
});
return false; // prevent page from refreshing
});
});
</script>

How do I delete a MySQL record using Ajax and Jquery?

I'm not sure how to get the post title into the jquery .ajax call. I am able to create and display my blog posts, now I'm trying to add functionality to delete and edit. I'm starting with delete since it's obviously the easier of the two. How do I get the blog title from the post array into my functions.js file so that I can delete the matching record in my Database? Also... Thanks!
HTML
<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result))
{
echo'<div class="blog"><h3 class="blog">' . $row['Title'] . "</h3><h3>" . $row['Date'] . "</h3><h3>" . $row['Tag'] . "</h3><hr>";
echo'<p class="blog">' . $row['Body'] . '</p><button id="editPost" type="button">Edit</button><button id="deletePost" type="button">Delete</button><button id="commentPost" type="button">Comment</button></div>';
}
?>
Functions.php
$function= $_POST['function'];
$title = $_POST['title'];
if($function == "deletePost")
deletePost($title)
function deletePost($title){
$sql = "DELETE FROM blog WHERE Title = '$title';";
mysqli_query($mysqli, $sql);
}
Functions.js
$(document).ready(function(){
$('#deletePost').on('click', function(){
$.ajax({
url: 'functions.php',
data:{function: "deletePost", title: "how do I get the blog title here"}
success: function(data){
//confirmation of deletion
}
});
});
});
Since you are expecting a POST request, you'll need to specify that while making the AJAX request.
$.ajax({
url: 'functions.php',
type: 'POST', // specify request method as POST
...
});
That should do it.
Try This
<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result))
{
echo'<div class="blog"><h3 class="blog">' . $row['Title'] . "</h3><h3>" . $row['Date'] . "</h3><h3>" . $row['Tag'] . "</h3><hr>";
echo'<p class="blog">' . $row['Body'] . '</p><button id="editPost" type="button">Edit</button><a class="deletePost" rel="'. $row['Title'] .'" href="#" >Delete</a><button id="commentPost" type="button">Comment</button></div>';
}
?>
$(document).ready(function(){
$(".deletePost").on('click', function(){
$.ajax({
url: 'functions.php',
type: 'POST',
data:{function: "deletePost", title: $(this).attr('rel')}
success: function(data){
//confirmation of deletion
}
});
});
});

Categories

Resources