jquery ajax request fails - php

I'm new to web programming and I'm trying to select value for a selector box based on value selected in another selector box. Below is the jquery code snippet and php script for your reference. thanks for the help in advance.
jquery-ajax code
$(function(){
$("#tier").change(function(){
var formdata = {'tierval':document.getElementById("tier").value};
alert("Selected Tier : "+document.getElementById("tier").value);
$.ajax({
type: "POST",
url: "/includes/getplayers.php",
data: formdata,
success: function(data)
{
alert("called getplayers.php");
$("#opp").empty();
$("#opp").html(data);
},
error:function()
{
alert('ajax failed');
}
});
});
});
php script:
<?php
if (isset($_POST['tierval']))
{
$tier = $_POST['tierval'];
}
$query = "select PlayerID,First_Name from GOFTEL.PLAYER where TierID = $tier";
$result = mysqli_query($pconn, $query);
$row = mysqli_fetch_assoc($result);
while($row)
{
echo '<option value=\"$row[PlayerID]\" > $row[First_Name] </option>';
}
/* free result set */
$result->free();
/* close connection */
$pconn->close();
?>

Since you are already using jQuery consider the below:
var formdata = {'tierval':$("#tier").val};
alert("Selected Tier : "+$("#tier").val);
// or
console.log(formdata); // using the browser console
// or
alert( this.value );
// or
console.log($(this).val())
then you need to output something in the php script, so that #opp actually gets populated with the result, so
$query="select PlayerID,First_Name from GOFTEL.PLAYER where TierID = $tier";
$result=mysqli_query($pconn, $query);
$row=mysqli_fetch_assoc($result);
print $row['First_Name'];
Then evaluate what you get in the console or alerts and go from there.

You need to use below code in php script
while($row=mysqli_fetch_assoc($result)){
echo "<option value=" . $row[PlayerID]. ">" . $row[First_Name] . "</option>";
}

Related

How do we pass data in ajax? [duplicate]

This question already has answers here:
How can I get the data-id attribute?
(16 answers)
Closed 5 years ago.
I am new to Ajax and I am confused as to how we pass data in Ajax. I have an index.php file which displays some data, it has a link to delete the record, now the problem is, I am not able to figure out how to transfer the id value from index.php of the selected record to ajax file. Also, how should I go about once I have fetched the value in delete.php page where lies the code to delete records.
I have coded as below.
index.php
<div id="delMsg"></div>
<?php
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
echo"</tr>";
}
echo "</table>";
?>
ajax-file.js
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(str){
$('#delMsg').html(str);
}
})
})
})
delete.php
<?php
$id=$_GET['id'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"delete from member where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "error";
}
?>
Hopefully this conveys the idea of how an AJAX call works.
The first thing we want to do is setup our trigger, which in your case is a button with an onclick event.
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<!-- <button id="delete">Delete Something</button> -->
<button id="delete" onclick="onClickHandler(5)">Delete Something</button>
<p id="message">AJAX</p>
<script>
/* Notice I removed the document ready */
function onClickHandler(id)
{
event.preventDefault();
$.ajax(
{
url:"delete.php",
method:"POST", /* In the real world you want to use a delete here */
data: { /* plugin your data */
id: id,
name: "Bob",
age: 25
},
dataType:"html",
success: function(success) {
// Handle the success message here!
if (success) {
$('#message').text("Your message was received!");
}
},
error: function(error) {
// Handle your errors here
$('#message').text("Something went wrong!");
}
});
};
</script>
Notice how my data is prepared in the data object. I leave it up to you to figure out how to grab data and set it in the right field. You could: $('#someId').value(); or pass it through a function. If this is a source of confusion I can clarify.
data: { /* plugin your data */
id: 1,
name: "Bob",
age: 25
},
Next, we need to setup our script.
delete.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Obviously validate the data.
// But this is how you access it.
// $_POST is a global array, so you can access it like so:
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
// Do your server side stuff...
$sql = "DELETE FROM member
WHERE id = '{$id}' AND name = '{$name}' AND age = '{$age}'";
// Do your SQL (delete) here
// $con = mysqli_connect("localhost","root","","ajaxtest");
// Use prepared statements http://bobby-tables.com/php
// $data = mysqli_query($con,"delete from member where id='$id'");
// if ($data) { // Your condition
// This is where you would check if the query passed
// and send back the appropriate message.
if ($id) {
echo json_encode($id);
}
else {
echo http_response_code(500);
}
}
else {
echo "You don't belong here!";
}
you should use what is called JSON ( Javascript Object Notation, I think). This will let you order your data better to do that you have to use, json_encode.
Now I am not exactly sure what you mean by this id value from index.php
But taking your index.php file, I would change it like this
//make sure the is no space here
<?php
//start output buffering
ob_start();
$html = ['<div id="delMsg"></div>'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
$html[] = "<table>";
while($row=mysqli_fetch_array($data))
{
$html[] = "<tr>";
for($i=0;$i<$col;$i++)
{
$html[] = "<td>".$row[$i]."</td>";
}
$html[] = "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
$html[] = "</tr>";
}
$html[] = "</table>";
$result = [
'html' => implode("\n", $html),
'debug' => ob_get_clean()
];
header("Content-type:application/json");
echo json_encode($result);
//?> ending tags are undesirable
Your JavaScript part will change too
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(data){
$('#delMsg').html(data.html);
}
})
})
})
You can see now that instead of just returning HTML, We will be returning it like this data in the Javascript and $result in php
{
html : '<div id=" ...',
debug : ""
}
I added ob_start and ob_get_clean this can be helpful because you cannot just echo content when outputting JSON, so this will catch any echo or print_r type content and put that into the debug item in the return.
Just replace
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
To
echo "<td><a onclick="deleteRow($row[0])">Delete</a></td>";
Javascript
function deleteRow(recordID)
{
event.preventDefault();
$.ajax({
type: "GET",
url: "delete.php",
data:{id: recordID}
}).done(function( result ) {
alert(result);
});
}
In your PHP I recommend you to use PDO which is more easy and protected from SQL injection attacks.
PHP:
$db = new PDO('mysql:host=localhost;dbname=yourDB','root','');
$query = $db->prepare("Delete From yourTableName Where ID=:ID");
$id=$_GET['id'];
$query->bindParam('ID', $id);
$query->execute();
if ($query->rowCount()) {
echo "success";
}
else
{
echo "fails";
}

Retrieving multiple values via PHP/jQuery/Ajax

I'm using the following jQuery to retrieve values for a 'Live Search' field:
$(document).ready(function(){
/* LIVE SEARCH CODE - START HERE*/
var UserID = ('<?php echo $_SESSION['UserID'] ?>');
$(document).ready(function(){
$('.clLiveSearchAccount').on("keyup" , "[id*=txtAccountID]", "input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var ParentTransID = $(this).prev().val();
alert(UserID);
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("Apps/Finance/incGetAccounts.php", {term: inputVal, usr: UserID }).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".clLiveSearchAccount").find('#txtAccountID').val($(this).text());
$(this).parent(".result").empty();
});
});
I'm using this PHP ajax handler:
<?php
/* ------------------------------------------------ */
$link = mysqli_connect("xxx", "xxx", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$term = mysqli_real_escape_string($link, $_REQUEST['term']);
$user = mysqli_real_escape_string($link, $_REQUEST['usr']);
if(isset($term)){
// Attempt select query execution
$sql = "SELECT * FROM tblAccounts WHERE Name LIKE '%" . $term . "%' AND UserID=" . $user;
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<p>" . $row['Name'] . "</p>";
}
// Close result set
mysqli_free_result($result);
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// close connection
mysqli_close($link);
?>
But how do I send back (and accept) an additional value, so the String Name and Integer Key?
It seems you are looking to send JSON data. Put the HTML you want to echo in a variable.
$html ="<h1>PHP is Awesome</h1>";
$myVariable = 3;
echo json_encode(array( 'variable1' => $myVariable, 'html' => $html ));
and you'll need a success callback in your javascript
success: function($data) {
var html = $data.html;
var myVar = $data.variable1;
// other stuff
}
look up a tutorial on PHP JSON
W3schools always a good place to start
https://www.w3schools.com/js/js_json_php.asp
I always do this return format in ajax.
Success Response
// PHP
$result = [
'success' => true,
'variable' => $myVariable,
'html' => $html,
];
Fail Response
// PHP
$result = [
'success' => false,
'err_message' => 'Error message here!',
],
use json encode when returning the data to the ajax example json_encode($result) and also dont forget to add dataType setting in your ajax so that it will expect json format response.
Ajax fn
$.ajax({
url: 'path to php file',
type: '' // specify the method request here i.e POST/GET
data: {} // data to be send
dataType: 'JSON',
success: function(res) {
if (res.success) {
...
} else {
// you can put the error message in html by accessing res.err_message
}
}
});

How to assign ajax response to Variables

I have drop down Select box as follows
<?php
$sql = "SELECT scheduleName FROM schedule";
$result = mysqli_query($link,$sql);
echo "<select name='schedule' id='schedule'>";
echo "<option value=''>-- Select Schedule --</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['scheduleName'] . "'>" . $row['scheduleName'] . "</option>";
}
echo "</select>";
?>
And I have a file called processClg.php as follows
<?php
include "config.php";
if ($_POST['type']=='POST')
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE 'Row id of drop down selection'";
$res = mysqli_query($link,$qry);
}
?>
How can I call processClg.php file on $("#schedule").change(function ());by assigning Row id of drop down selection as where condition.
Update
Am getting Response from processClg.Php as follows
[{"id":"2","scheduleName":"shanth","subject":"Patho","university":"Dali","facultyName":"Dr","scheduleStartDate":"2015-06-05","scheduleEndDate":"2015-06-09"}]
How to assign response values from ajax call to the following Php variables
<?php
$scheduleStartDate = '';
$scheduleEndDate = '';
?>
Any help my greatly appreciated.
$("#schedule").change(function() {
var value = $('#schedule option:selected').text();
var ajaxCheck = $.ajax({
url: 'processClg.php',
type: 'POST', // had mention post bcoz u mention in processClg.php
dataType: 'json', // processClg.php will return string means change to text
data: { id: value },
success: function(data){
console.log('success');
itrToRead(data);
}
});
});
function itrToRead(data) {
$(data).each(function(key, value){
console.log('key is: '+key+' and value is: '+value);
});
}
processClg.php
<?php
include "config.php";
if ($_POST['type']=='POST') {
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_POST['id']."'";
$res = mysqli_query($link,$qry);
echo $res;
}
?>
You can call ajax as follows:
var RowId;
$.ajax({
type: "POST",
async: false,
url: url,
data: postdata,
//dataType: "json",
success: function (data) {
RowId = data;
}
});
The fact is that to assign response to variable is pass the parameter async: false,
Then its work.
I guess you have your dropdown in your rendered page and you want to send the selected value to the php page:
$("#schedule").change(function(){
var val2pass = $(this).find(':selected').val(); // get the value
$.ajax({
url: 'processClg.php',
type:'post', // <-----you need to use post as you are using $_POST[]
data: { rowid : val2pass }, //<---pass the value
success: function(data){
itrToRead(data);
}
});
});
So now on the php side you need to do this:
<?php
include "config.php";
if ($_POST['type']=='POST')
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_POST['rowid']."'";
$res = mysqli_query($link,$qry);
}
?>
Your procellClg.php will be
<?php
include "config.php";
if (isset($_REQUEST['qid']))
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_REQUEST['qid']."'";
$result = mysqli_query($link,$qry);
echo "<select name='schedule' id='schedule'>";
echo "<option value=''>-- Select Schedule --</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['scheduleName'] . "'>" . $row['scheduleName'] . "</option>";
}
echo "</select>";
}
?>
and then make Ajax function call
$("#schedule").change(function() {
val = $(this).val();
$.ajax({
type: "POST",
async: false,
url: 'processClg.php',
data: {qid:val},
success: function(data){
$(this).html(data);
}
});
});

jQuery and MySQL

I have taken a jQuery script which would remove divs on a click, but I want to implement deleting records of a MySQL database. In the delete.php:
<?php
$photo_id = $_POST['id'];
$sql = "DELETE FROM photos
WHERE id = '" . $photo_id . "'";
$result = mysql_query($sql) or die(mysql_error());
?>
The jQuery script:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The div goes away when I click on it, but then after I refresh the page, it appears again...
How do I get it to delete it from the database?
EDIT: Woopsie... forgot to add the db.php to it, so it works now >.<
There's no way the php could even come close to working. Where is the database? Check out http://www.php.net/manual/en/mysql.examples-basic.php from which you can see there's more to the database than just a query.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
You have your data as a GET string, but you are using a POST request, try changing your string variable to an object. Like :
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = { id : id };
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
Plus I am hoping you are preparing your MySQL connection properly in your PHP, you cannot just call mysql_query and hope it will know which database you mean, and how to connect to it by itself :)
Look at #Quotidian answer! :)

How to update rows in jQuery with PHP and HTML

My PHP script generates a table with rows which can optionaly be edited or deleted. There is also a possibilety to create a new Row.
I am having a hard time to figure out how to update the HTML rows which are generated through PHP and inserted via jQuery. After the update it must be still editable. The HTML is generated into a div.
jQuery (insert generated HTML/wait for action)
PHP (generate html)
Go back to step 1)
(EDIT: Corrected an error and changed script to answer)
PHP
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME, $dbh) or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if ($action == "new") {
mysql_query("INSERT INTO place (id, name) VALUES (NULL, $name)");
}
elseif ($action == "edit") {
mysql_query("UPDATE place SET name = $name WHERE id = $id");
}
elseif ($action == "delete") {
mysql_query("DELETE FROM place WHERE id = $id");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=" . $row["id"] . " class=inputfield_td><input class=inputfield_place type=text value=" . $row["name"] . " /></td><td class=place_name>" . $row["name"] . "</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function(html) {
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display", "none").prevAll(".place_name").css("display", "none").prevAll(".inputfield_td").css("display", "block").nextAll(".cancel").css("display", "block").nextAll(".save").css("display", "block").prevAll(".inputfield_td").css("display", "block");
});
$(".cancel").live("click", function() {
$(this).css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none").nextAll(".save").css("display", "none");
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display", "none").prevAll(".cancel").css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none");
alert("save name: " + myvariable1 + " save id: " + myvariable2);
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
alert(myvariable3);
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {
action: "new",
name: "" + myvariable4 + ""
});
});
});
place all your event-handlers outside the ajax function and use the live() method instead. And you need to include what data to send when using ajax. From visualjquery:
$(function() {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(".edit").live("click", function() {
//event handler code here
});
//more event handlers
});
I think you are not getting click events for editing, deleting etc. after new rows from php are appended to the div.
Try using jquery live plugin to bind click events as and when new stuff is created. Please refer to this question dealing with similar problem.
Like peirix and TheVillageIdiot pointed out, the live plugin maybe useful. However, there are some other things you may got wrong in your code:
First, your HTML isn't valid. You have to put quotes around attribut values. You could do this within quotes by escaping inner quotes with a backslash:
echo "<input type=\"text\" class=\"inputfield_visible\" />";
since this looks not that nice, you could leave the PHP part and write pure HTML if you change this:
<?php
...
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
To that (IMHO by far more readable):
<?php
...
?>
</tbody>
</table>
<input type="text" class="inputfield_visible" />
<button class="new">Neu</button>
Secondly, and that seems to be even more important, it looks to me like you have a SQLInjection vulnerability, because you pass the field values directly to mysql without using mysql_real_escape_string first. I'm not that into PHP, so maybe I got that wrong, but what happens if you enter ';-- into you input fields?

Categories