This is a jquery/ajax problem. The jquery/ajax is responding to keyup event with the alert(loc) showing the result of the value inputted into the number textbox.
The essense of the program is to get data from the database which is in an array form after encoding with json via php and display the result inside the textbox.
However, reaching the .ajax function, it does not display anything inside the success section. At the end, there is no response or any error. Used JSONLINT to see if there is any error, it gave a code i dont understand.
Afte using mozilla firebug to step through jquery, it still did not show any message.
This are my html,php,jquery codes for verification.
JS:
$(document).ready(function() {
$('#number').keyup(function() { //keyup event responds
var loc = $('#number').val();
alert(loc); //display result from the number textbox
$.ajax({ //skips ajax function
dataType: "json"
url: "/php/barry.php",
data: ({loc : loc}),
async: false,
type: "GET",
contentType: "application/json; charset=utf-8
success: function(data) {
$.each(data.result, function()
{
$("#number").append(this['number']);// its suppose to display
$("#name").append(this['name']);
});
}
});
});
});
PHP:
<?php
include_once('/db.php');
if(isset($_GET['loc'])){
$foo = $_GET['loc'];
$sql = "SELECT * FROM freak where number='$foo'";
$res = mysql_query($sql);
$result = array();
while( $row = mysql_fetch_array($res) )
array_push($result, array('number' => $row[0],
'name'=> $row[1];
//print_r($result);
echo json_encode(array("result" => $result));
}
?>
Related
I want to send a javascript variable to php file which shows the comments on a webpage.
I was able to send this js variable to some other php file, but I can't do it with this comment-list.php file. I guess there is some problem with JSON.
function listComment() {
$.ajax({
url: "Komentarji/comment-list.php",
data : {page_num: page_num},
type : 'post',
success : function(response) {
}
});
$.post("Komentarji/comment-list.php", function(data) {
var data = JSON.parse(data);
.
.
.
The function is called here:
$(document).ready(function() {
listComment();
});
Inside comment-list.php I try to get the variable that was sent with ajax. However it doesn't work and comment's aren't displayed on page. If I delete this line, the comments work again (but of course, I don't get the sent variable).
$num = $_POST['page_num'];
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
Here is the javascript variable and included php file.
<script>
var page_num = 1;
</script>
<?php
include($_SERVER["DOCUMENT_ROOT"]."/index.php");
?>
I get this error in console: Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()
As said eariler if I remove the line where I get the variable with post, this error disappears.
You shouldn't use $.ajax and $.post to do the same thing, pick one, I'd say remove the $.post one and dont forget to put an exit; statement after you echo the response to avoid PHP to process further code if existing, also worth mentionning but not necessary, you can put the dataType to json so dataType: 'json' in the $.ajax call, dataType is used to tell jQuery what to expect as a response type from the server, as you are echoing the response by encoding it in JSON, you won't need to parse the response on your JS side if you speficied the dataType beforehand.
$.ajax({
url: "Komentarji/comment-list.php",
data : {page_num: page_num},
type : 'post',
dataType: 'json',
success : function(response) {
console.log(response); //will show the result of echo json_encode($record_set); from your PHP
}
});
$num = $_POST['page_num'];
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
exit; //exit statement here
Following discussion with OP who wanted to use the $.post method, this is how it is done, pass the data as an object to the second attribute (more infos here):
$.post("Komentarji/comment-list.php", {page_num: page_num});
Just make your format JSON in your JS script
$.ajax({
url : 'Komentarji/comment-list.php',
type: "POST",
data: page_num:page_num,
dataType: "JSON",
success: function(data)
{
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
I have been searching for hours and haven't found any solutions for my problem.
This is my jQuery/Ajax code:
$(document).ready(function() {
$(".submit_btn").click(function () {
var name = $("input#name").val();
var dataString = 'query='+$("#query").val()+'&facebook='+facebook+'&twitter='+twitter;
$.ajax({
type: "POST",
url: "selectDataSets.php",
dataType: "json",
data: dataString,
success: function(data) {
alert ("hello");
}
});
return false;
});
});
Now my selectDataSets.php code:
<?
include_once 'config.php';
if ((isset($_POST['facebook'])||isset($_POST['twitter']))&&isset($_POST['query'])) {
$elements=0;
$dataSet=array();
$tt=array();
$fb=array();
mysql_connect($config['database_url'], $config['database_user'], $config['database_password']) or die(mysql_error());
$queries = explode(";", $_POST['query']);
foreach ($queries as $query){
if(isset($_POST['facebook']) && $_POST['facebook'] == true){
mysql_select_db("facebook") or die(mysql_error());
$mysql_query = "SELECT * FROM page WHERE lower(name) LIKE '%".mysql_real_escape_string(strtolower($query))."%'";
// Perform Query
$result = mysql_query($mysql_query);
while ($row = mysql_fetch_assoc($result)) {
$set = array(
"name" => str_replace("-","",$row['name']),
"likes" => $row['likes'],
"about" => $row['talkAbout'],
"source" => "Facebook (Page)",
"id" => $row["id"],
"query" => $query
);
$fb[$elements]=$set;
$elements++;
}
mysql_free_result($result);
}
}
mysql_close();
echo json_encode($fb);
}
With dataType: "json", the alert("Hello") does not work, as well as nothing that I add inside the success callback. Although when I remove dataType: "json", the alert works, but the variable data is not recognized as JSON (as I keep getting undefined when I try to do data[0].name), even though I have checked and data is on the format [ { "name: ... } ], which I guess is correct JSON. I don't know what else to do, as I have a similar (almost the same) code on another php file that works perfectly with the dataType: "json".
Thanks in advance!
Can you see the actual output of the PHP script/AJAX call using Chrome's network window?
Make sure there are no MySQL errors and stuff. The reason you get no error when you don't put dataType: "json" is because the JSON parser is not attempting to read your malformed JSON. For some reason, your example JSON is good but whatever AJAX is receiving is not good. From the network window, select your AJAX call and look at the response tab. This will show you the real output.
I have to admit my AJAX skills suck. I have an array of news items. With about 25 rows. Instead of displaying all 25 rows I figured I would just slice the array into parts of 5 and allow the user to 'load more' using array_slice and some ajax. The php side is easy for me, but I'm having some trouble with the ajax. I put it together the best I could but it doesn't quite work yet.
The AJAX:
<script type="text/javascript">
$(document).ready(function() {
$('#load-more').click(function () {
var size = 5;
var data = 'size=' + content.val() + '&submit=yes';
$('.loading-circle').show();
//start the ajax
$.ajax({
url: "<?php echo $url; ?>/process/load.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
if (html==1) {
}
else {
alert("Sorry, an unnexpected error has occurred.");
}
}
});
return false;
});
});
</script>
load.php
<?php
session_start();
if ($_GET["submit"] == 'yes')
{
$_SESSION["load_size"] = $_GET["size"];
}
?>
index.php
$sorted = Feed::sortFeed($feed, $day, 0, $_SESSION["load_size"]);
foreach ($sorted as $article)
require $baseDir . 'feed.php';
So I'm trying to get the session variable to determine the size. There's a couple problems with this approach though that I don't know how to get around. There may be multiple news feeds per page that would all be expanded even if the user just wanted to expand one. On top of that the feeds wouldn't resize to their default of 5 on a page refresh. I'm thinking I have to generate the array with the load.php page but I don't know how to pass it back through ajax. So how would I best go about sorting an array using ajax. Is there anything I can read up on, or some simple changes I can make?
Thanks
You can pass a PHP array back through ajax by using json_encode function on your PHP Array. Just echo out the the returned value from json_encode in your load.php
<?php
session_start();
if ($_GET["submit"] == 'yes')
{
$_SESSION["load_size"] = $_GET["size"];
}
//load some php array here
$array = array('success' => true, 'items' => array('item1','item2'));
echo json_encode($array);
?>
You can then tell jQuery that the return type is is JSON by specifying the dataType option like this:
$.ajax({
url: "<?php echo $url; ?>/process/load.php",
type: "GET",
data: data,
cache: false,
dataType: 'json',
success: function (response) {
// response var is an object, same structure as the PHP array you encoded
if(response.success){
// handle success
} else {
alert('something went wrong');
}
}
});
I've been trying to find an answer for this for hours but really struggling.
I have a simple jquery Ajax function which sends data to a PHP script. The data is then used to conduct a MySQL query and the results are included as an array. I'm sending the array back using json_encode but can't work out how to display the array at the other end. I've posted the code below. The console.log is displaying Object {modules: Array[0]}
. There should be 3 entries in the array.
The PHP
<?php
include_once('../../dbconnect.php');
$name = $_POST['uploadname'];
$query = "SELECT * FROM marking_assignments WHERE name = '$name'";
$details = $conn->query($query);
$modules = array();
while ($row = $details->fetch_assoc()){
$modules[] = $row['unit'];
}
$dataarray = array("modules"=>$modules);
echo json_encode($dataarray);
?>
The jQuery
var uploadname;
$("#uploadname").blur(function(){
uploadname = $(this).val();
$.ajax({
url: "uploadnames.php",
type: "POST",
data: {uploadname: uploadname},
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
you should use:
var parsedData = jQuery.parseJSON(data);
and then:
console.log(parsedData)
I am trying to make a search box in my web application, and I used ajax post to make a request to my server. My question is:
Is it possible to send looped array values from PHP to my JavaScript?
I want to get all of the results from my server.
CLIENT SIDE: Ajax POST request
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
type: "POST",
url: "searchPlaces.php",
data: { searchInput: form.searchTxtId.value },
success: function (result)
{
// Get the search result
}
});
});
</script>
SERVER SIDE (after retrieving the post from ajax, and making queries):
while ($result = mysql_fetch_assoc ($query))
{
$resultName = $result['name'];
$resultAddress = $result['address'];
}
$results = array();
while ($result = mysql_fetch_assoc ($query)) {
$results[] = $result;
}
echo json_encode(array('results' => $results));
In your success callback you can then iterate over result.results which contains an object with the column names from your query as attributes.
success: function(result) {
$.each(results, function(i, row) {
console.log(row.name, row.address);
})
}
It is also advisable to use dataType: 'json' in your $.ajax({...}); arguments to avoid unnecessary guessing of the response type.
In case you have more columns in the SQL resultset than you want to forward to the client, you could add a custom array in the loop:
$results[] = array('name' => $row['name'], 'address' => $row['address']);
yes you can you can return a json string :
$.ajax({
type: "POST",
dataType: 'json', // return type is json ;
url: "searchPlaces.php",
data: { searchInput: form.searchTxtId.value },
success: function (result)
{
$.each($result,function(index, value){
// use params
}
}
});
and on your php side you use json_encode()