Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've been stuck 2 days on the TutsPlus - jQuery in 30 Days exercises... lesson 26
Why does my ajax success function refuse to log the results to the console?
What happens instead is index.php simply echoes the text onto the webpage itself.
It's like some syntax problem is preventing the success callback from even running at all.
The rest of the code works (it does not rely on this particular callback), but I don't want to proceed until I find out what's wrong.
var Actors = {
init: function( config ) {
this.config = config;
this.bindEvents();
},
bindEvents: function() {
this.config.letterSelection.on('change', this.fetchActors);
},
fetchActors: function() {
var self = Actors;
$.ajax({
url: 'index.php',
type: 'POST',
data: self.config.form.serialize(),
dataType: 'json',
success: function(results) {
console.log(results);
}
});
}
};
Actors.init({
letterSelection: $('#q'),
form: $('#actor-selection')
})
and here's my index.php page...
<?php
require 'functions.php';
if ( isset($_POST['q']) ) {
connect();
$actors = get_actors_by_last_name( $_POST['q'] );
echo 'index returning your call with ' . $_POST['q'];
// echo json_encode($actors); return;
}
include 'views/index.tmpl.php';
?>
When specifying a dataType, such as 'json', the entire response needs to conform to that type.
By including additional output, such as:
echo 'index returning your call with ' . $_POST['q'];
The response won't be valid JSON and jQuery will error when attempting to parse it.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
How can I upload data to database with AJAX, JSON and PHP?
Here is the code.
AJAX
function saveToTheDB(ratedIndex) {
$.ajax({
url: 'fetch.php',
method: 'POST',
cache: 'false',
dataType: 'json',
data: {
ratedIndex: ratedIndex
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
}
PHP
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
require_once 'includes\dbh.inc.php';
$rate = $_POST['ratedIndex'];
if(isset($_GET['userid'])){
if($db->query(" INSERT INTO `recipes_ratings` (`recipe_rating_id`, `recipe_id`, `user_id`, `rating`)
VALUES (null, 3 , 8, '".$rate."')
"))
}
echo json_encode($rate);
}
What have I done wrong?
Can some one help me to solve this problem? Thank you very much!
EDIT
ERROR
I get back a full object
As the response points you have syntax error, here I refactored your code in order to work.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once 'includes\dbh.inc.php';
$rate = $_POST['ratedIndex'];
if (isset($_GET['userid'])) {
if($db->query("INSERT INTO `recipes_ratings` (`recipe_rating_id`, `recipe_id`, `user_id`, `rating`) VALUES (null, 3 , 8, '".$rate."')")) {
// implementation if query is successful
}
}
echo json_encode($rate);
}
JFYI: Avoid directly placing the input variables into the query, you should use Prepared Statements.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I've tried to look up different ways to get this json to output correctly but im not sure if im accessing the right variable in php/or the success function value.pTitle as well as how to I get the access to the other value out such as artTitle im failing somewhere not sure where or why.UPDATE fixed the php file added and an array $data[].
this is my php code.
$sqlPAQuery = "SELECT pTitle, GROUP_CONCAT(artTitle) AS
artTitle
FROM p
JOIN art ON art.pId = p.pId
GROUP BY pTitle";
if ($result=mysqli_query($conn,$sqlPAQuery))
{
$data = [];
while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
This is the outcome from the php encode of row:
[{"pTitle":"ent","artTitle":"11,12"},{"pTitle":"pro","artTitle":"10"},{"pTitle":"sports","artTitle":"1,13"}]
This is the html code:
<h3>Output: </h3>
<div id="output"></div>
<script id="source" language="javascript" type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: 'Data.php',
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function(index, value) {
var pageTitle = value.pTitle; //get name
$('#output').append("<b>pageTitle: </b>"+pageTitle+"<br/>");
}
});
});
Output should be:
pageTitle: ent
pageTitle: pro
pageTitle: sport
FIXED THE PHP FILE WORKS
If you want to proces the json like that this is what you need to do:
if ($result=mysqli_query($conn,$sqlPAQuery)) {
$data = [];
while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a small ajax call:
$.ajax({
type:'POST',
dataType: 'json',
url: 'inc/getfunctions.php?q='+l_id+'&func=load_po',
success:function(data){
//alert ('hi');
if (data.po_num) {
$('#po_num_s').append($('<option>').text('Select a PO').attr('value', 0));
var po_num = data.po_num;
var $subType = $("#po_num_s");
$.each(data, function () {
$subType.append($('<option></option>').attr("value", data.l_id).text(data.po_num));
});
}
}
});
it is apending 2 rows :
<'option value="11">112212<'/option>
<'option value="11">112212<'/option>
is the output
Thanks in advance
The $.each function will take an array or an object and iterate over its items, while providing the item key and value as parameters to the callback. Like so:
$.each(["aaaa", "bb", "ccc"], function(key, value){
console.log(value.length);
});
// Will output:
// 4
// 2
// 3
But you aren't using the each-loop for something useful, as you don't receive any item in the callback function. The only reason you're getting as few as 2 lines is that your data object only has 2 keys in it. Try adding another property to data at the same place as your commented alert, like so:
......
success:function(data){
//alert ('hi');
data.foo = "bar"
if (data.po_num) {
......
and watch the each-loop go three rounds.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to access my data being sent through ajax and I am returning my echo statements, but not what I am passing, what am I doing wrong?
$.ajax({
url: 'http://www.example.php',
data : { 'foo' : 'bar', 'bar2' : 'foo2' },
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('success data '+data);
}
});
$data = $_POST['foo'];
$data2 = $_POST['bar2'];
echo('almost');
echo($data);
echo($data2);
echo('almost');
console reads success data almostalmost
Your ajax request is incorrect, you're telling jQuery.ajax not to process your data and send it as is, which wont work
$.ajax({
url: 'http://www.example.php',
data : { 'foo' : 'bar', 'bar2' : 'foo2' },
type: 'POST',
success: function(data){
console.log('success data '+data);
}
});
Your sever side script is expecting application/x-www-form-urlencoded content type this is what jQuery.ajax does by default, but not if you tell it not to process the data or set a content type.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a database which has about 5000 books. When user comes on the page, I don't want to load the books by using simple select * from BOOkTABLE, my approach is to go as the user needs it, so I want that as the user scrolls down I could fetch data from the Database. May be in chunks of 15-20 books, is that a good approach? Any alternative?
Secondly I have alphabets on top of div so if a user clicks on "Z" we could fetch the books starting with Z and show him in the DIV.
Yes you can do this by using Ajax on scroll down.Something like that:
$(window).scroll(function () {
if ($(window).height() + $(window).scrollTop() == $(document).height()) {
$.ajax({
type: "POST",
url: 'abc.php',
async:false,
data:"pagedata="+pageData ,
cache: false,
success: function(data){
}
});
}
});
In abc.php you can set the query according to your requirement and render the html(response) to be shown when scrolled down.
For the first question, using ScrollTop() you can load iterations of data from your PHP after an interval of pixels has been scrolled.
You will need a PHP file, and JavaScript.
This is written freehand with no testing so I can't guarantee these will work, but try something along these lines:
JavaScript
jQuery(document).ready(function($){
// Set the number of pixels from the top you want the event to fire
// Select the number of books you would like to load each time
// i = number of loads you've called
var reloadAfter = 500;
var numberBooks = 20;
var i = 1;
$(window).scroll(function() {
if ( $(this).scrollTop() >= reloadAfter )
{
$.get("getbooks.php", {number:numberBooks , counter:i} )
.done(function(data){
$('#books').append("Title:", data.title)
.append("Author:", data.author);
});
reloadAfter = reloadAfter + reloadAfter;
i++;
}
});
PHP
$numberBooks = $_GET['number'];
$i = $_GET['counter'];
$upper = ( $numberBooks * $i );
$lower = ( $upper - $numberBooks );
$get_books = mysql_query('SELECT * FROM BOOkTABLE WHERE id > $lower AND id < $upper');
echo json_encode($get_books);