After both sql commands are run, JSON should send an updated result to the AJAX script. Upon triggering, a spot opens in the page where the data should be populating, but nothing there. The PHP below is not creating any error messages and the data is updating to the db. I wish I had a more specific type of question but Im not finding the cause of the problem.
$storyidr=$_POST['storyidr'];
$mysqli = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());";
$sql .= "SELECT AVG(rank) AS avrank from ratings WHERE storyidr = $storyidr";
if($mysqli->multi_query($sql))
{
if ($result = $mysqli->store_result())
{
$data = mysqli_fetch_assoc($result);
$avrank = $data['avrank'];
if(is_null($avrank)){$avrank ="null";}
if(!$mysqli)
{
$arr = array ('status'=>'fail');
echo json_encode($arr);
}
else
{
echo json_encode($avrank);
}
exit;
}
}
AJAX
<script type ="text/javascript">
$('#products .rateit').bind('rated reset', function (e) {
var ri = $(this);
var value = ri.rateit('value');
var storyidr = ri.data('storyidr');
ri.rateit('readonly', true);
$.ajax({
url: '../rate.php',
data: { storyidr: storyidr, value: value },
type: 'POST',
success: function (data) {
$('#response').append('<li>' + data + '</li>');
},
error: function (jxhr, msg, err) {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
});
</script>
html
<ul id="response">
</ul>
Related
I'm dev a ratings script. I need to update SQL and then find an average based on criteria (storyidr). With the following script I'm getting {"status":"fail"} from AJAX after it's triggered. I need to be reporting the value $avrank.
$storyidr=$_POST['storyidr'];
$con = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());";
$sql .= "SELECT AVG(rank) AS avrank from ratings WHERE storyidr = $storyidr";
if($mysqli->multi_query($sql))
{
if ($result = $mysqli->store_result())
{
$data = mysqli_fetch_assoc($result);
$avrank = $data['avrank'];
if(!$result)
{
$arr = array ('status'=>'fail');
echo json_encode($arr);
}
else
{
echo json_encode($avrank);
}
exit;
}
}
here's what I'm using in AJAX, but i don't think the issue is there:
$.ajax({
url: '../rate.php',
data: { storyidr: storyidr, value: value },
type: 'POST',
success: function (data) {
$('#response').append('<li>' + data + '</li>');
},
error: function (jxhr, msg, err) {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
thank you in advance!
You can try with below
$mysqli = new mysqli("localhost", "user", "password", "database");
$sql .= "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());"
$sql .= "SELECT AVG(rank) AS avrank from ratings WHERE storyidr=$storyidr;"
$mysqli->multi_query($sql);
for more info go to http://us2.php.net/manual/en/mysqli.quickstart.multiple-statement.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);
}
?>
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.
I'm trying to develop an application which gets the the response from the MySQL database using ajax post and update in list selector, but the list is displaying empty, can some one help me out from this please.....
code for .js:
SecondAssistant.prototype.setup = function() {
this.selectorChanged = this.selectorChanged.bindEventListener(this);
Mojo.Event.listen(this.controller.get('firstselector'), Mojo.Event.propertyChange, this.selectorChanged);
this.names = [];
try {
new Ajax.Request('http://localhost/projects/testingasdf.php', {
method: 'post',
parameters: {
'recs': getallrecords,
'q': q
},
evalJSON: 'true',
onSuccess: function(response){
var json = response.responseJSON;
var count = json.count - 1;
for(i=0; i<count; i++){
this.names.push({
label: json[i].name,
value: '0'
});
}
this.controller.modelChanged(this.model);
}.bind(this),
onFailure: function(){
Mojo.Controller.errorDialog('Failed to get ajax response');
}
});
}
catch (e){
Mojo.Controller.errorDialog(e);
}
this.controller.setupWidget("firstselector",
this.attributes = {
label: $L('Name'),
modelProperty: 'currentName'
},
this.model = {
choices: this.names
}
);
};
code for php:
<?php
header('Content-type: application/json'); // this is the magic that sets responseJSON
$conn = mysql_connect('localhost', 'root', '')// creating a connection
mysql_select_db("test", $conn) or die('could not select the database');//selecting database from connected database connection
switch($_POST['recs'])
{
case'getallRecords':{
$q = $_POST['q'];
//performing sql operations
$query = sprintf("SELECT * FROM user WHERE name= $q");
$result = mysql_query($query) or die('Query failed:' .mysql_error());
$all_recs = array();
while ($line = mysql_fetch_array($result,MYSQL_ASSOC)) {
$all_recs[] = $line;
}
break;
}
}
echo json_encode($all_recs);
// Free resultset
mysql_free_result($result);
// closing connection
mysql_close($conn);
?>
I would move the model updating code out of the SecondAssistant.prototype.setup method and have it fire somewhere in SecondAssistant.prototoype.activate.
Also call modelChanged
this.controller.modelChanged(this.model);
There is a typo on bindEventListener - should be bindAsEventListener and the return of the bind should be a different object:
this.selectorChangedBind = this.selectorChanged.bindAsEventListener(this);
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! :)