I am currently trying to figure out how I can find out what errors are in my php script.
I have made a small script which an error on purpose. Using the chrome console I get...
Uncaught SyntaxError: Unexpected token <
However, normally PHP errors would point you to the line in which the error occurs.
Here is my AJAX Request.
var myData = "Hello";
$.ajax({
type: "GET",
url: 'test.php',
datatype: 'json',
data: { data: myData},
success: function(output) {
var result = $.parseJSON(output);
for(var i=0; i<result.length; i++){
console.log(result[i]);
}
}
});
And my PHP script with the syntax error
$data = ($_GET['data']);
echoo boom;
echo json_encode(array($data, "test"));
As you can see, line 2 is the error but the error in my console gives me no information as such.
Thanks
$.ajax({
type: "GET",
url: 'test.php',
datatype: 'json',
data: {},
success: function(output) {
result = output;
for(var i=0; i < result.length; i++){
console.log(result[i]);
}
}
});
By defining the dataType as json the output is already parsed. Parsing the already parsed 'output' again led to the error. So it was a client side / javascript error.
ALso note that - in case an error occurs - the actual error message is parsed too. So you get an array containing the "fragmented" error message from the server ;)
When the error is server side you typically only get an error message (maybe 500 or Server Error) on the client side which is very non-specific. You must debug on the web server. Once I see such an error I check out the web server's error log file (which will show both compile and run time errors).
Please write :
$data = $_GET['data'];
echo boom;
echo json_encode(array($data, "test"));
Instead of :
$data = ($_GET['data']);
echoo boom;
echo json_encode(array($data, "test"));
And write :
$.ajax({
type: "GET",
url: "test.php",
timeout: 6000,
success: function(data) {
json = $.parseJSON(data);
for (var i = 0; i <= json.length-120; i++) {
console.log(json[i]);
}
}
});
Use the debugging tools in your browser. Specifically look for a tab or set of functionality for monitoring network requests. This will show you the actual request and response to and from the server in your AJAX.
What's happening here is your PHP code is generating an error, which results in returning some kind of HTML to the browser (possibly showing the error message). However, look at what you're doing with the response:
var result = $.parseJSON(output);
If output is HTML and not JSON, then this code will fail with an error. Since JSON syntax doesn't use < but HTML does, I would expect you to get the error:
Uncaught SyntaxError: Unexpected token <
Related
I'm making a function to get a xml file and edit it. I've never done that before so I searched a good way to get an xml file. I decided to use ajax, but the file is never returned because the url is undefined.
EDIT :
I edited the code and made the treatment in the success function. Now there is no problem with this file.
Here is the update of the ajax part :
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
//file = $.parseXML(xml);
// Editing the file to have the good dates
$(xml).find('StartDateTime').text(start);
$(xml).find('EndDateTime').text(end);
var strFile;
if (window.ActiveXObject) {
strFile = xml.xml;
} else {
strFile = (new XMLSerializer()).serializeToString(xml);
}
var encoded64 = Base64.encode(strFile); // Encoded in base64
var encodeURL = encodeURIComponent(encoded64); // Encoded URL
var AR = urlAR + encodeURL; // The URL to open
window.open(AR, '_blank');
}
})
Now all is working well about the xml file, I have a little problem with the window.open, which open my url but with %31 at the beggining, but it's another problem.
Thank you for your help !
file is undefined because you are declaring it inside a ajax success function
function openRecords(start, end) {
// Extraction of the xml file
var file;
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
file = $.parseXML(xml);
},
error: function(ex) {
console.log(ex);
}
})
// Test
var start = '2016-02-15T12:57:00+01:00';
var end = '2019-02-16T13:57:00+01:00';
setTimeout(function(){
// Editing the file to have the good dates
file.find('StartDateTime').text(start);
file.find('EndDateTime').text(end);},1500);
}
Add an error callback:
error: function (ex) {}
Many things can be happening, you will get more info with the error callback. Probably you are querying an incorrect url. Do not trust that undefined upon url, see what returns your jquery ajax function. Maybe you should be querying something like '\files\xxx.xml'.
can you give me a picture of Network in your broswer? I want to know the URL is send or not:
1. F12 open your console
2. select the Network tab
3. refresh the broswer
4. check the request is send or not
I come asking because I can't find any more trail for my problem. Hope someone could help me :)
Since several week, all in a sudden, my json got a weird unreadable character, provoking ajax request to raise an error instead of success state.
My code didn't change. I tried more tips like a simple boolean as return in the json. But nothing can help.
I lighten the code in order to avoid possible wrong character data.
I get an SyntaxError: Unexpected '' on line 1 when i try to validate on jsonlint he detects the wrong character
my code server side in php is the following :
$resultat = array();
$resultat['Success'] = true;
echo json_encode($resultat);
and my js ajax request :
var param = [{ name: "tbActionToDo", value: "InitialiseMailbox" }];
$.ajax({
type: "POST",
url: "actions/DatasourceEmail.php",
data: param,
dataType: "json",
dataFilter: function(data, type){
return data;
},
error: function(xhj, statut, thrown){
Notify("Danger", xhj.responseText);
},
success: function(result){
// do something
}
});
Thanks for your time and help !!
With some help, I have managed to make a form that validates and confirms user password before adding the user to the database. I have encountered some problem as the data of the user is not sent and giving me the following error :
Uncaught SyntaxError: Unexpected token in JSON at position 0 at JSON.parse () at Object.success (confirm3.php:29)
at i (jquery.min.js:2) at at A (jquery.min.js:4) at
XMLHttpRequest. (jquery.min.js:4)
The error
at Object.success (confirm3.php:29)
is referring to this following line
var data = JSON && JSON.parse(response) || $.parseJSON(response);
The POST variable
$UserNm=$_POST["UserNm"];
$UserId=$_POST["UserId"];
$UserPwd=$_POST["UserPwd"];
To make things clear, the data that should be returned is $ReturnMessage which is retrieved from stored procedure. $ReturnMessage will display the status of the operation for both successful and fail operation.
An example of $ReturnMessage :
"USER ID EXIST. (011 CODE)."
"USER ID MINT20 ADDED."
POST method is used : if(isset($_POST['Submit'])) {
$ReturnMessage :
if(isset($ReturnStatus) && $ReturnStatus==1) {
$ReturnMessage=odbc_result($stmt,'ReturnMessage');
}
}
$ReturnMessage = utf8_encode ($ReturnMessage);
echo json_encode($ReturnMessage);
}
Script :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#myForm").on("submit", function(e) {
e.preventDefault();
var password = $("#UserPwd").val();
var confirmPassword = $("#ConfirmPassword").val();
console.log(password,confirmPassword)
if ($.trim(password) === password &&
password !== "" &&
password === confirmPassword) {
$.ajax({
url: "confirm3.php",
method: "POST",
data: { Submit: "true" },
success: function(response) {
var data = JSON && JSON.parse(response) || $.parseJSON(response);
alert(data);
}
});
} else {
alert("Please Enter Password Correctly");
}
});
});
<script>
I'm kind of confuse. Please guide me. Thank you.
Have you set your content-type in your php?
header('Content-Type: application/json');
Also you don't need to put "true" in quote marks, when the json gets to your php script, once you run json_decode, php will recognise it as a boolean.
First of all, jQuery can decode JSON automatically for you (and it will make its best to guess). Trying to do it manually only makes your code more verbose and error-prone. However, you don't give it any hint. Nothing in the code you've shared gives any clue about your intention to use jQuery.
All the phases where you can do so, in chronological order:
Report data type from web server. If you happen to be using Apache:
<Files "confirm3.php">
ForceType application/json
</Files>
Report data type from PHP:
header('Content-Type: application/json');
Tell jQuery that you expect JSON:
url: "confirm3.php",
method: "POST",
dataType: "json",
data: { Submit: "true" },
success: function(response) {
console.log(data); // Already decoded (don't use alert to debug!)
}
You can certainly omit almost any step, but not all.
Secondly, if you get a JSON parse error the very first you need to check is whether the response is valid JSON. The most straightforward way to see it is using the browser developer tools, more specifically the "Network" pane.
Use this in my case there was some null bytes so this i figured out and it fixed my issues.
var data3 = data.substring(data.lastIndexOf("{")+1,data.lastIndexOf("}"));
count = $.parseJSON("{"+data3+"}");
alert( count.firstname ); // firstname is the key so you can use anything to test it.
I have a function that makes a ajax call. The .done doesn't seems to be firing. I checked for the error on my console. It says
function getIncidentInfo() {
$.ajax({
type: "GET",
url: "../../page_components/statsboard/stats.php",
data: $(this).serialize(),
dataType: "json",
}).done(function(response) {
incidentAr = response;
for (var i in incidentAr) {
var zaNorth = parseInt(incidentAr[i].zaNorth);
......
}
}).fail(function(xhr, status, error) {
console.log("Status: " + status + " Error: " + error);
console.log(xhr);
});
}
I asked my friend to try the same piece of code and it works.
The script in stats.php is throwing an XDebug error and is returning HTML describing the error instead of the JSON you are expecting. Loading the stats.php page in a browser, or check your PHP logs to find out what the error is.
Check .always(response) instead of .done(response). Some services return non 200 codes with a response body to describe the error.
Check response.responseJSON, response.responseText, and response.responseXML. You may have to state response.responseJSON = eval(respaonse.responseText).
However, I see that the responseText is of HTML type, so my guess (and I say this because you're getting a 200 status and not a 404 or 500) is that you are getting a more generic server error that is rendering a response from a route you did not intend to query.
I'm trying to make a graphic with jqplot extracting the values vía mysql ajax, I have read so much information about this, i'm IT and to me it's a little embarrasing making this question. It's causing me a big headache :(
I've spent 20 days resolving this but i can't alone myself, anyone can help me please? I have tried almost everything (json.parse, parsejson, getjson, datatype html, datatype json, method get and post.....)
I know it will be easy...
Why crash when i try to do JSON.parse(resultado) ?
http://jsonlint.com/ say it's a Valid Json, but when I try to do JSON.parse he give me an exception saying ("JSON.parse: unexpected character at line 1 column 1 of the JSON data")
It seems is the [ character
Here is the php:
<?php include('conex.php');
$datos=mysql_query("SELECT * FROM Meteorologia");
$arrDatos = array();
while ($rs=mysql_fetch_assoc($datos))
$arrDatos[] = array_map('utf8_encode', $rs);
echo json_encode($arrDatos);
?>
I obtain:
[{"FECHA":"2015-01-01","OZONO":"3","KT":"2","VV":"4"},{"FECHA":"2016-03-03","OZONO":"68","KT":"86","VV":"78"}]
The js is:
try
{
var strHtml = "";
$.ajax({
global: false,
dataType: "html",
async: false,
type: "POST",
url: $("#form").attr('action'),
data: $("#form").serialize(),
success: function(resultado){
alert('success!!'+resultado);
console.log(typeof resultado);
console.log(resultado);
//var datosRecibidos = JSON.parse(resultado);
//var datosRecibidos = jQuery.parseJSON(resultado);
var lista = "";
$.each( resultado, function( key, value ) {
if(value.FECHA == "2015-01-01")
{
alert('si!!');
}
else
{
alert('sino!!');
}
});
},
error: function(data){
alert('Error!!: '+data);
}
});
}
catch(ex)
{
alert("catch!!"+ex);
}
With the $each key value ... can i move inside the array?
After trying a lot of things (changing datatype json,html,..., method get, post...)
I debugging with the address file:///C:/xampp/htdocs/traerdatos/index.html
instead of http://localhost/traerdatos/index.html
So the solution is to CHANGE THE ADDRESS TO LOCALHOST
(Thanks to reformed that helps me with his vision)
Novel error =)