I am using Wordpress and I have a page where I have a drop down that when the links are clicked it will make an Ajax call and pass the data variable to PHP, at least that is what I'm attempting to do lol.
When clicking on the link I check my browser and in the Network tab for the page I receive a variable for the data object in the html and the ajax post's to the php page but for some reason I can't get a value.
My HTML
<div class="category-submenu">
<ul>
<li>Corporate</li>
<li>Office1</li>
<li>Office2</li>
<li>Office3</li>
</ul>
</div>
My jQuery
$('.category-submenu a').click(function(){
$.ajax({
type: "POST",
url: "/load-team.php",
dataType: 'json',
data: {office: $(this).data('office')},
success: function(data) {
$.each( data, function(i, item) {
alert(data[i].start);
});
}
});
});
My PHP
<?php
$office = $_GET['office'];
$link = mysql_pconnect("localhost", "root", "root") or die("Could not connect");
mysql_select_db("somedb") or die("Could not select database");
$arr = array();
$query = mysql_query("SELECT first_name, last_name FROM ic_team_members WHERE office ='" . $office . "'");
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
echo '{"members":'.json_encode($arr).'}';
?>
I'm sure there is some code missing or my syntax might be incorrect in some parts but I can't seem to find where, if any place.
Again I want to grab the data object from HTML element, pass it through Ajax into PHP and return the result as json object, which I can do but for some reason I think the error is in my PHP.
Any help would be appreciated.
You are passing it by POST, and therefore you need to receive it with POST:
$office = $_POST['office'];
Otherwise, use GET to send the ajax request:
$.ajax({
type: "GET",
...
});
Related
I am building two interdependent drop-down lists, where the options of the second list (the 'sensor_list') depend on what option was chosen in the first list (the 'node_list'). To do that I attach a listener to the 'node_list' and when an option is selected I make an ajax request in order to load the data for the 'sensor_list'. All data, for both lists, is loaded from the same database.
In that ajax request I access the 'sensors' table on the database and I get the 'Sensor_ID' and the 'Sensor_name' of the sensors I need. What I want, now, is to pass this data back to the 'success' function of the request. Is this done automatically? Do I need to pass any arguments to the function?
Also, I need the returned data to be in JSON format, for later use. How is this possible?
Here is the PHP code:
<?php
$con = mysql_connect("localhost", "root", "") or die('connection not made');
$db = mysql_select_db('name_of_db', $con) or die('db not selected');
$query = "SELECT SensorID,Variable FROM sensors WHERE SensorID IN (SELECT SensorID FROM nodesensors WHERE NodeID=node_selected)";
$result = mysql_query($query, $con) or die('query not made');
$options = json_encode($result);
?>
The 'node_selected' is the variable I pass with the request and it is the id of the node I selected in the first list.
The JavaScript is:
if (node_selected!=0 & node_selected!=null){
$.ajax({
type: "POST",
url: "php/fetch_sensors.php",
data: node_selected,
success: function( options ){
...//here I need the options to be in json format
}
});
}
'Options' is the data I want to be returned from the request and they are going to be the options for the 'sensor_list'.
Thanks a lot in advance!!
You can use the mysql_fetch_assoc function for that
Try changing the PHP code to the following:
<?php
$con = mysql_connect("localhost", "root", "") or die('connection not made');
$db = mysql_select_db('name_of_db', $con) or die('db not selected');
$query = "SELECT SensorID,Variable FROM sensors WHERE SensorID IN (SELECT SensorID FROM nodesensors WHERE NodeID=node_selected)";
$result = mysql_query($query, $con) or die('query not made');
$returnArray = array();
while($row = mysql_fetch_assoc($result)) {
$returnArray[] = $row;
}
$options = json_encode($returnArray);
?>
Change
$options = json_encode($result);
To
echo json_encode($result);
And add dataType:'json' to your ajax call:
$.ajax({
type: "POST",
url: "php/fetch_sensors.php",
data: node_selected,
dataType: 'json',
success: function( options ){
...//here I need the options to be in json format
}
});
First off, stop using ext/mysql if you can.
You are not actually fetching the results from the query.
while ($row = mysql_fetch_assoc($results)) {
$rows[] = $row;
}
Then you actually have to emit the array to the response.
echo json_encode($rows);
jQuery is pretty smart about detecting JSON and should parse it automatically so you can use options as an object. If it doesn't work automatically, you can do any of the following:
//php
header("Content-type: application/json")
//javascript
data: node_selected,
dataType: "json",
// *or*
success: function (options) {
options = JSON.parse(options);
}
Finally since this request is an idempotent retrieval you should really be using GET instead of POST as the method.
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 want to populate a jQWidgets listbox control on my webpage(when page finished loading and rendering) with values from an actual MySQL database table.
PARTIAL SOLUTION: Here
NEW PROBLEM:
I've updated the source code and if I hardcode the SQL string - the listbox gets populated. But I want to make a small JS function - popList(field, table) - which can be called when you want to generate a jQWidgets listbox with values from a MySQL database on a page.
Problem is - for some reason the $field and $table are empty when the PHP script is being executed, and I receive You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM' at line 1 error. What gives?
The page:
<div id="ListBox">
<script type="text/javascript">
popList("name", "categories");
</script>
</div>
popList(field, value):
function popList(field, table) {
$.ajax({
type: "GET",
url: 'getListOfValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: 'json',
success: function(response) {
var source = $.parseJSON(response);
$("#ListBox").jqxListBox({ source: source, checkboxes: true, width: '400px', height: '150px', theme: 'summer'});
},
error: function() {
alert('sources unavailable');
}
});
}
getListOfValues.php:
<?php
require "dbinfo.php";
// Opens a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$field = $_GET["field"];
$table = $_GET["table"];
$field = mysql_real_escape_string($field);
$table = mysql_real_escape_string($table);
$qryString = "SELECT " . $field . " FROM " . $table;
$qryResult = mysql_query($qryString) or die(mysql_error());
$source = array();
while ($row = mysql_fetch_array($qryResult)){
array_push($source, $row[$field]);
}
mysql_close($connection);
echo json_encode($source);
?>
Ok, you have a few things here. First off you need a callback function when you do the ajaxRequest. (I'll explain why in a bit.) So add the following line BEFORE your ajaxReqest.send(null);
ajaxRequest.onreadystatechange = processAjaxResponse;
Then you need to add the processAjaxResponse function which will be called.
function processAjaxResponse() {
if (ajaxRequest.readySTate == 4) {
var response = ajaxRequest.responseText;
//do something with the response
//if you want to decode the JSON returned from PHP use this line
var arr = eval(response);
}
}
Ok, now the problem on your PHP side is you are using the return method. Instead you want PHP to print or echo output. Think about it this way. Each ajax call you do is like an invisible browser. Your PHP script needs to print something to the screen for the invisible browser to grab and work with.
In this specific case you are trying to pass an array from PHP back to JS so json_encode is your friend. Change your return line to the following:
print json_encode($listOfReturnedValues);
Let me know if you have any questions or need any help beyond this point. As an aside, I would really recommend using something like jQuery to do the ajax call and parse the response. Not only will it make sure the ajax call is compliant in every browser, it can automatically parse the JSON response into an array/object/whatever for you. Here's what your popList function would look like in jQuery (NOTE: you wouldn't need the processAjaxResponse function above)
function popList(field,table) {
$.ajax({
type: "GET",
url: 'getListofValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: "json",
success: function(response) {
//the response variable here would have your array automatically decoded
}
});
}
It's just a lot cleaner and easier to maintain. I had to go back to some old code to remember how I did it before ;)
Good luck!
i have a javascript code that requests a php page to provide it with list of names that are currently online and update a Table, but i have a problem sending it back in form of an array, someone told me that this is usually done using XML, but i dont know how to start.
javascript Post method:-
$.post( "updateTable.php", POSTdata,
function( data ) {
$("#mytable").last().append('<tr><td>'+data+'</td></tr>');
}
);
the php file:-
include("connect.php");
$query1 = "SELECT * FROM formtable";
$result_id = mysql_query($query1, $global_dbh)
or die ("display_db_query:" . mysql_error());
while ($table_array = mysql_fetch_object ($result_id))
{
$rows[] = $table_array;
}
foreach ($rows as $temp ) {
if ($temp->isOnline==1)
$newRow[] = $temp->name;
}
echo "$newRow";
mysql_close($global_dbh);
Please excuse any syntax or semantics in my code, i am a beginner.
How can i populate my table using ajax callback function, and in what form the data will arrive there, and how can i use xml to help me.
Many thanks in advance.
A quick example of json:
var table = $("#mytable").last();
$.ajax({
type: 'post',
url: "updateTable.php",
dataType: 'json',
data: POSTdata,
success: function(data){
jQuery.each(data, function(i, row){
//console.log(row);
table.append('<tr><td>'+row.name+'</td></tr>');
});
}
});
and in php file, instead of :
echo "$newRow";
replace with:
echo json_encode($newRow);
That's it!
I'm trying to populate a form with jquery's populate plugin, but using $.ajax
The idea is to retrieve data from my database according to the id in the links (ex of link: get_result_edit.php?id=34), reformulate it to json, return it to my page and fill up the form up with the populate plugin. But somehow i cannot get it to work. Any ideas:
here's the code:
$('a').click(function(){
$('#updatediv').hide('slow');
$.ajax({
type: "GET",
url: "get_result_edit.php",
success: function(data)
{
var $response=$(data);
$('#form1').populate($response);
}
});
$('#updatediv').fadeIn('slow');
return false;
whilst the php file states as follow:
<?php
$conn = new mysqli('localhost', 'XXXX', 'XXXXX', 'XXXXX');
#$query = 'Select * FROM news WHERE id ="'.$_GET['id'].'"';
$stmt = $conn->query($query) or die ($mysql->error());
if ($stmt)
{
$results = $stmt->fetch_object(); // get database data
$json = json_encode($results); // convert to JSON format
echo $json;
}
?>
Now first thing is that the mysql returns a null in this way: is there something wrong with he declaration of the sql statement in the $_GET part? Second is that even if i put a specific record to bring up, populate doesn't populate.
Update:
I changed the populate library with the one called "PHP jQuery helper functions" and the difference is that finally it says something. finally i get an error saying NO SUCH ELEMENT AS
i wen into the library to have a look and up comes the following function
function populateFormElement(form, name, value)
{
// check that the named element exists in the form
var name = name; // handle non-php naming
var element = form[name];
if(element == undefined)
{
debug('No such element as ' + name);
return false;
}
// debug options
if(options.debug)
{
_populate.elements.push(element);
}
}
Now looking at it one can see that it should print out also the name, but its not printing it out. so i'm guessing that retrieving the name form the json is not working correctly.
Link is at http://www.ocdmonline.org/michael/edit_news.php with username: Testing and pass:test123
Any ideas?
First you must set the dataType option for the .ajax call to json:
$.ajax({dataType: 'json', ...
and then in your success function the "data" parameter will already be a object so you just use it, no need to do anything with it (I don't know why you are converting it into a jQuery object in your code).
edit:
$( 'a' ).click ( function () {
$( '#updatediv' ).hide ( 'slow' );
$.ajax ( {
type: "GET",
url: "get_result_edit.php",
success: function ( data ) {
$( '#form1' ).populate ( data );
},
dataType: 'json'
} );
$( '#updatediv' ).fadeIn ( 'slow' );
return false;
}
also consider using $.getJSON instead of $.ajax so you don't have to bother with the dataType
Try imPagePopulate (another jquery plugin). It may be easier to use:
http://grasshopperpebbles.com/ajax/jquery-plugin-impagepopulate/