Parsing values in JSON - php

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.

Related

Get data from JSON.parse from ajax call

I've been looking everywhere for the answer.
I have the JSON string
"[{"id":"0"}]"
I've tried
obj['id'] and obj.id
but that doesn't work
$.ajax({
url: 'php/checkdoctorappointmentonday.php',
data: 'doctorName=' + doctorName + '&dayOfEvent=' + date1,
type: "POST",
success: function (json) {
obj = JSON.parse(json.data)[0];
b = obj.id;
}
});
return true;
}
Am I missing anything?
This is the php used to get the result
Edit:
<?php
$doctorName = $_POST['doctorName'];
$dayOfEvent = $_POST['dayOfEvent'];
// Query that retrieves events
$query = "SELECT COUNT(id) AS 'id'
FROM doctoravailability
WHERE start >='$dayOfEvent' AND start < DATE_ADD('$dayOfEvent', INTERVAL 1 DAY)
AND title = '$doctorName'
AND backgroundColor = 'red'
";
// connection to the database
try {
$bdd = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($query) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
As per comments, the object is actually an array containing an object
var str = "[{\"id\":\"0\"}]";
var obj = JSON.parse(str)[0];
alert(obj.id);
http://jsfiddle.net/6ae0bgag/
obj["id"] would have also worked, its the same as obj.id
Does your JSON string actually have the start and end " in it, or have you just added them there to illustrate that it is a string?
Assuming that our data string actually has the ", then you just want to use the syntax
[{"id":"0"}]
Try this:
JS
$.ajax({
url: 'php/checkdoctorappointmentonday.php',
data: {
doctorName: doctorName,
dayOfEvent: date1
},
type: "POST",
dataType: 'json',
success: function (data) {
console.log(data);
b = data.0.id;
}
});
PHP
<?php
$doctorName = $_POST['doctorName'];
$dayOfEvent = $_POST['dayOfEvent'];
// Query that retrieves events
$query = "SELECT COUNT(id) AS 'id'
FROM doctoravailability
WHERE start >='$dayOfEvent' AND start < DATE_ADD('$dayOfEvent', INTERVAL 1 DAY)
AND title = '$doctorName'
AND backgroundColor = 'red'
";
// connection to the database
try {
$bdd = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($query) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
return $resultat->fetchAll(PDO::FETCH_ASSOC);
?>

Passing json to php and getting response

I am new to php/ajax/jquery and am having some problems. I am trying to pass json to the php file, run some tasks using the json data and then issue back a response. I am using the facebook api to get log in a user,get there details, traslate details to json, send json toe the server and have the server check if the users id already exists in the database. Here is my javascript/jquery
function checkExisting() {
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.id );
var json = JSON.stringify(response);
console.log(json);
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
}
Here is my php file
if(isset($_POST['user']) && !empty($_POST['user'])) {
$c = connect();
$json = $_POST['user'];
$obj = json_decode($json, true);
$user_info = $jsonDecoded['id'];
$sql = mysql_query("SELECT * FROM user WHERE {$_GET["id"]}");
$count = mysql_num_rows($sql);
if($count>0){
echo 1;
} else{
echo 0;
}
close($c);
}
function connect(){
$con=mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to Database: " . mysqli_connect_error();
}else{
return $con;
}
}
function close($c){
mysqli_close($con);
}
I want it to return either 1 or 0 based on if the users id is already in the table but it just returns a lot of html tags. . The json looks like so
{"id":"904186342276664","email":"ferrylefef#yahoo.co.uk","first_name":"Taak","gender":"male","last_name":"Sheeen","link":"https://www.facebook.com/app_scoped_user_id/904183432276664/","locale":"en_GB","name":"Tadadadn","timezone":1,"updated_time":"2014-06-15T12:52:45+0000","verified":true}
Fix the query part:
$sql = mysql_query("SELECT * FROM user WHERE {$_GET['id']}");
Or another way:
$sql = mysql_query("SELECT * FROM user WHERE ". $_GET['id']);
Then it's always better to use dataType in your ajax
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
dataType: "jsonp", // for cross domains or json for same domain
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
Where is $jsonDecoded getting assigned in your PHP? Looks unassigned to me.
I think you meant to say:
$obj = json_decode($json, true);
$user_info = $obj['id'];
And your SELECT makes no sense. Your referencing $_GET during a POST. Maybe you meant to say:
$sql = mysql_query("SELECT * FROM user WHERE id = {$user_info}");

Ajax post in oscommerce

I'm trying to update my database on the event of a change in my select box. The php file I'm calling on to process everything, works perfectly. Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry will be updated under the products table, ex: www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time I've ever used anything other than serialize, so any pointer would be appreciated!
Would it not be enough to define your URl like so:
url: "dropship_process.php?pID="+ pid +"&drop-shipping="+ dropshippingid
Your ajax code is not correct. replace your ajax code by below code:
$.ajax({
type: "POST",
url: "dropship_process.php",
dataType: 'text',
data: {"pID": pid,'drop-shipping': dropshippingid},
success: function(returnData) {
alert("success");
}
});

setup webos list selector choices with ajax json response dynamically

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

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! :)

Categories