I'm trying to make a simple ajax call:
When the user selects and option, some info about that option will be
echoed into a div (this is dynamic)
Here's my code for the ajax call
ajax.js
$(document).ready(function()
{
//Add Event
//Currently Broadcasting #Zone
$('#beacon0').on('change', function ()
{
var Selected = $(this).find("option:selected");
var SelectedText = Selected.text();
var SelectedEncoded = encodeURIComponent(SelectedText);
$.ajax
({
url: 'ajax-addevent.php',
data: 'n_beacon='+ SelectedEncoded,
dataType: 'JSON',
success: function(returnClass)
{
var resultajax = jQuery.parseJSON(returnClass)
console.log(resultajax);
},
error: function(xhr, status, error)
{
var errors = JSON.parse(xhr.responseText);
console.log("failed");
console.log (errors);
}
});
});
});
SO the ajax call should give the name of the zone in the URL, so I can $_GET the parameter in my php script. This is the php I run just to test the ajax call.
ajax-addevent.php
<?php
include("classes/event.class.php");
$event = new Event();
$GetZoneName = $_GET['n_beacon'];
$ZoneName = urldecode($GetZoneName);
$arrayDetails = $event->getBeaconEvent($ZoneName);
while($row = mysqli_fetch_array($arrayDetails))
{
$EventTitle = $row["n_title"];
$EventLink = $row["n_link"];
$EventDate = $row["n_date"];
}
$arr = array( "EventTitle" => $EventTitle,
"EventLink" => $EventLink,
"EventDate" => $EventDate );
header("content-type:application/json");
$json_arr = json_encode($arr);
return $json_arr;
?>
My problem is that the ajax call fails and gives me this as result:
What's wrong why my ajax call? Can you help?
EDIT Update Code:
You're trying to get an XML response when the returned datatype is JSON - xhr.responseXML will always be undefined unless the response is valid XML.
Try using xhr.responseText instead. You can use JSON.parse(xhr.responseText) to get a javascript object out of it.
Another good technique is to use the dev tools of your current browser to inspect the network response directly (F12 in Firefox or Chrome, then open the Network tab).
Related
I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
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>
I am trying to update a webpage on the fly after inserting some data in the db and returning a json object to no avail.
Let's say I have
<div id="try1"> try(<span id="votes1">0</span>)</div>
When loeaded the page displays the current number of votes, (0) at the moment.
then I have a button
<button onclick="vote(1);">+</button>
that calls this function:
function vote(votes_id)
{
var div = 'try' +votes_id;
var url = 'vote.php?id=' +votes_id;
var destination = '#votes' +votes_id;
$.getJSON( url, function(data) {
$(destination).html (data.votes);
});
}
my vote.php returns this json or after correctly updating the db or, at least that is what I think
{"votes":"1"}
However my webpage doesn't get updated from 0 to 1,
I use $data = json_encode($data);
the result of which as var_dump is:
string '{"votes":"1"}'
and
{"votes":"1"}
as echo $data.
What am I possibly missing?
That's because you are putting he success callback in the wrong place.
Use:
function vote(votes_id)
{
var div = 'try' +votes_id;
var url = 'vote.php?id=' +votes_id;
var destination = '#votes' +votes_id;
$.getJSON( url, {}, function(data) {
$(destination).html (data.votes);
});
}
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 use this pseudo-class to make Ajax request to server:
function RequestManager(url, params, success, error){
//Save this Ajax configuration
this._ajaxCall = null;
this._url= url;
this._type = params.type;
this._success = function(){
alert("ok");
};
this._error = function(){
alert("ko");
};
}
RequestManager.prototype = {
require : function(text){
var self = this;
this._ajaxCall = $.ajax({
url: this._url,
type: this._type,
data: text,
success: function(xmlResponse){
var responseArray = [];
var response = _extractElements(xmlResponse, arrayResponse);
self._success(response);
},
error: self._error,
complete : function(xhr, statusText){
alert(xhr.status);
return null;
}
});
}
This is PHP that will be loaded:
<?php
header('Content-type: text/xml');
//Do something
$done = true;
$response = buildXML($done);
$xmlString = $response->saveXML();
echo $xmlString;
function buildXML ($done){
$response = new SimpleXMLElement("<response></response>");
if($done){
$response->addChild('outcome','ok');
}
else {
$response->addChild('outcome', 'ko');
}
return $response;
}
When I instantiate a new object, and I use it to load a request, it always return to me error, and status code is 0. The server correctly generates an XML document. Why I can't get a correct 200 code back?
If this happens on your second call to require, it's because the call to abort() results in your callback being called with a status code of 0. You should later get the correct result for the second request.
In jQuery 1.4 there's also a bug where your success callback is called after an aborted request. See my answer to Request periodically coming back empty under race conditions.
Unrelated to this issue, there are variables in your code (timer and ajaxCall) that seem to be referenced both with and without a leading underscore.