JQuery ajax call failing but the direct URL works - php

I have a simple Jquery code which makes an ajax call to a php code.
$(document).ready(function(){
var $isbn = $('#isbn');
var $authorName = $('#authorName');
var $bookTitle = $('#bookTitle');
$('#searchButton').click(function(){
var isbnValue = $isbn.val();
var authorNameValue = $authorName.val();
var bookTitleValue = $bookTitle.val();
alert(isbnValue);
$.ajax({
type: "GET",
url: "php/getBooks.php",
dataType: "json",
data: {
isbn: isbnValue
},
success: function (data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
And my PhP code connects to the Database and fetches data based on the query string. Here is my PhP code.
<?php
$dsn = 'mysql:dbname=library;host=localhost';
// 'mysql:host=localhost;dbname=myDatabase'
$username = 'root';
$password = 'maddie';
$isbnValue = $_GET["isbn"];
try {
$db = new PDO($dsn, $username, $password); // also allows an extra parameter of configuration
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$isbn = $db->quote($isbnValue);
$rows = $db->query("SELECT isbn, title FROM book WHERE isbn = $isbn");
$names = array();
foreach ($rows as $row) {
$names[] = array($row['isbn'], $row['title']);
}
print json_encode($names);
} catch(PDOException $e) {
die('Could not connect to the database:<br/>' . $e);
}
?>
When I execute from jQuery I get the below error object as response
Object {readyState: 0, responseText: "", status: 0, statusText: "error"}
Wherease if I directly call the php code using the URL -
http://localhost/LibraryManagement/php/getBooks.php?isbn=970880812
I get the json object as the result. I am not sure where the error is. Any help would be helpful. Thanks in advance.

The code you supplied seems functional. I even tested it locally with jQuery 1.12.1 and had no problems at all.
The error you are receiving is indicative of an ajax call being interrupted before it gets completed. there are many things that can cause this. The most common include cross domain issues and using links or forms actions in concert with your ajax call.
See the following article for more details on this:
http://www.justinball.com/2013/02/25/jqxhr-returning-readystate-0-and-status-0/
A quick google search for:
{readyState: 0, responseText: "", status: 0, statusText: "error"}
will reveal a number of other situations where that can occur as well.
Hope this helps ;)

Related

JQuery AJAX PHP post method issue

I am trying to post values form HTML file through AJAX as a request and get a JSON formatted string as a response from PHP.
I have done the following
The Javascript file:
$(document).ready(pageLoad);
function pageLoad()
{
$("#submit").click(submitClick)
}
function submitClick()
{
var data = {Year:"2005"};
$.getJSON("db/connect.php", data, fetchData);
}
function fetchData(data)
{
$.each(data, function(index, element) {
$("#content").append(data[index].Name + "<br />");
})
}
The PHP file
<?php
$server = "localhost";
$user = "amey";
$pass = "";
$database = "education";
echo $_POST["Year"];
$conn = mysql_connect($server, $user, $pass) or die("Unable to connect to MySQL");
mysql_select_db($database, $conn);
$query = "select * from BabyNames";
$result = mysql_query($query) or die(error_get_last());
$json = array();
while($row = mysql_fetch_array($result))
{
$json[] = $row;
}
echo json_encode($json);
mysql_close($conn);
?>
I can not retrieve the Year value in the PHP file. I've also tried using $.post and $.ajax function. In $.ajax function, when I remove the dataType: "json", the post method works.
Please make changes in your code,
if your php code working fine.
$(document).ready(function() {
var pageLoad = function() {
$("#submit").click(function(){
submitClick();
})
});
pageLoad();
});
if you want submit form/data on click "#submit" then no need to pageLoad function
$(document).ready(function() {
$("#submit").click(function(){
submitClick();
});
});
});
$.getJSON() method does an HTTP GET and not POST. You need to use $.post().
$.post(url, dataToBeSent, function(data, textStatus) {
//data contains the JSON object
//textStatus contains the status: success, error, etc
}, "json");
click here for solution more solution

Error with JSON Ajax get method

I am using a jquery ajax get method to fetch information from the server however I am having trouble parsing the information so that I may use it. My website has a gallery of products that will filter its items based on category.
Here is the jQuery ajax function:
$('.category').click(function() {
var category;
if ($(this).hasClass('Shirts')) {
category = 'shirts';
}
if ($(this).hasClass('Hats')) {
category = 'hats';
}
if ($(this).hasClass('Acc')) {
category = 'acc';
}
$.ajax({
type: 'GET',
url: 'galleryfetch.php',
data: { 'category' : category },
dataType: 'json',
success: function(data) {
arr = $.parseJSON(data);
alert(arr);
}
});
});
This is the php script that the information is posted to:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$category = $_GET['category'];
$conn = mysqli_connect('localhost', '*****', '*****', 'clothing');
$rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");
while ($row = mysqli_fetch_array($rows)) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
}
I using the alert in the success function to see if the information is passed succesfully but at the moment there is no alert and i get an:
Unexpected token o error.
I'm not sure if I'm parsing the information correctly or if Im not correctly using JSON
tl;dr: $.parseJSON(data); should be removed.
Your server is returning JSON (but claiming it is sending HTML, you should have header("Content-Type: application/json")).
You have told jQuery to ignore the claim that it is HTML and parse it as JSON. (This would be redundant if you fixed the above problem)
dataType: 'json',
The parsed data is passed to your success function.
You then pass that data to JSON.parse so it gets converted to a string (which will look something like [ [Object object], ... and is not valid JSON) and then errors.
Remove:
arr = $.parseJSON(data);
And just work with data.

Issue with retrieving a parameter from a $.ajax call

Hey guys I have the following $.ajax call:
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text(),
},
success: function(response) {
$('#notes_body').text(response.the_notes);
alert(response.the_notes);
}
)};
Now focus on the data: lets say I sent 'BillCosby'. That will be sent over to the file specified and i have this inside that file:
$username_notes = $_POST['nameNotes'];
Now lets say I was to just have $username_notes return in the json like this...
$returnArray = array( 'the_notes' => $username_notes );
echo json_encode($returnArray);
This would work and the response would be BillCosby. Now with that out of the way, when I try to get a value for BillCosby from my MySQL database using PDO it will return null....Before I show the code for the whole file I just want to make clear that the PDO works perfect, if I were to give the variable $username_notes the direct value of 'BillCosby' I would run through the database perfect, it only returns null if I have the $_POST['nameNotes']; in front.
getNotes.php:
$username_notes = $_POST['nameNotes'];
grabNotes($username_notes);
function grabNotes($xusername)
{
.....
$newUser = $xusername;
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
$sql = "SELECT notes FROM csvdata WHERE username = :username";
$getmeminfo = $DBH->prepare($sql);
$getmeminfo->execute(array(':username' => $newUser));
$row = $getmeminfo->fetch(PDO::FETCH_ASSOC);
$notes = $row['notes'];
$returnArray = array( 'the_notes' => $row['notes'],);
echo json_encode($returnArray);
$DBH = null;
}
So my question is, why can I not get the return value back from the PDO statement? It will work perfect if I told the PDO statement the name - 'BillCosby' inside the file that the $.ajax file calls to. But it will not work and returns null if I get the value through $_POST from the $.ajax. the funny thing is I can return the same value that was sent in.
Thanks for your time guys!
Try trimming it :
$username_notes = trim( $_POST['nameNotes'] );
Sometimes spaces in the string will cause this sort of error, and they can be hard to spot.
I often have to add the ?callback=?. So your JQuery ajax request will look like the following:
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php?callback=?',
data:
{
'nameNotes': notes_name.text(),
},
success: function(response) {
$('#notes_body').text(response.the_notes);
alert(response.the_notes);
}
)};
Also, preferrably you'd use the jQuery.getJSON method.

Query string parameters from Javascript do not make it to processing PHP script

I want to populate a jQWidgets listbox control on my webpage(when page finished loading and rendering) with values from an actual MySQL database table.
PARTIAL SOLUTION: Here
NEW PROBLEM:
I've updated the source code and if I hardcode the SQL string - the listbox gets populated. But I want to make a small JS function - popList(field, table) - which can be called when you want to generate a jQWidgets listbox with values from a MySQL database on a page.
Problem is - for some reason the $field and $table are empty when the PHP script is being executed, and I receive You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM' at line 1 error. What gives?
The page:
<div id="ListBox">
<script type="text/javascript">
popList("name", "categories");
</script>
</div>
popList(field, value):
function popList(field, table) {
$.ajax({
type: "GET",
url: 'getListOfValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: 'json',
success: function(response) {
var source = $.parseJSON(response);
$("#ListBox").jqxListBox({ source: source, checkboxes: true, width: '400px', height: '150px', theme: 'summer'});
},
error: function() {
alert('sources unavailable');
}
});
}
getListOfValues.php:
<?php
require "dbinfo.php";
// Opens a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$field = $_GET["field"];
$table = $_GET["table"];
$field = mysql_real_escape_string($field);
$table = mysql_real_escape_string($table);
$qryString = "SELECT " . $field . " FROM " . $table;
$qryResult = mysql_query($qryString) or die(mysql_error());
$source = array();
while ($row = mysql_fetch_array($qryResult)){
array_push($source, $row[$field]);
}
mysql_close($connection);
echo json_encode($source);
?>
Ok, you have a few things here. First off you need a callback function when you do the ajaxRequest. (I'll explain why in a bit.) So add the following line BEFORE your ajaxReqest.send(null);
ajaxRequest.onreadystatechange = processAjaxResponse;
Then you need to add the processAjaxResponse function which will be called.
function processAjaxResponse() {
if (ajaxRequest.readySTate == 4) {
var response = ajaxRequest.responseText;
//do something with the response
//if you want to decode the JSON returned from PHP use this line
var arr = eval(response);
}
}
Ok, now the problem on your PHP side is you are using the return method. Instead you want PHP to print or echo output. Think about it this way. Each ajax call you do is like an invisible browser. Your PHP script needs to print something to the screen for the invisible browser to grab and work with.
In this specific case you are trying to pass an array from PHP back to JS so json_encode is your friend. Change your return line to the following:
print json_encode($listOfReturnedValues);
Let me know if you have any questions or need any help beyond this point. As an aside, I would really recommend using something like jQuery to do the ajax call and parse the response. Not only will it make sure the ajax call is compliant in every browser, it can automatically parse the JSON response into an array/object/whatever for you. Here's what your popList function would look like in jQuery (NOTE: you wouldn't need the processAjaxResponse function above)
function popList(field,table) {
$.ajax({
type: "GET",
url: 'getListofValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: "json",
success: function(response) {
//the response variable here would have your array automatically decoded
}
});
}
It's just a lot cleaner and easier to maintain. I had to go back to some old code to remember how I did it before ;)
Good luck!

Retrieving Data with Jquery, AJAX, and PHP from a MySQL Database

I am trying to figure out how to retrieve data from a MySQL database using an AJAX call to a PHP page. I have been following this tutorial
http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form/
But i cant figure out how to get it to send back json data so that i can read it.
Right now I have something like this:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "ajax.php",
data: "code="+ code,
datatype: "xml",
success: function() {
$(xml).find('site').each(function(){
//do something
});
});
});
My PHP i guess will be something like this
<?php
include ("../../inc/config.inc.php");
// CLIENT INFORMATION
$code = htmlspecialchars(trim($_POST['lname']));
$addClient = "select * from news where code=$code";
mysql_query($addClient) or die(mysql_error());
?>
This tutorial only shows how to insert data into a table but i need to read data. Can anyone point me in a good direction?
Thanks,
Craig
First of all I would highly recommend to use a JS object for the data variable in ajax requests. This will make your life a lot simpler when you will have a lot of data. For example:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "ajax.php",
data: { "code": code },
datatype: "xml",
success: function() {
$(xml).find('site').each(function(){
//do something
});
});
});
As for getting information from the server, first you will have to make a PHP script to pull out the data from the db. If you are suppose to get a lot of information from the server, then in addition you might want to serialize your data in either XML or JSON (I would recomment JSON).
In your example, I will assume your db table is very small and simple. The available columns are id, code, and description. If you want to pull all the news descriptions for a specific code your PHP might look like this. (I haven't done any PHP in a while so syntax might be wrong)
// create data-structure to handle the db info
// this will also make your code more maintainable
// since OOP is, well just a good practice
class NewsDB {
private $id = null;
var $code = null;
var $description = null;
function setID($id) {
$this->id = $id;
}
function setCode($code) {
$this->code = $code;
}
function setDescription($desc) {
$this->description = $desc;
}
}
// now you want to get all the info from the db
$data_array = array(); // will store the array of the results
$data = null; // temporary var to store info to
// make sure to make this line MUCH more secure since this can allow SQL attacks
$code = htmlspecialchars(trim($_POST['lname']));
// query
$sql = "select * from news where code=$code";
$query = mysql_query(mysql_real_escape_string($sql)) or reportSQLerror($sql);
// get the data
while ($result = mysql_fetch_assoc($query)) {
$data = new NewsDB();
$data.setID($result['id']);
$data.setCode($result['code']);
$data.setDescription($result['description']);
// append data to the array
array_push($data_array, $data);
}
// at this point you got all the data into an array
// so you can return this to the client (in ajax request)
header('Content-type: application/json');
echo json_encode($data_array);
The sample output:
[
{ "code": 5, "description": "desc of 5" },
{ "code": 6, "description": "desc of 6" },
...
]
So at this stage you will have a PHP script which returns data in JSON. Also lets assume the url to this PHP script is foo.php.
Then you can simply get a response from the server by:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "foo.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
// do something with data
for (var i = 0, len = data.length; i < len; i++) {
var code = data[i].code;
var desc = data[i].description;
// do something
}
});
});
That's all.
It's nothing different. Just do your stuff for fetching data in ajax.php as usually we do. and send response in your container on page.
like explained here :
http://openenergymonitor.org/emon/node/107
http://www.electrictoolbox.com/json-data-jquery-php-mysql/

Categories