Retrieving multiple values via PHP/jQuery/Ajax - php

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
}
}
});

Related

get record from php with ajax and change ID attribute

i have a ajax and php as follows but it is not changing the value of html attribute with id #respo
is there any modification require?
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
dataType: "json",
data: {reccount: reccount},
success: function(response) {
var response = ($response);
$("#respo").text(response);
},
})
and php as
<?php
$id = $_POST['reccount'];
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "testsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "SELECT response from paper WHERE ID=$id";
$result=mysqli_query($link, $sql);
while ($row = mysql_fetch_row($result)) {
$response => $row['response'];
}
echo json_encode($response);
// Close connection
mysqli_close($link);
?>
i want to assign a value of response to html element with id respo
Your code must look like
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
success:function(data){
var obj = jQuery.parseJSON(data);
document.getElementById('elementName').value = obj.varaibleName;
}
});

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";
}

jquery ajax request fails

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>";
}

How to insert data from sqllite database to remote mysql database using appcelerator titanium and php

I have tried using the following code. But it is not working. I have a temporary sqllite table, I need to insert all data from temporary database to remote mysql server.
var url = "http://bmcagro.com/manoj/insertopinion.php";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this.responseText holds the raw text return of the message (used for JSON)
// this.responseXML holds any returned XML (used for SOAP web services)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == "true") {
var newtoast = Titanium.UI.createNotification({
duration: 1000,
message: "Inserted"
});
newtoast.show();
} else {
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "False"
});
toast.show();
}
},
onerror: function(e) {
Ti.API.debug(e.error);
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "Error in Connection!!"
});
toast.show();
},
timeout:5000 });
xhr.open("POST", url);
xhr.send({names: names});
});
and the php code is
<?php
$con = mysql_connect("MysqlSample.db.8189976.hostedresource.com","MysqlSample","xszZ#123ddlj");
if (!$con) {
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db("MysqlSample",$con);
if (!$db) {
echo "Failed to select db.";
exit;
}
$names = $_POST['names'];
foreach ($names as $name) {
mysql_query("INSERT INTO seekopinion(uid,gid,opiniondescription,date,postedto) VALUES (" + $name.gid + "," + $name.tempid + "," + $name.gid + ",NOW()," + $name.gid + ")");
}
if($query) {
$sql = "SELECT * FROM MysqlSample.seekopinion";
$q= mysql_query($sql);
$row = mysql_fetch_array($q);
$response = array(
'logged' => true,
'seekopinion' => $row['seekopinion']
);
echo json_encode($response);
} else {
$response = array(
'logged' => false,
'message' => 'User with same name exists!!'
);
echo json_encode($response);
}
?>
actually iam a beginer in php as well as titanium...anybody pls help me out.
Finally i found a way out ....
I changed the entire row to a string using delimiter '-' in appcelerator and then passed the parameter to the php code...from where the code is split using explode and then inserted using for loop
the appcelerator code for posting a table from an sqllite database to mysql database..
postbutton.addEventListener('click', function(e)
{
var names = [];
var datarow ="";
var db = Ti.Database.open('weather');
var rows = db.execute('SELECT tempid,gid,name,email FROM postedto');
while (rows.isValidRow())
{
datarow=datarow+"-"+rows.fieldByName('tempid')
rows.next();
}
db.close();
var params = {
"uid": Ti.App.userid,
"opiniondescription": question2.text,
"database": datarow.toString()
};
var url = "http://asdf.com/as/asd.php";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this.responseText holds the raw text return of the message (used for JSON)
// this.responseXML holds any returned XML (used for SOAP web services)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged ==true)
{
var seekopinion11=require('seekopinion2');
var seekop11 = new seekopinion11();
var newWindow = Ti.UI.createWindow({
//fullscreen : true,
backgroundImage : 'images/background.jpg',
});
newWindow.add(seekop11);
newWindow.open({
//animated : true
});
}
else
{
var toast = Titanium.UI.createNotification({
duration: 2000,
message: response.message
});
toast.show();
}
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "There was an error retrieving data.Please try again"
});
toast.show();
},
timeout:5000
});
xhr.open("GET", url);
xhr.send(params);
});
the php code for breaking the string using explode
<?php
$con = mysql_connect("MysqlSample.db.hostedresource.com","MysqlSample","xszZ#");
if (!$con)
{
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db("MysqlSample",$con);
if (!$db)
{
echo "Failed to select db.";
exit;
}
$uid= $_GET['uid'];
$opiniondescription= $_GET['opiniondescription'];
$database= $_GET['database'];
$insert = "INSERT INTO seekopinion(uid,opiniondescription,date) VALUES ('$uid','$opiniondescription',NOW())";
$query= mysql_query($insert);
$rows = explode("-", $database);
$arrlength=count($rows);
for($x=0;$x<$arrlength;$x++)
{
$insert = "INSERT INTO seekopinionuser(sid,postedto) VALUES ((SELECT MAX(sid) FROM seekopinion),$rows[$x])";
$query= mysql_query($insert);
}
if($query)
{
$sql = "SELECT s.sid,s.opiniondescription,s.uid,u.postedto FROM seekopinion s left join seekopinionuser u on s.sid=u.sid WHERE uid=$uid AND s.sid=(SELECT MAX(sid) FROM seekopinion) ";
$q= mysql_query($sql);
$row = mysql_fetch_array($q);
$response = array(
'logged' => true,
'opiniondescription' => $row['opiniondescription'],
'uid' => $row['uid'] ,
'sid'=>$row['sid']
);
echo json_encode($response);
}
else
{
$response = array(
'logged' => false,
'message' => 'Seek opinion insertion failed!!'
);
echo json_encode($response);
}
?>

Parsing values in JSON

I am trying to pass some values to my PHP page and return JSON but for some reason I am getting the error "Unknown error parsererror". Below is my code. Note that if I alert the params I get the correct value.
function displaybookmarks()
{
var bookmarks = new String();
for(var i=0;i<window.localStorage.length;i++)
{
var keyName = window.localStorage.key(i);
var value = window.localStorage.getItem(keyName);
bookmarks = bookmarks+" "+value;
}
getbookmarks(bookmarks);
}
function getbookmarks(bookmarks){
//var surl = "http://www.webapp-testing.com/includes/getbookmarks.php";
var surl = "http://localhost/Outlish Online/includes/getbookmarks.php";
var id = 1;
$.ajax({
type: "GET",
url: surl,
data: "&Bookmarks="+bookmarks,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "getbookmarkscallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
}
function getbookmarkscallback(rtndata)
{
$('#pagetitle').html("Favourites");
var data = "<ul class='table-view table-action'>";
for(j=0;j<window.localStorage.length;j++)
{
data = data + "<li>" + rtndata[j].title + "</li>";
}
data = data + "</ul>";
$('#listarticles').html(data);
}
Below is my PHP page:
<?php
$id = $_REQUEST['Bookmarks'];
$articles = explode(" ", $id);
$link = mysql_connect("localhost","root","") or die('Could not connect to mysql server' . mysql_error());
mysql_select_db('joomla15',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM jos_content where id='$articles[$i]'";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
for($i = 0; $i < count($articles); $i++)
{
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = $post;
}
}
}
header('Content-type: application/json');
echo $_GET['onJSONPLoad']. '('. json_encode($posts) . ')';
#mysql_close($link);
?>
Any idea why I am getting this error?
This is not json
"&Bookmarks="+bookmarks,
You're not sending JSON to the server in your $.ajax(). You need to change your code to this:
$.ajax({
...
data: {
Bookmarks: bookmarks
},
...
});
Only then will $_REQUEST['Bookmarks'] have your id.
As a sidenote, you should not use alert() in your jQuery for debugging. Instead, use console.log(), which can take multiple, comma-separated values. Modern browsers like Chrome have a console that makes debugging far simpler.

Categories