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.
Related
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.
In my index.php file, I have the following code snippets. Can someone provide an explanation how this process occur ? I found this somewhere and it somehow matches what I intend to do on a work.
case 'option1':
$final['a']['b'] = queryDatabase($conn, $id, 'customer');
echo json_encode($final);
I have a function queryDatabase that contains an SQL query.
function queryDatabase($conn, $id, $searchType) {
$query = "SELECT .....
Then it sets the variable $rows as follows:
$rows = query($conn, $query);
The variable $query contains the SQL query.
Then I have another function as follows:
function query($conn, $query) {
$rows = [];
$result = mysqli_query($conn, $query);
if($result) {
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$rows[] = $row;
}
}
return $rows;
}
Now in my global.js file, I have created and ajax request as follows:
$.ajax({
type: "POST",
url: "index.php",
dataType: "json",
data: {
action: 'option1',
id: id,
},
success:
function(data) {
Also, in the function(data), does the data contains all the result retrieved from the database? How can I access individual data from the database here?
Please help. Thanks.
First, the data should include the result, however, you need to echo back the data to be accessible,
Moreover, you need to encode the result in json, so your last line of code should be something like
echo json_encode($rows);
After that you can edit your javascript in the success part to log the returned result, something like:
console.log(data);
This will show you exactly how to access your data.
I'm creating my project using OOP. I need to pass all the values inserted in the database in the form of array. And it's a multidimensional array. SO when I pass now via ajax as a 'text' datatype it displays array in console.log(). But I'm unsure if this is the correct way and how to display the value in a table form in jquery.
Below are the functions where the values returned to the object in another page.
public function selectType()
{
$sql="SELECT * FROM car_type";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carType=array();
while($row = $stmt->fetch())
{
array_push($carType,$row['car_type']);
}
return $carType;
}
public function selectMaker()
{
$sql="SELECT * FROM car_maker";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carMaker=array();
while($row = $stmt->fetch())
{
array_push($carMaker,$row['car_maker']);
}
return $carMaker;
}
ANd this is how I'm fetching the values to be passed to another page to be displayed to the user.
$setting = new setting($car_type,$car_maker,$rental_type,$rental);
//$setting->connection;
$setting->addCarType();
$setting->addCarMaker();
$setting->addRentalBy();
$carType=$setting->selectType();
$carMaker=$setting->selectMaker();
$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo $json;
Finally ajax to fetch and display data
$("#submit").on("click",function()
{
$("#set_setting").submit(function(){
data = $(this).serialize()
$.ajax({
type: "POST",
dataType: "html",
url: "submit_setting.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//hide the form
$("#set_setting").slideUp("slow");
//show the result
for (i = 0; i < data.length; i++) {
console.log(data);//outputs array
$(".the-return").html(data);
}
}
});
return false;
});
});
You need to pass array as JSON and post it using name value pairs.
var data = {a:{'foo':'bar'},b:{'this':'that'}};
$.ajax({ url : '/',
type : 'POST',
data : {'data':JSON.stringify(data)},
success : function(){ }
});
And in backend (PHP):
$data = json_decode($_POST['data']);
print_r($data);
// Result:
// Array( "a" => Array("foo"=> "bar"), "b" => Array("that" => "this"))
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.
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);
}
}