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
Related
I am trying to update a php function using ajax.
I Have an array stored in localstorage.
The array contains values of clicked id's.
When I click the <tr>, the array gets updated and sent via ajax from a js file to the php file.
js file
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}else{
//remove id from array
var index = ids.indexOf(id);
if (index > -1) {
ids.splice(index, 1);
}
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}
//ajax function
$('table tr').click(function(){
var id = $(this).attr('id');
storeId(id);
var selected_lp = localStorage.getItem('reportArray');
console.log(selected_lp);
var query = 'selected_lp=' + selected_lp;
$.ajax({
type: "POST",
url: "../inc/updatelponadvdash.php",
data: { selected_lparr : selected_lp},
cache: false,
success: function(data) {
return true;
}
});
});
updatelponadvdash.php file
<?php
require_once 'inc.php';
$selected_lparr = json_decode($_POST['selected_lparr']);
foreach($selected_lparr as $value){
$dbData = $lploop->adv_lploops($value);
}
?>
Now, in the chrome network tab, when I click the and I dump_var($selected_lparr) the array is updated and I see the values like this:
For some reason I get a 500 error.
As well I dont understand why the var_dump(inside the function below) dosent work. I seems that the function adv_lploops dosent get the variables. but i dont understand why.
This is the fuction I call:
public function adv_lploops($value){
$sql = "SELECT * FROM `lptitels` WHERE titleidNo = '$value'";
$row = $sql->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
You aren't executing the sql query, try the following:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
note: you will need the $db object which is a connection to your database
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 ;)
I am trying to populate a select list with data from my db (php & mysql). I am working with AngularJs and Angular Material. So for i am not able to show the data from the db in the list
db situation:
tblProjectType -> name of table
2 rows:
id_ProjectType
project_type
Any help or pointers would be great.
This is my html code:
<form ng-controller="AppCtrl">
<div layout="row">
<md-select-label>Project type</md-select-label>
<md-select ng-model="project_type" name="project_type" placeholder="Choose a project type" id="containerProjectType">
<md-option ng-repeat="projecttype in projecttypes" value="{{projecttype.id_ProjectType}}">{{projecttype.project_type}}</md-option>
</md-select>
</div>
</form>
The code of my app.js is:
var app = angular.module("DragDrop", ['ngMaterial']);
app.controller('AppCtrl', function($scope, $mdDialog, $http) {
$scope.projectTypeInfo = [];
var getProjectTypeFunction = function(succesFn, errorFn)
{
$http.get('db.php?action=get_ProjectType_info')// call to the server
.succesFn(function(data){
succesFn(data); //call the function passed into getProjectTypeFunction with the data from the server
console.log('Retrieved data from server');
})
.error(errorFn || function() {
console.log("Error in retrieving data from server");
})
}
this.reloadProjectTypeList = function()
{
getProjectTypeFunction(
/* success function */
function(data) {
//debugger;
$scope.projectTypeInfo = data;
//digest recycle
//if (!$scope.$$phase) { $scope.$apply(); }
},
/* error function */
function()
{
alert("Server load failed");
})
};
My php code is:
<?php
include('config.php');
//echo ('test' . $_GET['action']);
switch($_GET['action']) {
case 'get_ProjectType_info' :
get_ProjectType_info();
break;
}
/** Function to data from tblProjectType **/
function get_ProjectType_info(){
$qry = mysql_query('SELECT * from tblProjectType');
echo("test");
//echo(qry);
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id_ProjectType" => $rows['id_ProjectType'],
"project_type" => $rows['project_type']
);
}
print_r(json_encode($data));
return json_encode($data);
}
?>
So for starters lets clean up your JS. We can reduce what you have to this:
var app = angular.module("DragDrop", ['ngMaterial']);
app.controller('AppCtrl', function($scope, $mdDialog, $http)
{
$scope.projectTypeInfo = [];
$scope.getProjectTypeFunction = function()
{
$http.get('db.php?action=get_ProjectType_info')
.success(function(data, status, headers, config)
{
$scope.projectTypeInfo = data;
console.log('Retrieved data from server');
console.log(data);
})
.error(function(data, status, headers, config)
{
console.log("Error in retrieving data from server");
console.log(data,status);
});
};
$scope.getProjectTypeFunction(); //-- call the function that invokes $http.get()
};
In PHP your function needs to echo the data via echo json_encode($data);, not return it (as stated by #Avalanche).
Now, your console should output something, but you need to remove console.log("test"); from your PHP as that will surely cause an error.
edit
Currently your repeat states:
<md-option ng-repeat="projecttype in projecttypes" value="{{projecttype.id_ProjectType}}">{{projecttype.project_type}}</md-option>
We have stored your data in $scope.projectTypeInfo therefore it needs to be modified to:
<md-option ng-repeat="projecttype in projectTypeInfo" ng-value="projecttype.id_ProjectType">{{projecttype.project_type}}</md-option>
I'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();
$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
function(resultmsg) {
$('#edit_field').val('');
$('#savebtn').attr('disabled',true);
refresh_studynames();
});
And this is the function refresh_studynames:
function refresh_studynames()
{
$.ajax({
url: 'getStudyNames.php',
data: "",
dataType: 'json',
error: function() {
alert('Refresh of study names failed.');
},
success: function(data)
{
$data.each(data, function(val, sname) {
$('#studylist').append( $('<option></option>').val(val).html(sname) )
});
}
});
}
Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
FROM ibg_studies ST
ORDER BY studyname";
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$array = pg_fetch_all($fetchresult);
echo json_encode($array);
} else {
$msg = "Failure! SQL="+$sql;
echo $msg;
}
Any help much appreciated....
The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );
looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
$studylist.append( $('<option/>').html(record.sname) );
});
oI am having problem fetching comments from MySQL database using jQuery.
I am trying this way, but its not working.
PHP (comments.php)
<?php
if (isset($_POST['value1'])) {
$id = ($_POST['value1']);
}else{
$id = '';
}
if (isset($_POST['value2'])) {
$database = ($_POST['value2']);
}else{
$database = '';
}
if (isset($_POST['value3'])) {
$tablename = ($_POST['value3']);
}else{
$tablename='';
}
require_once('rt-connect.php');
$find_data = "SELECT * FROM $tablename";
$query = mysqli_query($connection, $find_data);
?>
<?php while($row = mysqli_fetch_assoc($query)):?>
<div class="comment-container">
<div class="user-info"><?php echo $row['user_name']; ?></div>
<div class="comment"><p><?php echo $row['comment']; ?></p></div>
</div>
<?php endwhile;?>
Jquery(comments.html)
var id=2;
var database='comments_db';
var tablename='comments';
$.post('comments.php', {value1:id, value2:database, value3:tablename}, function(data)
{
$('#comments').load('comments.php .comment-container');
});
Html(div on comments to load on comments.html)
<div id="comments"></div><!--end of comments-->
Please see and suggest any possible way to do it.
Thanks
Try This one it will help you.
This is jquery Ajax post method requesst if you want to show your data is loaded or not just remove the commet.
$.ajax({
type: "POST",
url: url,
data: { value1:id, value2:database, value3:tablename}
}).done(function( data ) {
//alert(data); return false;
$("#comments").html(html);
});
You have $.load() inside success function of $.post(), try this..
$.post('comments.php', {value1:id, value2:database, value3:tablename}, function(data)
{
$('#comments').html(data);
});
In your javascript, you are posting data to a url, accepting response and if the response is successful, you are sending another request to the PHP script, this time without parameters. Your comments box is displaying the result of your second request.
You do not require :
$('#comments').load('comments.php .comment-container');
in your javascript, since you have already received a response. Instead, use :
$('#comments').html(data);
which will display the response data in the comments div.
You could try this one,
var id = 2;
var database = 'comments_db';
var tablename = 'comments';
$.ajax({
type :"POST",
data :"id="+id+"&database="+database+"&tablename="+tablename,
url : comments.php,
success: function(msg){
$("#comments").html(msg);
}
});