Can't pass parameters to $.getJSON() - javascript

I'm using jQuery and PHP to communicate with my MySQL database. jQuery calls a PHP script and passes along the parameters to look up, then PHP looks through my MySQL database, turns it into JSON and then echos the JSON back to my jQuery. In theory that should work. It returns the jQuery in the correct format and all, however I run into a problem when I use the optional data parameter in $.getJSON(). Heres what I'm doing:
// I would like to send a string to the php file on my webserver
$.getJSON('http://garbagewire.tk/server/refresh.php', { user:"jacob.pickens" }, function(data) {
console.log(data.ammount);
});
However, I never get the data logged back, I get this error here:
08-18 13:35:01.866 17420-17420/? W/WebConsole﹕ Console.ERROR: Uncaught TypeError: Object #<Object> has no method 'call' (http://garbagewire.tk/zepto.js:2)
And here's my php: (MySQL stuff omitted)
<?php
$user = $_GET['user'];
echo "{";
echo "\"ammount\":", json_encode($user);
echo "}";
?>
I'm using the App.js api to make a kik webpage if that is to any importance.

Are you sure you're loading jQuery correctly? Try jQuery.ajax you should be able to pass data through getJSON
http://api.jquery.com/jquery.getjson/
$.getJSON( "test.js", { name: "John", time: "2pm" } )
.done(function( json ) {
console.log( "JSON Data: " + json.users[ 3 ].name );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
Also you can do echo json_encode(['amount'=>$user]) instead of making the string yourself and get the same output.

Try this, I guess you got confused with $.post syntax
$.getJSON('http://garbagewire.tk/server/refresh.php?user=jacob.pickens', function(data) {
console.log(data.ammount);
});

If you want, you can pass your parameters through the url
$.getJSON('http://garbagewire.tk/server/refresh.php?user=jacob.pickens', function(data) {
console.log(data.ammount);
});

Related

AJAX POSTing to PHP isn't working

I am trying to POST a JSON to PHP where it should be decoded and pushed to MySQL database.
This is my JavaScript code.
var dictstring = "{sensorid: \""+ name +"\", x: " +pos.x +" ,y: "+pos.y+"}";
console.log(dictstring);
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
url: "myfile.php",
data: JSON.stringify(dictstring),
success: function(data){
alert('Success');
},
error: function(e){
console.log(e.message);
}
});
And this is my PHP code
<?php
$jsonData = file_get_contents('php://input');
$data_back = json_decode($jsonData);
$unit = $data_back->{"sensorid"};
$x_axis = $data_back->{"x"};
$y_axis = $data_back->{"y"};
// Create connection
$con=mysqli_connect("xxxxxxx:xxxx","xxxxx","xxxx","xxxxxxxx");
// Check
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert Values
$sql_hm = "INSERT INTO xxxx(unit, x_axis, y_axis)
VALUES ('$unit', $x_axis, $y_axis)";
if ($con->query($sql_hm) === TRUE) {
echo "values inserted successfully";
} else {
echo "No data ";
}
?>
I know the PHP part works - I tried POSTing JSON data with contentType: application/json from a REST client app and it works. But when I am trying it with my Javascript code, it isnt POSTing. I can see the "dictstring" string value in console. I cannot see the "Success" alert too. Interestingly, "Success" alert is shown if I remove the dataType: "json" line. But, POSTing is still not happening as I cannot see the values in database.
What am I missing here?
var dictstring = "{sensorid: \""+ name +"\", x: " +pos.x +" ,y: "+pos.y+"}";
You have a string.
data: JSON.stringify(dictstring),
Which you then convert to a JSON representation of that string.
$data_back = json_decode($jsonData);
Which you decode to a string.
$unit = $data_back->{"sensorid"};
Which you try to treat like an object.
Start with an object, not a string:
var dictstring = { sensorid: name, x: pos.x, y: pos.y };
… you probably want a different variable name too.
dictstring is already in JSON format, you don't need JSON.stringify in your JS
dataType: "json" is to be used if the data returned from server is JSON
You can create an array of messages and then use echo json_encode($array); to return JSON data to your js.
Coming to your problem, from the question and the information you've supplied, I couldn't find an obvious problem, but I could suggest to use console.log(data) in your success function and see what is returned. You'll at least know if it hit your php page or returned with some error like 404 or 500.
Try $data_back['sensorid']
or
Just print_r($data_back); and see the data structure of $data_back and then try access the data accordingly.
Okay it might sound silly but have you made sure to state that you're using JQuery in the java script because the amount of times I've been doing ajax and i cant figure out why it wont work and its because I haven't declared the JQuery.
like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">

Cant get PHP variables using AJAX

I can't seem to figure out what's the problem. For my next little project I'm creating dynamic web page with database and etc. I need to get all the necessary variables from PHP file. But for some reason I cannot do it if I include another PHP file. (I need it for database queries).
main.php
include ('databaseQueries.php');
if (isset($_POST["points"])){
$points = json_decode($_POST["points"]);
if($_POST["execute"] == 1){
}
}
$advert= array(
'Hello' => 'Hello world!',
'bye' => 'Why bye?',
);
echo json_encode($advert, $another);
pageJs.js
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
databaseQueries.php
$another = "another string";
If I remove the include and $another variable from json_encode. Everything works and I get object in console log. But if I leave the those two things, Ajax call fails.
What I'm doing wrong and how can I get both the $test array and $another variable?
Thank's in advance!
You are using json_encode incorrectly. From the documentation:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
You are trying to send $another to the function as the options parameter.
You could do something like this:
$ret = array($advert, $another);
echo json_encode($ret);
Unless I'm completely wrong, I can't see where you're sending anything TO your post
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json'
// I would expect a data call here, something like:
data: $(form).serialize(), // OR { points: 3, execute: 1 }
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
I assume that you want to spit back some results with the format of result->key;
So Keeleon's answer above is good:
$ret = array($advert, $another);
echo json_encode($ret);
But you can also do:
//Adding everything to array, and asking json_encode to encode the array is the key. Json_encode encodes whatever is in the first argument passed to it.
$ret = array('advert'=>$advert, 'another'=>$another,'test'=>$test);
echo json_encode($ret);
Hopefully, this answers your questions.

Error in JSON when I am doing a AJAX call in jQuery

I'm getting the following error in the console when I am trying to return a string of JSON from a AJAX call.
Uncaught SyntaxError: Unexpected token
I have added a codepen with the code I am using.
If you click the convert button and look in the console you will see the error.
I cannot for the life of me figure it out.
Thanks.
JB
http://codepen.io/anon/pen/XJvyWq
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("Data: " + data);
}, 'json')
});
First remove the "=" .
for a string display in the console you can use the methode stringify of the JSON object
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback", function(data){
console.log("Data: " +JSON.stringify(data) );
}, 'json');
});
or for display an object in the console you can juste write :
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback", function(data){
console.log(data );
}, 'json');
});
the result :
Object {To: "CAD", From: "EUR", Rate: "1.3138"}
Remove json at the second parameter as #SnehalShah said and it'll work
$('.convert').click(function(){
$.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("Data: " + JSON.stringify(data));
});
});
http://jsfiddle.net/1z20m3pL/
Try this way::
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("To: " + data.To);
console.log("From: " + data.From);
console.log("Rate: " + data.Rate);
});
});
Remove the callback=? from the end of the URL you are providing OR remove the 'json' from the .get() method call.
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD", function(data){
console.log(data);
});});
This is because jQuery assumes that when you pass a "callback" parameter in URL and type 'json' that the response will be JSONP. But in this case the server sends a JSON string. Instead of passing "?" if you pass the name of an existing function the error will not be thrown.
The current response by the server is:
{"To":"CAD","From":"EUR","Rate":"1.3138"}
If the Server was responding with JSONP and if the callback you passed was "test" then the response would have been:
test({"To":"CAD","From":"EUR","Rate":"1.3138"})
http://codepen.io/tejzpr/pen/yymQNz?editors=101 explains both cases.

Uncaught SyntaxError: Unexpected token - JSON character encoding

In my controller I handle POST requests with ajax and adds data from GET requests directly to the js-code
mycontroller.php
$sServiceNumber = isset($_POST['ServiceNumber']) ? $_POST['ServiceNumber'] : $_GET['ServiceNumber'];
//Here I do a db call for sServiceNumber and fetch some data as array $aAllrows
$aResponse['ServiceNumber'] = $sServiceNumber;
$aResponse['Data'] = $aAllrows;
$sJson = json_encode(self::convertToStrictUtf8($aResponse));
if (isset($_POST['ServiceNumber'])) {
echo $sJson;
exit;
} else {
$sJs = '
$(document).ready(function() {
var sData = \'' . $sJson . '\';
handleResponseData(sData);
});';
MyHtmlHead::addExtraJsCode($sJs);
//continue with rendering html page here..
}
When I call this with ajax everything works fine but when I try to run handleResponseData() directly I get Uncaught SyntaxError: Unexpected token on special characters.
My JavaScript
function handleResponseData ( rawData ) {
response = jQuery.parseJSON(rawData); //<--this is where the error occurs (on GET requests)
//Make use of response data
}
$("form[name='searchform']").submit(function( event ) {
event.preventDefault();
// Send post and fetch some data!
$.post(baseUrl, { ServiceNumber: $("input[name='ServiceNumber']").val(), time: "2pm" }).done(handleResponseData);
});
Lastly here comes my conversion method
protected static function convertToStrictUtf8 ($p_aValues) {
function detectEncoding(&$mValue) {
if (!mb_detect_encoding($mValue, 'UTF-8', true)) {
$mValue = utf8_encode($mValue);
}
}
array_walk_recursive($p_aValues, 'detectEncoding');
return $p_aValues;
}
How come the json string parses fine when fetched with jquery $.post but not when embedded into code manually? How do I solve this issue?
edit:
Stripped down version of rawData from console.log(rawData)
GET
{"ServiceNumber":"485218-1138932068","Data":[{"RowId":"AEEA-IU3A61","ServiceRequestId":"AEEA-IU39LX","Name":"SV LIDEHÄLL)","FileSize":"8812","ServiceNumber":"485218-1138932068","Subject":"O(BERGMAN/LIDEHÄLL)
","Area":"svrT","Dir":"1702"}]}
POST
{"ServiceNumber":"485218-1138932068","Data":[{"RowId":"AEEA-IU3A61","ServiceRequestId":"AEEA-IU39LX","Name":"SV LIDEH\u00c4LL)","FileSize":"8812","ServiceNumber":"485218-1138932068","Subject":"O(BERGMAN\/LIDEH\u00c4LL)\r\n","Area":"svrT","Dir":"1702"}]}
The problem was caused by Line breaks .
As the jQuery.parseJSON() docs states: "control characters" such as a tab or newline is not allowed.
When calling with $.post the new line chars were converted to a string "\r\n" which is why that case was working.
Adding something like this to remove new lines finally solved it.
function stripNewLines(&$mValue) {
if(is_string($mValue)) {
$mValue = trim(preg_replace('/\s+/', ' ', $mValue));
}
}
array_walk_recursive($aResponse, 'stripNewLines');
In your PHP controller, before echo JSON respose type the following line
header("Content-Type: application/json");
and also in jQuery Ajax call you need to mention data type as JSON
$.ajax({
...,
...,
dataType: 'JSON', // it is necessary to get JSON response
...
});

JSON Request appended with [object%20Object] in jQuery

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Categories

Resources