Im using a basic jquery ajax call.
I make a call to a php file without input parameters with option datatype set to json.
I want the server to parse the php which queries a table in a mysql db, convert it to array and finally encode it to json and return.
I tried a test call from the browser by copying the php file url in the address field, and it shows that it works, since I can see a blank page with all the rows of the table in json formatting.
Instead, when calling from my javascript code the $.ajax call fails with error
Requested JSON parse failed
which means ajax call was expecting json (since I set option datatype to that) but received another format.
So I tried removing the datatype option from the call, and lo and behold I got a response success, but what did I received from my php file?
Well, it was the whole code in the file, like the server doesn't parse it cause it thinks it's plain text.
Is there a way out of this problem? Thanks.
Send also content header with json data
<?php
header('Content-Type: application/json');
echo json_encode($data);
The ajax function is expecting a JSON encoded document so you have to send a header with the response saying that the response contains JSON. Something like this:
<?php
header('Content-Type: application/json');
// All your code here
echo json_encode($someArray);
?>
I'm an idiot, I may answer my own question, I was debugging jquery from visual studio, which automatically instatiates an iis web server, and it explains why it was treating php files like text files. Obviously under apache everything works fine.
Sorry for taking your time....
Related
I have a json string being printed using Lib.print(string); in haxe/php and am hosting that on my localhost
I've checked http://localhost/index.php, and it does indeed print the json object as text.
My HTML5 app has the following code in it
var h = new HttpJs('http://localhost/index.php');
function traceFunc (d:String){trace(d); }
h.onData = traceFunc;
h.onError = traceFunc;
This has yet to come back with an onData response (or onError for that matter). I know I have to be missing something simple.
It seems like you forgot to actually invoke the request?
h.request(false);
(using false for the post argument to make sure it's a GET instead of a POST request)
Im developing a javascript/php/ajax application and have stumbled across some problems.
Im confident at javascript and ajax but my php is a little rusty.
My aim is to get a json file from the server, modify it using javascript, and then save this modified json back to the server.
After some research it was obvious that the modified json file must be sent to a php file, this php file will then do the saving.
HOW do i send a json string from javascript to php? OR how do I get the php file to pick up the json variable from the javascript?
im assuming the php will be something like:
<?php
$json = $_POST["something"];
?>
but how do i send or "post" the javascript variable to the php file?
I was thinking about creating a hidden html form, setting a hidden textbox to the json string, then posting the html form
But surely there must be a way without including the html middle man?
Im looking for answer WITHOUT jQuery. Seeing as this is an application i would like a relieve the dependancy of jQuery.
The only, as far as I know, proper way to do this is sending data to a file through Ajax, then attaching some POST or GET data.
Example:
You could send the data in the url as GET:
http://example.com/foo.php?myvalue=cake
And then in the php you'd say:
<?php
$yourvalue = $_GET['myvalue'];
// Some code to save it to the database/server
?>
You would need to create a XMLHttp-Request like this:
xmlhttp.open( "POST", url, false );
xmlhttp.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8'
);
xmlhttp.send("data=yaystuff!")
So you can send it. In PHP just get the $_POST['data'] variable and do some json_decode() on it, if you send JSON :)
-- EDIT --
Solved by using JSON dataType.
-- QUESTION --
Hello,
I am trying to send iframe video embed code to db. I finally found javascipt's escape() command and it was working if I send only the embed script. Later, I tried to add embed code after some text and it neither gives an error at ajax or mysql nor adds the post.
What is the problem here? Do you have another solution for sending embed code without corruption instead of javascript's escape()? Can I do something with php?
Thank you,
I am getting content from page with var content = escape($('#textarea').html()); and sending with ajax. If I would use JSON type, will it send without corruption?
Sample iframe:
<iframe title="YouTube video player" width="540" height="435" src="http://www.youtube.com/embed/8ImAG94lSOE?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>
Solved by using JSON dataType.
The problem could indeed be caused by a special character, I am not too familiar with the escape command of JavaScript, but I do know what you can do with php, make sure your data is going through the Ajax request and try using htmlentities($string) to convert every HTML tag into its encoded version, which will allow you to store it in your database.
Also, in your Ajax request make sure of every step with your string, try using alerts to show that your string is going through or that it is being at least sent to the php file, inside the php file you can try printing or "echoing" the string to see the final result and then alert it in the Ajax request, here's a small example of it in jQuery:
$.post("ajax/edit.php", {id_poll:$('#idPoll').val(),id_css:$('#css_name').val(),css:$('#poll_description_textarea').val()},
function(applyData){
if ( applyData.toString() == 'invalid' ){
$('#pollError').html('Global styles cannot be modified.');
$('#pollNotice').html('');
}
else{
$('#pollNotice').html('The changes to the style have been applied.');
}
});
In the previous example I make an Ajax request in which I send CSS classes from a textbox, inside the php file I verify certain data and in case something goes wrong I return a simple string of "invalid" or "valid" to determine the outcome, along the way in such a request you can throw in an alert or two to verify that your string is being sent since it would be difficult to see an error in your JavaScript.
This might not be too specific but I hope it helps a bit.
I am trying to debug a simple PHP/JSON/jQuery problem.
The following PHP script:
header('Content-type: text/javascript');
echo json_encode(array('type'=>'error','message'=>'arg'));
is being consumed by jQuery but when the line:
var results = jQuery.parseJSON(responseText);
is executed, the jQuery JSON parser gives the following:
uncaught exception: Invalid JSON: <head></head><body><pre>{"type":"error","message":"oops!"}</pre></body>
Obviously the head/body/pre are not supposed to be returned.
I cannot see any hidden characters nor anything out of order in my PHP code..
Any ideas?
This one has had me stumped for the last two days. I'm using the jQuery Form plugin's ajaxSubmit function to submit a form via AJAX without reloading the page. I finally stumbled across the answer after this question showed me a parameter I hadn't noticed previously: dataType.
Behind the scenes, an iframe is being created and is actually making the call back to the server. The response from the server is being pulled from the iframe, which is bringing along with it the tags.
The jQuery Form plugin handles the situation by allowing you to specify the type of response to expect from the server. If I specify 'json' as the response type, the following few lines of code are executed to get the JSON from within the tags:
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
if (pre) {
xhr.responseText = pre.innerHTML;
}
(doc is a reference to the iframe's document and xhr is the XmlHttpResponse object that ultimately gets returned from the plugin's function.)
I don't know exactly how you're making your AJAX call, but I'm guessing a similar construct (perhaps using a document fragment) will allow you to extract the necessary JSON from the response.
Try not to send header('Content-type: text/javascript');
json for php find "function send_as_json($obj)"
headers types
Set the header to application/json.
I have a php file that outputs json encoded text via
echo '(' . json_encode( $final ) . ')';
And i have a javascript file that fetches that page
$.getJSON(file, function(data){
var object = eval(data);
alert(object); //for testing
...
When any browser other than firefox 3.5 visits the page that calls .getJSON it alerts null
BUT!!! If i take the text that is output by the php file paste it into a new file and load that via .getJSON it works fine. It's only when its output by php that it doesn't work.
The only difference i can see is that the PHP file's content length is 2 more than the other, i can't figure out why.
Thanks
UPDATE
I created a small array to test it with other data and it's working. There's something in my data that's causing the issue. Looking now...
a call to array_merge is the culprit.
data is not a string, it is a JSON object. Therefore eval will not work on it. Try the following instead:
$.getJSON(file, function(data){
alert(data); //for testing
I've narrowed it down to a call to array_merge that is corrupting the data somehow.