Ajax - Response from another page - javascript

My HTML as follows, located in index.php
<div id="showDetails">
</div>
<div id="showList">
</div>
And my Ajax as follows, still in index.php
function funcReadRecord() {
var readrecord1 = "readrecord1";
var sometext = $('#SNOW_INC').val();
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { readrecord1 : readrecord1,
sometext : sometext } ,
success : function(data, status){
$('#showList').html(data);
}
});
}
Now, I can return my list and view the required list (shown as a list group) in index.php.
I have a button in index.php that when clicked, runs the function.
<div>
<button type="button" onclick="funcReadRecord()" class="btn btn-primary">Search SQL (LIKE)</button>
</div>
The code in findsql.php as follows
if(isset($_POST['readrecord1']) && isset($_POST['sometext'])){
$displaysql = "SELECT * from datadump where short_description LIKE '%".$_POST['sometext']."%'";
$result = mysqli_query($conn, $displaysql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$items[] = array(
"number" => $row['number'],
"priority" => $row['priority'],
"description" => $row['short_description']);
}
}
echo '<p class="lead">SEARCH SQL (LIKE)<p>';
echo '<div class="list-group">';
foreach($items as $result) {
?>
<a href="#" class="list-group-item list-group-item-action">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1"><?php echo $result['number']; ?></h5>
<small></small>
</div>
<p class="mb-1"><?php echo $result['description']; ?></p>
<small><?php echo $result['priority']; ?></small>
</a>
<?php
}
echo '</div>';
}
All I'm doing is getting the data from MySQL and assigning them to array and listing them. I know I could do it directly but I need the array in some other function.
The question is how do I make details from the array to show in showDetails div tag when I click the list? Right now, the HREF is #. I could assign a function, but not sure where to write them.
If I should write a function to return them, should I write in index.php or findsql.php?
Thanks in advance.

I understand that you need individual record information in #showDetails div right ! then
step1: assign new function while clicking the particular item as onclick="funcReadRecord(number)", this should at findsql.php file.
step2: write an ajax function in index.php which will send that particular unique id or in your case number
function funcReadRecord(number) {
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { id: number } ,
success : function(data, status){
$('#showDetails').html(data);
}
});
Step3: Write another function in findsql.php with else if block as checking id isset or not, change the query that takes the number or any key that gets only that particular record.
else if(isset($_POST['id'])){
$displaysql = "SELECT * from datadump where number = ".$_POST['id'].";
// remaining design code below
}
We can use the if-else statement to write multiple ajax calls as above.
Edited, Note: kindly ignore the syntax issue in the above code, concentrate on the process used to a single PHP file for multiple ajax calls using branching statements.

Related

Button for Updating a Database single entry with PHP AJAX Call

For Future Readers, this was my first question and the answer has been found (read comments and replies below):
First of all, i've searched in Stackoverflow and i didn't found an answer for a similar problem.
i would like to link a html Button (among many buttons) with a JQuery function. The function shall execute AJAX method like so :
HTML Code in a separated file index.php:
<button id="submitbtn" type="button" class="btn btn-success">UPDATE</button>
JQuery Function :
$('#submitbtn').on('click', function(){
var id = $(this).data('id');
$.ajax({
url: 'includes/updatequery.php',
type: 'POST',
data: {id:id},
success: function(data){
if (data) {
console.log("updated");
} else {
$('#error').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#error').html("oops" + errorThrown);
}
});
});
Here is the PHP file that should be called by AJAX Method :
<?php
include("src/db.php");
$query = "UPDATE mytable SET job='completed' WHERE id=id";
mysqli_query($conn, $query);
?>
The problem is that i CANNOT link the ID of the clicked button (because there are many buttons) to the ID of the Database Entry in order to update the Data in the Database according to this specific button.
Now i would like to have the results updated LIVE after updating the Database.
This is the PHP code that output menu items (items stored in the same Database table as before) and in front of every menu item, a badge should be displayed (with a value within it : "completed" or "not completed") :
<?php
foreach($data as $d) {
$id = $d['id'];
$mystatus = $d['status'];
?>
<li class="nav-item">
<a class="nav-link clickable blueMenuItem" id="nav-location" data-id="<?php echo $d['id']; ?>">
<i class="nav-icon fas <?php echo $d['icon']; ?>"></i>
<p><?php
echo $d["title"];
if ($d['type'] == "job") { ?>
<span id="updatedicon" class="right badge <?php if($mystatus == "completed"){echo "badge-success";} else {echo "badge-danger";}?>"><?php setJob($con, $id)?></span><?php
} ?>
</p>
</a>
</li><?php
}
?>
Here is the PHP file where the setJob method is defined :
<?php
function setJob($con, $idd) {
$sql = "SELECT status FROM mytable WHERE id=$id";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $row => $value) {
echo $value;
}
}
}
?>
Any suggestions?
Thanks
Use the data-id attribute to add the id:
<button id="submitbtn" data-id="<id>" type="button" class="btn btn-success">UPDATE</button>
https://www.w3schools.com/tags/att_global_data.asp
By default, jQuery ajax uses a Content-Type of application/x-www-form-urlencoded; charset=UTF-8. This means in PHP the POST values can be accessed using $_POST. If using a Content-Type of application/json, you will need to do this.
include("src/db.php");
$id = $_POST['id']; // make sure to sanitize this value
$query = "UPDATE mytable SET job='completed' WHERE id=$id";
mysqli_query($conn, $query);
The above example only demonstrates how to reference the id value from the POST. However, this is not secure as-is. Make sure to sanitize the value as well as protect yourself from SQL Injection using prepared statements. Prepared Statements allow you to bind variables to SQL queries which are sent separately to the database server and can not interfere with the query itself.
Updated HTML - added data-id="" to button and replace with id
<button id="submitbtn" data-id="<id>" type="button" class="btn btn-success">UPDATE</button>
Updated jQuery - use attr to get the id of row/record by using data-id attribute
$('#submitbtn').on('click', function(){
var id = $(this).attr('data-id');
$.ajax({
url: 'includes/updatequery.php',
type: 'POST',
data: {id:id},
success: function(data){
if (data) {
console.log("updated");
} else {
$('#error').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#error').html("oops" + errorThrown);
}
});
});

Entire database deletes instead of one row

I have been trying to delete a row in my mySQL database on the onclick of a delete button. But instead of the one mySQL row getting deleted, all rows in the database get deleted.
I am targeting just the specific ID, so I am unclear as to why all other ID's are getting deleted.
HTML:
<?php foreach ($movies as $movie) : ?>
<div class="col-4">
<div class="card card-cascade">
<div class="view gradient-card-header purple-gradient">
<h2><?php echo $movie['name']; ?></h2>
<p><?php echo $movie['genre']; ?></p>
</div>
<div class="card-body text-center">
<!-- Delete -->
<a type="button" class="btn-floating btn-small btn-dribbble delbutton" data-toggle="tooltip" data-placement="top" title="Delete" id="<?php echo $movie['id']; ?>"><i class="fa fa-trash-o" aria-hidden="true"></i></a>
</div>
</div>
</div>
<?php endforeach; ?>
JS:
$(function () {
// Tooltips Initialization
$('[data-toggle="tooltip"]').tooltip();
// Delete Movie
$(".delbutton").click(function() {
console.log('watch me')
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "../movieApp/delete.php", //URL to the delete php script
data : {id:info},
success : function() {
console.log("success");
},
error: function () {
console.log("failed");
},
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
PHP:
require 'config/config.php';
require 'config/db.php';
if($_POST['id']){
$id=$_POST['id'];
$delete = "DELETE FROM movies WHERE id=$id";
$result = $conn->query($delete);
}
if (mysqli_query($conn, $sql)) {
mysqli_free_result($result);
mysqli_close($conn);
echo "Worked!";
exit;
} else {
echo "Error deleting record";
}
You set ajax method POST, But Post data format is not correct as per your requirement.
Change your ajax Data like as
//var info = 'id=' + del_id;
var info = {
id : del_id
}
And
$.ajax({
/*...*/
data : info,
/*.../
});
And also check if your id field is string, If integer then change the Query string to -
#$delete = "DELETE FROM movies WHERE id='$id'";
$delete = "DELETE FROM movies WHERE id=$id";
Also change -
#$_POST['info']
$_POST['id']
Because, You didn't set $_POST['info'] anywhere in your code.
Note : And don't forget to console your correct Ajax URL
In your HTML use data-id="<?php echo $movie['id']; ?>" for the tag. Then in your JS you can pick up the value like so: var del_id = $(this).data("id");. I would also inspect element in your browser to see if you are in fact sending an "id" to your PHP script. If you are then possibly you may want to enable error debugging in your PHP script like so: error_reporting(E_ALL);
ini_set('display_errors', 1);. Also wouldn't hurt to change your SQL statement to something like this: $delete = "DELETE FROM movies WHERE id='" . $id . "'";. Good luck with this one doesn't sound too hard.

Using Ajax to create session and echo results

I'm trying my best to get this to work. But AJAX is pretty new to me. So hang in there...
Ok, I've asked a couple of questions here about getting this issue that I'm having to work. I (We)'ve come a long way. But now the next issue is here.
I'm trying to echo a session in a div using AJAX.
The AJAX code is working, I can echo plain text to the div I want it to go. The only problem I have is it does not display the title of the item.
I have some items (lets say 3 for this example) and I would like to have the custom save the Items in a Session. So when the customer clicks on save. The ajax div displays the title. And if the custom clicks the 3rd item it show the 1st and 3rd item, etc...
My HTML:
<button type="submit" class="btn btn-primary text-right" data-toggle="modal" data-target=".post-<?php the_ID(); ?>" data-attribute="<?php the_title(); ?>" data-whatever="<?php the_title(); ?>">Sla deze boot op <span class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
My AJAX code:
$(".ajaxform").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "example.com/reload.php",
success: function(data) {
$(".txtHint").html(data);
},
error: function() {
alert('Not OKay');
}
});
return false;
});
My PHP reload.php:
<h4>Saved Items</h4>
<p>Blaat...</p>
<?php echo "Product Name = ". $_SESSION['item'];?>
I saw this code on here: I'm not using this code. Only wondering if I can use it for my code, and then how?
Change session.php to this:
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
And in your HTML code:
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"name": brandName}, function(results) {
$('#SOME-ELEMENT').html(results);
});
}
How I'm getting my title();:
<?php
// Set session variables
$_SESSION["item"][] = get_the_title();
?>
Is this some thing I can use? And could someone help me with the code?
Thanks in advance!
I'm not too sure on what exactly you're trying to accomplish, but here's a quick and dirty example of making an HTTP request (POST) with a name of a product, storing it in a PHP session, and outputting all product names in the session:
HTML
<p>Product A <button class="add-product" data-product="Product A">Add Product</button></p>
<p>Product B <button class="add-product" data-product="Product B">Add Product</button></p>
<p>Product C <button class="add-product" data-product="Product C">Add Product</button></p>
<div id="response">
</div>
JavaScript
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('addProduct.php', {productName: productName}, function(data) {
$('#response').html(data);
})
});
PHP (addProduct.php)
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if ($productName) {
$_SESSION['products'][] = $productName;
}
?>
<h4>Your added products:</h4>
<ul>
<?php foreach ($_SESSION['products'] as $product): ?>
<li><?php echo htmlspecialchars($product); ?></li>
<?php endforeach;?>
</ul>

AJAX GET simple PHP Multiple variables

I need a simple way to retrieve multiple PHP variables into html divs. I searched a lot of posts but I can't found an answer.
I am looking for something like this:
go-to-index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
?>
index.php
<div class="name">Your Name is : <?php echo $name; ?></div>
<div class="phone">Your Phone Number is : <?php echo $phone; ?></div>
<div class="details">Your Details are : <?php echo $details; ?></div>
I want instead of echo to get them via AJAX Call.
What is the correct AJAX REQUEST syntax to do that?
UPDATE
My bad I do not noticed before but forgot to say I also need to load the calls one by one. I have too many requests and take a lot of time.
May the query .each() function should work like I want?
In your PHP:
<?php
echo json_encode(Array(
'name' => "John",
'phone' => "1234567890",
'details' => "Details about..."
));
Your HTML:
<div class="name">Your Name is : <span class="name_value"></span></div>
<div class="phone">Your Phone Number is : <span class="phone_value"></span></div>
<div class="details">Your Details are : <span class="details_value"></span></div>
Your jQuery:
$(document).ready(function(){
$.getJSON('user-info.php',function(data){
$(".name_value").html(data.name);
$(".phone_value").html(data.phone);
$(".details_value").html(data.details);
});
});
Note: you'll set the user-info.php string to the URL (relative or absolute) of your PHP script that grabs the user info.
You need a PHP script that will output JSON containing the values you want, and you need a Javascript handler to ask for that data and do something when it gets it. Here's an example:
# File: go-to-index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
echo json_encode(
[
'name' => $name,
'phone' => $phone,
'details' => $details
]
);
Then your HTML page:
<!-- File: index.php -->
<div class="name">Your Name is : <span class="container"></span></div>
<div class="phone">Your Phone Number is : <span class="container"></span></div>
<div class="details">Your Details are : <span class="container"></span></div>
<button class="loadMe" type="button">Click here to make things work</button>
And finally your jQuery:
$(document).ready(function() {
$('.loadMe').click(function() {
$.ajax({
// Path to your backend handler script
url: 'go-to-index.php';
// Tell jQuery that you expect JSON response
dataType: 'json',
// Define what should happen once the data is received
success: function (result) {
$('.name .container').html(result.name);
$('.phone .container').html(result.phone);
$('.details .container').html(result.details);
},
// Handle errors in retrieving the data
error: function (result) {
alert('Your AJAX request didn\'t work. Debug time!');
}
});
});
});
You can do this on any event - the button was just an example. You can also use plain Javascript or any other library, just used jQuery since you tagged it in your question.

How to call a PHP function within a page using AJAX

I wrote a php function which does the job perfectly if it is called standalone by PHP page. but I want to integrate this function in a program and want to call it when a button is clicked.
My PHP function is
function adddata($mobile){
// outside of this function, another database is already selected to perform different
//tasks with program's original database, These constants are defined only within this
//this function to communicate another database present at the same host
define ("HOSTNAME","localhost");
define ("USERNAME","root");
define ("PWD","");
define ("DBNAME","budgetbot");
// link to mysql server
if (!mysql_connect(HOSTNAME,USERNAME,PWD)) {
die ("Cannot connect to mysql server" . mysql_error() );
}
// selecting the database
if (!mysql_select_db(DBNAME)) {
die ("Cannot select database" . mysql_error() );
}
//inserting phone number into database
$query = "INSERT INTO `verify_bot` (phone_number) values('".$mobile."')";
if(!mysql_query($query)){
die( mysql_error() );
}
// wait for 2 seconds after adding the data into the database
sleep(2);
$query = "SELECT * FROM `verify_bot` WHERE phone_number = ".$mobile;
$result = mysql_query($query) or die( mysql_error() );
// if more than one records found for the same phone number
if(mysql_num_rows($result) > 1){
while($row = mysql_fetch_assoc($result)){
$data[] = $row['response'];
}
// return an array of names for the same phone numbers
return $data;
}else{
// if only one record found
$row = mysql_fetch_assoc($result);
$response = $row['response'];
return $response;
}
// end of function
}
HTML Code is written as
<form action="self_page_address_here" method="post" accept-charset="utf-8" class="line_item_form" autocomplete="off">
<input type="text" name="mobile_number" value="" placeholder="(000) 000-0000" class="serial_item" size="20" id="serialnumber_1" maxlength="10" />
<button id="verify" class="btn btn-primary">Verify</button>
<button id="cname" class="btn btn-primary"><!-- I want to print return value of the php function here --></button>
</form>
I want to call this function and assign the return value to a javascript variable by ajax/jquery.
My code to do this is...
<script type="text/javascript" language="javascript">
$('#verify').click(function(){
var value = $( ".serial_item" ).val();
//I have some knowledge about php but I am beginner at ajax/jquery so don't know what is happening below. but I got this code by different search but doesn't work
$.ajax({
url : "add_data.php&f="+value,
type : "GET"
success: function(data){
document.getElementById("cname").innerHTML = data;
}
});
});
</script>
I would like to share that the above javascript code is placed outside of documnet.ready(){}
scope
Any help would be much appreciated.
Thanks
Because your <button> elements have no type="button" attribute, they're supposed to submit the form using normal POST request.
You should either use type="button" attribute on your buttons, or prevent default form submission using event.preventDefault():
$('#verify').click(function(event){
event.preventDefault();
var value = $( ".serial_item" ).val();
$.ajax({
// there's a typo, should use '?' instead of '&':
url : "add_data.php?f="+value,
type : "GET",
success: function(data){
$("#cname").html(data);
}
});
});
[EDIT] Then in add_data.php (if you call AJAX to the same page, place this code at the top, so that no HTML is rendered before this):
if(isset($_GET['f'])){
// call your function:
$result = adddata(trim($_GET['f']));
// if returned value is an array, implode it:
echo is_array($result) ? implode(', ', $result) : $result;
// if this is on the same page use exit instead of echo:
// exit(is_array($result) ? implode(', ', $result) : $result);
}
Make sure you escape the value on $query.

Categories

Resources