HTML, AJAX and PHP included below. Before introducing AJAX, everything functions (form tags and PHP processing values removed from HTML below).
The drop-down (categories) is populated from a MySQL query. When the user selects an option, I want to pass the ID via ajax to a PHP script (index.php) to run a MySQL query to populate another drop-down (sub-categories).
The Chrome console log indicates that ajax is passing the ID correctly.
Firebug also shows it passing and that the URL is correct (index.php?business_category_id=ajax-passed value). If the GET variable is being passed, and my PHP script is looking for it, why is the script not responding? Why is it not receiving the value? I cannot echo it, so I know it's not being received.
The ajax script is in js/script.js, index.php (my controller) is in the root, and the page with the html (buy-a-biz.php) is in the root and included in the php script (see below).
If anyone can help, I'd appreciate it very much. I am new to using jQuery ajax.
HTML.
<select name="category" id="business-category">
<option value="all_categories">Select category</option>
<?php foreach ($categories as $category): ?>
<option value="<?php htmlout($category['id']); ?>"><?php htmlout($category['name']); ?></option>
<?php endforeach; ?>
</select>
AJAX. I experimented using $.get and $.post also.
$(document).ready(function(){
$("#business-category").change(function(){
var category_id = $(this).val();
console.log(category_id);
$.ajax({
type: 'GET',
url: 'index.php',
data: { business_category_id: category_id },
success: function(category_id){
$("#result").html(category_id + ' submitted successfully!');
}
});
});
});
PHP.
if(isset($_GET['business_category_id'])){
$category_id = htmlspecialchars($_GET['business_category_id']);
include 'includes/dbconnect.php';
try {
$sql = "SELECT * FROM sub_category
WHERE category_id = :category_id";
$s = $db->prepare($sql);
$s->bindValue(":category_id", $category_id);
$s->execute();
while($row = $s->fetch(PDO::FETCH_ASSOC)){
$sub_categories[] = array(
'id' => $row['id'],
'category_id' => $row['category_id'],
'name' => $row['name']
);
}
$sql2 = "SELECT * FROM category";
$s2 = $db->prepare($sql2);
$s2->execute();
while($row = $s2->fetch(PDO::FETCH_ASSOC)){
$categories[] = array(
'id' => $row['id'],
'name' => $row['name'],
);
}
}
catch (PDOException $e) {
$errMsg = "Error fetching data" . $e->getMessage();
include 'error.html.php';
exit();
}
include 'buy-a-biz.php';
exit();
}
You are passing a done callback to $.ajax. You should either name this callback success
$.ajax({
type: 'GET',
url: 'index.php',
data: { business_category_id: category_id },
success: function(category_id){
$("#result").html(category_id + ' submitted successfully!');
}
});
or invoke done on the promise returned by $.ajax:
$.ajax({
type: 'GET',
url: 'index.php',
data: { business_category_id: category_id },
}).done(function(category_id) {
$("#result").html(category_id + ' submitted successfully!');
});
Related
here is my php code which would return json datatype
$sql="SELECT * FROM POST";
$result = mysqli_query($conn, $sql);
$sJSON = rJSONData($sql,$result);
echo $sJSON;
function rJSONData($sql,$result){
$sJSON=array();
while ($row = mysqli_fetch_assoc($result))
{
$sRow["id"]=$row["ID"];
$sRow["fn"]=$row["posts"];
$sRow["ln"]=$row["UsrNM"];
$strJSON[] = $sRow;
}
echo json_encode($strJSON);
}
this code would return
[{"id":"1","fn":"hi there","ln":"karan7303"},
{"id":"2","fn":"Shshhsev","ln":"karan7303"},
{"id":"3","fn":"karan is awesome","ln":"karan7303"},
{"id":"4","fn":"1","ln":"karan7303"},
{"id":"5","fn":"asdasdas","ln":"karan7303"}]
But how can I access this data in html, that is, I want particular data at particular position for example i want to show 'fn' in my div and 'ln' in another div with another id
Before trying anything else I tried this
$.ajaxSetup({
url: 'exm1.php',
type: 'get',
dataType: 'json',
success: function(data){
console.log(data);
}
});
but it shows that data is undefined I don't know what I am doing wrong
What you've got should kind-of work if you swapped $.ajaxSetup (which is a global configuration method) with $.ajax. There are some significant improvements you could make though.
For example, your PHP does some odd things around the value returned by rJSONData. Here's some fixes
function rJSONData($result) {
$sJSON = array();
while ($row = mysqli_fetch_assoc($result)) {
$sJSON[] = array(
'id' => $row['ID'],
'fn' => $row['posts'],
'ln' => $row['UsrNM']
);
}
return json_encode($sJSON);
}
and when you call it
header('Content-type: application/json');
echo rJSONData($result);
exit;
Also make sure you have not output any other data via echo / print or HTML, eg <html>, etc
In your JavaScript, you can simplify your code greatly by using
$.getJSON('exm1.php', function(data) {
console.info(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR, textStatus, errorThrown);
});
Use $.ajax instead of $.ajaxSetup function.
Here is a detailed answer from another SO post how to keep running php part of index.php automatically?
<script>
$.ajax({
// name of file to call
url: 'fetch_latlon.php',
// method used to call server-side code, this could be GET or POST
type: 'GET'
// Optional - parameters to pass to server-side code
data: {
key1: 'value1',
key2: 'value2',
key3: 'value3'
},
// return type of response from server-side code
dataType: "json"
// executes when AJAX call succeeds
success: function(data) {
// fetch lat/lon
var lat = data.lat;
var lon = data.lon;
// show lat/lon in HTML
$('#lat').text(lat);
$('#lon').text(lon);
},
// executes when AJAX call fails
error: function() {
// TODO: do error handling here
console.log('An error has occurred while fetching lat/lon.');
}
});
</script>
When call php from jquery via ajax ,have any response .I changed the dataTypeand put jsoninstead html.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm'] never carries a value.
PHP:
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
and jQuery :
$(document.body).on('click', '.edit', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {
retriveForm: id
},
dataType: "json",
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
Code is all in the same page if that may be important.
Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.
Also, you're not correctly adding to $data_json in your loop. You're overwriting the variable each time instead of pushing onto it.
<?php
// code here to set up database connection
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json[] = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
exit();
}
?>
<html>
<head>
...
Then in the success function, you'll need to index the elements of response, since it's an array, not a single object.
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.
I am having troubles with my ajax call. When I try to alert the result it keeps resulting as Undefined.
Both alerts are resulting to undefined.
I am not too sure if I am coding this correctly, please help me if I am.
Q: If I am accessing it incorrectly, how exactly would I access the skill property/index.
JQUERY/JSCRIPT
$(document).ready(function(){
// Skill sort on change
$('#order_by').on('change', function() {
$.ajax({
type: "POST",
url: "sort_skill_be.php",
dataType: "json",
data: {skill:this.value}
}).done(function(result){
alert(result[0].skill);
})
});
});
PHP FILE: This method receives a statement and places an "object" array to an overall array.
function helpFetchPostInfo($stmt){
$results = $stmt->fetchAll();
$recent_posts = array();
foreach ($results as $row){
$post = array(
'username' => $row['username'],
'steam' => $row['steam'],
'skill' => $row['skill'],
'description' => $row['description'],
'date' => $row['date'],
);
array_push($recent_posts, $post);
}
return json_encode($recent_posts);
}
Thank you for the assistance it is much appreciated
function sortSkill($skill){
// If All skill is selected display posts normally
if ($skill == 'All'){
displayPosts();
exit;
}
$db = connect();
$sql = "SELECT * FROM users LEFT JOIN posts
ON users.idUsers = posts.fkuser
WHERE posts.fkuser IS NOT NULL and users.skill=:skill
ORDER BY date DESC";
$stmt = $db->prepare($sql);
$stmt->execute(array(':skill' => $skill));
if ($stmt->rowCount() == 0){
// Nothing has returned
unset($_SESSION['recent_posts']); // Reset session of posts if no posts appear.
}
else
{
$recent_posts = helpFetchPostInfo($stmt);
return $recent_posts;
}
}
Sort skill is being called in a seperate php file called sort_skill_be.php, which is called from the jquery when a selection is changed.
<?php
session_start();
include 'database.php';
$skill_sort = $_POST['skill'];
sortSkill($skill_sort);
header('Location:index.php');
?>
EDIT: added JSON datatype to jquery
Now my problem is the alert is not being called at all anymore.
Looks like you are not providing the dataType attribute in your ajax method.
dataType: "json",
Either do that or parse your result to JSON before accessing it.
I don't see any issue the way you are trying to access the object.
Building a comment system with Ajax and JQuery and I want the div the comments are in to reload after a comment is added. It posts just fine. This is what I have so far.
The function getComments queries the database and generates the html
$.ajax({
type: "POST",
url: "post_comment.php",
data: dataString,
cache: false,
success: function(html){
????????? What should go here... it is a div with id#commentBody
}
<div id="commentBody">
<ul>
<?php
$q = "SELECT * FROM comment WHERE parent_id = 0 AND idpost = $postID";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)):
getComments($row,$postID,$custID);
endwhile;
?>
</ul>
</div>
Since you're regenerating the entire div I would use replaceWith.
$('#commentBody').replaceWith(html);
When you post it, you should return the data you want from your server side script. Then you can use the .html() jQuery function to update your div.
So, like:
$('#commentBody').html(html);
You could also return just the latest comment (optionally as a JSON object) and then just use the .append() method to add it to your #commentBody.
I would create a JSON object which has a status property and a data property. When the status is -1 (or whatever) there was an error adding the comment and you could put a message in the data property. When the status is 0, it was successful and the latest comment information would be available available in the data property.
Example
PHP
//Check postback variables, add comment and retrieve
// comment information (such as ID) if necessary
if (postedsuccessfully) {
$ary = array("status" => 0,
"data" => array("id" => $commentidvar,
"user" => $commentuser,
"text" => $comment)
);
echo json_encode($ary);
} else {
$ary = array("status" => -1,
"data" => "There was a problem adding your comment.");
echo json_encode($ary);
}
JavaScript
success: function(json){
if (json.status == 0) {
$mydiv = $('<div>');//construct your comment div using json.data.id,
//json.data.user, and json.data.text
$('#commentBody').append($mydiv);
} else {
alert(json.data);
}
}