I am having Unexpected token b in position 0 from the json that I returned in my php file to my javascript.
$file = array(
array(
'src' => 'http://localhost/grapesjs-dev/uploads/'.$_FILES['files']['name'][0],
'width' => '150',
'height' => '150',
)
);
//var_dump(json_encode($file));
return json_encode($file);die;
I have read something that is related to this and could be the solution but I don't know how to change my php code to match the solution that is in this stackoverflow question. link here guys to the post
image to network in debug tool
UPDATE AND SOLUTION
I deleted all the var_dumps which gave me the error.
Now I'm getting a new error which is Unexpected end of JSON input.
I changed my json format(the arrays).
And used echo rather than return.
Just change return to echo. That should solve the problem
echo json_encode($file);die;
Looking at network screen shot it is clear that you are doing var_dump somewhere in your PHP code which is printing data types rather than actual json object, which javascript is unable to read.
Remove the var_dump and put echo json_encode(your_desired_data) and check it. It should fix the issue.
Related
I have a php array of products that I want to move to javascript but when I json_encode it errors out giving me
Uncaught SyntaxError: Unexpected token ;
The debugger is giving me
var phpPro=;
and the code reads
var phpPro=<?php echo json_encode($pro)?>;
I have also encoded the array in the php script and tried to assign to js variable from there.
php =
$jpro=json_encode($pro);
js =
var phpPro=<?php echo $jpro;?>;
This code was actually working and now that I'm trying to copy it to another site it is not working. All the products are in the php recordset when displayed so I know they are there.
Hi I have troubles to generate JSON with json_encode() PHP function.
I have a .php file that is doing only following:
<?php
// include_once for a few files here
$address = MyModelClass::getByAtrrId(52);
echo json_encode($address, JSON_HEX_QUOT | JSON_HEX_APOS) ;
result is following:
{"number":"7"}
Then there is jQuery in another file, retrieving this by following code:
$(document).ready(function e() {
let file_path = 'myJson.php';
let json = $.getJSON(file_path);
console.log(json);
let json_obj = JSON.parse(json);
However $.getJSON reads this string as "{\"number\":\"7\"}, therefore JSON.parse ends with following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I'm sorry, I'm almost 100% sure this is beginner's mistake, however I have failed with my search for correct answer. Anyone having idea what might be the problem?
I have found plenty of articles taking into account input into jason_encode, but right now I have more feeling real trouble is in fact input to jQuery function, however I'm still unable to resolve.
If your web server sends JSON, it's good practice to set the Content-Type accordingly:
header("Content-Type: application/json; charset=utf-8");
On the client, you need to do:
$(document).ready(function() {
$.getJSON('myJson.php', function(response) {
// the response is already parsed by jQuery
alert(response.number);
});
}
$.getJSON() is asynchronous, so you need to pass a handler function to process the response.
I have a PHP backend script where I am creating a PHP Session variable:
if(!isset($_SESSION))
session_start();
if(isset($_SESSION['uid']))
unset($_SESSION['uid']);
$_SESSION['uid']=$this->_out;
In my HTML Script I am using the following way to access it:
editor = new $.fn.dataTable.Editor( {
ajax: {url:"euseradd.php",complete : function(){var uid='<?php if(!isset($_SESSION)) session_start();if(isset($_SESSION["uid"])){echo $_SESSION["uid"];unset($_SESSION["uid"]);}?>';alert(uid)}},
......................
} );
But I am not getting the value - my alert prints empty value. However when I try to echo the session variable output in WAMP server Apache logs by below way:
echo 'Value is ' . $_SESSION['uid']
I get an error that 'Notice: Array to string conversion' - my intention is to log the value in some logs to see whats the value backend is also assigning.
EDIT:
I modified the echo statement by below way:
echo 'Hello ' . serialize($this->_out);
And Now I get the data at browser side like:
Hello a:5:{s:2:"id";i:-1;s:11:"fieldErrors";a:0:{}s:5:"error";s:0:"";s:4:"data";a:0:{}s:3:"row";a:11:{s:8:"DT_RowId";s:7:"row_135";s:2:"id";s:3:"135";s:9:"last_name";s:6:"sdfdsf";s:10:"first_name";s:3:"dsf";s:8:"homeaddr";s:21:"sdfdsfsdfdsfdsfdsfdsf";s:5:"email";s:8:"s#jj.com";s:10:"officeaddr";s:24:"wwwwwwwwwwwwwwwwwwwwwwww";s:6:"mobile";s:8:"11111111";s:3:"age";s:2:"11";s:9:"chargeamt";s:2:"11";s:10:"start_date";s:10:"11/11/2011";}}{"row":{"DT_RowId":"row_135","id":"135","last_name":"sdfdsf","first_name":"dsf","homeaddr":"sdfdsfsdfdsfdsfdsfdsf","email":"s#jj.com","officeaddr":"wwwwwwwwwwwwwwwwwwwwwwww","mobile":"11111111","age":"11","chargeamt":"11","start_date":"11\/11\/2011"}}
I am in need to extract the value "id":"135" from it.
Actually I cannot use success function for my operation due to some constraint. And cause I am fixing an issue I am writing the code for the issue that I have
EDIT:
I tried printing the values like below:
echo 'Hello ' . serialize($this->_out['row']['DT_RowId']);
I get the below output at console logs:
Hello s:7:"row_140";{"row":{"DT_RowId":"row_140","id":"140","last_name":"sdfdsf","first_name":"dsf","homeaddr":"sdfdsfsdfdsfdsfdsfdsf","email":"s#jj.com","officeaddr":"wwwwwwwwwwwwwwwwwwwwwwww","mobile":"11111111","age":"11","chargeamt":"11","start_date":"11\/11\/2011"}}
I am not sure what structure of the output is - but how can I extract "id":"140" from above. I just guess that "row_140" is not a constant name but rather row_# record number
EDIT:
Below is the output of echo print_r($this->_out); as requested:
Array
(
[id] => -1
[fieldErrors] => Array
(
)
[error] =>
[data] => Array
(
)
[row] => Array
(
[DT_RowId] => row_157
[id] => 157
[last_name] => sdfdsf
[first_name] => dsf
[homeaddr] => sdfdsfsdfdsfdsfdsfdsf
[email] => s#jj.com
[officeaddr] => wwwwwwwwwwwwwwwwwwwwwwww
[mobile] => 11111111
[age] => 11
[chargeamt] => 11
[start_date] => 11/11/2011
)
)
1{"row":{"DT_RowId":"row_157","id":"157","last_name":"sdfdsf","first_name":"dsf","homeaddr":"sdfdsfsdfdsfdsfdsfdsf","email":"s#jj.com","officeaddr":"wwwwwwwwwwwwwwwwwwwwwwww","mobile":"11111111","age":"11","chargeamt":"11","start_date":"11\/11\/2011"}}
Am not really sure whether I understood your issue. But session_start() is supposed to be called at the very beginning of the page in your php script. That is, before printing anything. Because the session headers should be sent to the browser.
When you preform the ajax, don't mix up with the PHP. Send the user details to the PHP script via ajax. Then make the php script return the user id back as the response and then you can use it in your javascript. The page that you get on your browser is actually as an output of the PHP script. I mean, all PHP code in your PHP script would be executed and the output is what you are getting on your browser. So, when your page is executed(accessed from browser), that var uid = ''; in your javascript will already be having a result of the PHP script. It won't get updated after that AJAX call!
And for the array error, I believe you are assigning an array to the $_SESSION['uid']. I think it would be better if you just store the value(ie. the user id) as int or string there in that session instead of array!
You cannot access php variables from jquery like that
There is a much simpler solution to your problem just echo $_SESSION['uid'] to your jquery callback function and access it using jquery some what like this
useradd.php
if(!isset($_SESSION))
session_start();
if(isset($_SESSION['uid']))
echo $_SESSION['uid'];
unset($_SESSION['uid']);
Jquery
$.ajax({
url : "euseradd.php",
cache: false,
success: function(responseText){
alert(responseText); //this should contain your session uid
}
}); //end of ajax call
return false;
I'm using CodeIgniter form helper, and this is what it does:
Uncaught SyntaxError: Unexpected token ILLEGAL
The code:
jQuery('#window-1').append('<?= form_dropdown('hfdata', $hf_arr, set_value('hfdata'), 'class="span3"') ?>');
As you can see, I'm using a PHP inside of a JS, when I do <?= 'Test' ?> it works.
So it seems like its related with the CodeIgniter function.
As far as i know this error message can be caused by unknown/wrong characters in the code, and from what I saw in the firebug, this CI function is generating text with tabs and line breaks... and that is my problem I guess.
I may be wrong, so please correct me if so.
I will appreciate any solution for this problem.
Chances are you're screwing up your quotes and you need to change the way you're passing that last parameter to the dropdown.
$class = 'class="span3"';
jQuery('#window-1').append('<?= form_dropdown("hfdata", $hf_arr, set_value("hfdata"), $class) ?>');
To explain how PHP and Javascript works: Php is executed on the server, this give html output. You browser will get that output and can do anything with it. From this point javascript can do his job.
You are echoing the php function call to the users browser. Javascript can't call the php function. If you want to do this, then you need to make a php file call that returnes the result you want. But I guess there is an other problem. ( if you want to do this, escape the ' characters)
You need to execute the PHP code on the server. This will give a result. You send this result to the client. On the clients PC javascript will execute your javascript code.
If you want to generate with PHP the javascript code, then you can do something like this ( in PHP on the server!):
jQuery('#window-1').append('<?= form_dropdown('hfdata', $hf_arr, set_value('hfdata')); ?> ');
If this isn't what you want, then you are working on a design problem. Then it's a kind of dead end.
I found the answer myself... As I said, it was caused by the HTML output that was returned from the from_dropdown.
The solution is simple, remove all unwanted characters like line breaks:
<?php
$prepare = preg_replace('/^\s+|\n|\r|\s+$/m', '', form_dropdown('hfdata', $hf_arr, set_value('hfdata'), 'class="span3"'));
?>
jQuery('#window-1').append('<?= $prepare ?>');
In my form, I want to do something with two fields:
"website_domain" and "website_ip_address"
I'm trying to use jQuery/JSON to call a PHP script, pass the website_domain to it, and receive JSON including the IP address of that website.
Problem/Symptoms Description:
It's partially working: On blur, it GETs the url of the PHP script. I can see that much in firebug. I get a 200 OK. Output from the PHP script is valid JSON according to JSONLint:
{"field":"website_ip_address","value":"74.125.225.70"}
But in Firebug, I don't have a JSON tab. I only have Params and Headers tabs. Not even a Response tab.
Needless to say, the website_ip_address field is also not being populated with the data I should be getting from the PHP script's JSON output.
My PHP Script:
It may be important to note that for now, this PHP script on a different domain from my application. Maybe my whole problem is cross-domain?
<?php
$domain = $_GET["domain_name"];
$ip = gethostbyname($domain);
// echo $ip;
$json = array(
'field' => 'website_ip_address',
'value' => $ip,
);
header('Content-Type: text/plain');
echo json_encode($json );
?>
My jQuery/JSON script:
Note this is written inside a Ruby On Rails application view.
:javascript
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name=" +$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
I really hope this isn't just a syntax error on my part. I've been writing/rewriting this for 2 days, based on answers I've found on StackOverflow, to no avail. I'm just missing something here.
You are currently attempting to output the JS object (that is formed from the parsed JSON response) to the field. You need to output a value from within it. So not:
$('#website_ip_address').val(data); //data is an object, not a string
but
$('#website_ip_address').val(data.someValue); //output a property of the object
With your code as it is, I would expect the field to be populated with the string representation of an object, which is [object Object]. You don't mention this, so I wonder whether a) your success function is even firing (check this - stick a console.log in it); b) your jQ selector is sound.
The problem can be with different domain. I had it like this before. Try in php to add header("Access-Control-Allow-Origin: *")
Put your jQuery code inside document ready, example: $(function(){ });
:javascript
$(function() {
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name="+$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
});
});
And you have a missing end })