I'm totally lost, I copied this from my other apache server where this works just great (I get response as json etc...), now I tried this on other apache server and this does not work (the post goes in to server but not as json). If I have 'json' I don't get response (because I have jsonencode in php, but if I just echo result, it will come back, however this javascript will never go to function(r), so it does not ever even alert('test').
When I remove 'json', it works just fine, however I can't have proper response because php handles it and return it in jsonencoded array. This also goes behind function(r) and shows me the results...
There is no javascript error or php errors. I don't even know where to start debugging...
I also tried $.ajax({ equilevant to both methods and same results.
$.post('request.php', { getcontent: 'modal' }, function(r) {
title.html(r.title);
content.html(r.content);
footer.html(r.btns);
$('#modal').modal('show');
tinymce.remove();
tinymce.init({ selector: 'textarea', plugins: 'link anchor code image fullscreen textcolor colorpicker' });
},'json');
Some pointers to look at:
The last argument is the expected datatype of the response, not of the sending object. Maybe php does not receive the post correctly.
You might want to set an header in php to:
header('Content-type: application/json');
To make sure your response is in json.
The url (request.php) of your post might not be reachable
Related
I have written some jQuery + PHP code that takes the HTML from an element on a webpage and saves it on server. Here is the code that I am using:
var page = {
'html': document.querySelector("article").innerHTML,
'url': 'path/current/webpage.php' or (<?php echo "'$current_page'"; ?>)
// Both give same 'url' value. This is not an issue.
};
$.ajax({
url:'https://example.com/update.php',
type:'post',
data: page,
success:function(data){
window.location.reload();
}
});
Here is my code for update.php:
$content = $_REQUEST['html'];
$page = $_REQUEST['url'];
file_put_contents($page, $content, LOCK_EX);
I am not very comfortable with dataType and contentType so I skipped them initially. However the request succeeded sometimes but gave 403() error other times.I did a little research and found that this might be due to lack of dataType and contentType. So, I used the following values:
contentType: 'text/plain; charset=utf-8',
dataType: 'html'
I no longer get any errors but the pages are not actually updating. I also tried setting the values to:
contentType:'application/json',
dataType: 'html'
This time too, I did not get any 403() errors but the page would not actually update.
Does the post data needs to be accessed differently based on the value of contentType like 'application/json' or 'text/plain; charset=utf-8'? Because the updates don't seem to show up on the webpage even with a 200 response code.
Using application/x-www-form-urlencoded; charset=UTF-8 updates some pages but gives 403() error for others.
As Rory said (as did I, in an answer I wrote then deleted when I saw his comment; he was right to comment instead), a 403 response code probably doesn't mean there's a problem with either dataType or contentType. You should look for other reasons the server would refuse to satisfy the request. For instance, as you're posting HTML, perhaps you (or your web host) has some kind of anti-script-injection protection going on. You'll have to track that down, perhaps with your hosting company.
But two things: Some info for completeness, and a potential workaround:
dataType is the type you expect back from the server. contentType is the type of data you're sending to the server.
For the request you're sending, leaving off contentType is correct, because the default jQuery will use is what PHP will expect to see.
You shouldn't have to specify dataType at all; instead, you should ensure the response carries the correct Content-Type header. That means ensuring that your server is configured correctly (for static content) and that your PHP code sets the correct header if necessary via header("Content-Type: data/type-here") The only reason for specifying dataType is if you don't control the server and you know it sends back the wrong type.
If you need to try to work around it, first ask: What if someone sends me malicious HTML directly, not through my web page? The answer is: You need to be careful with what you do with the HTML. For example: If you are going to store this HTML and then display it (as HTML) to a user, that's a Cross-Site Scripting vulnerability and you have to rigorously sanitize that HTML before doing that.
Do not proceed with any workaround until you've answered that question for yourself.
Okay, so in terms of working around it (once you have robust safeguards in place): You might send JSON rather than a standard form, in hopes that whatever is rejecting the forms won't look at it. To do that, you'd change your ajax call:
var page = {
html: document.querySelector("article").innerHTML,
url: <?php echo "'$current_page'"; ?>
};
$.ajax({
url:'https://example.com/update.php',
type:'post',
data: JSON.stringify(page),
contentType: 'application/json; charset=UTF8',
success:function(data){
window.location.reload();
}
});
Then on the PHP side, you'd read that JSON and parse it (reading code below taken from this answer):
$entityBody = json_decode(stream_get_contents(STDIN));
$content = $entityBody['html'];
$page = $entityBody['url'];
file_put_contents($page, $content, LOCK_EX);
Again: Please do not use this unless you have robust anti-XSS safeguards in place. And again, if you do haev robust anti-XSS safeguards in place, you might be able to just use a normal form by changing your server config.
I have several different ajax calls on the same php page, but I get undefined index for only one function (createAlbum).
I send exactly the same parameters in each of my ajax calls. It worked fine for a few tests, but now it only works for the other ones, but not for this specific call.
I suspected that the .js file was still in the browser cache, so I cleared it and tried with other browsers, which worked for a few more attempts.
Now, I can't get it working on any browser, and definitely don't understand why.
Here is my ajax call :
$.ajax({
type: "POST",
url: BASE_URL,
data: {
action: "createAlbum",
data: JSONAlbum
},
cache: false,
success: callback
});
My php file handling the request ($_POST['action'] is always undefined with the above request) :
if (isset($_POST['action'])) {
switch ($_POST['action']) {
// Handle the action
// ...
}
} else {
echo 'ACTION : '.$_POST['action'];
}
The header containing the ajax parameters ("data" is a json containing one or more blob images, this might be the problem, but I didn't find anything saying so) :
And finally, the response containing the error :
I really hope this is not a dumb error of mine, but I asked a friend before posting, and he can't find the solution either.
Thanks for your help !
You said that the error not happens all the time (in some call yes, in other no).
The body post is sent, you see it in console. So we can exclude javascript problem.
So the problem is something that happens before or during the process.
PHP has some limitations on input vars, you can see it in php.ini.
I see that you send images in base64, so it's probable that something of these limitations are triggered.
See for example:
max_input_time
max_input_vars
post_max_size
I've read loads of other questions about this argument, but none could solve my problem.
I make a call to a php page in this way.
$.ajax({
url: 'https://mydomain/page.php',
type: "POST",
data: {
"arg1": arg1,
"arg2": arg2
},
success: function(data, textStatus, xhr) {
//do stuff
},
error: function(xhr, textStatus) {
alert("doLogin\n- readyState: "+xhr.readyState+"\n- status: "+xhr.status);
}
});
Now, if I put this stuff on the same server as the php it works fine. Troubles start when I launch it from localhost.
In that case I receive the following in the xhr:
readyState=0, status=0, statusText="error".
Reading some answers on the topic it seems to be because of a same-origin restriction, so I added a few parameters to the call. notably:
dataType:"jsonp",
crossDomain: true,
Apparently this works better, cause now I receive readyState=4, status=200, statusText="success". Trouble is, textStatus="parsererror". I also tried other things as jsonpCallback, cache, async, jsonp in many configurations with no luck.
Now, I receive no data back, cause this call will only give me a cookie that I need.
My question is: am I doing things correctly, for starters? In both cases, what is the reason of such an error? Does the fact that I call a 'https'/POST change something, rather than a plain http/GET?
Second question is, later on I will have to call some webservices through soap requests, which will return data in xml. Will using this same technique work (assuming jQuery doc is fine and I can write dataType:"jsonp xml" to have it converted on the fly (and assuming it is the right technique as well))? I assume it won't be, as jsonp expects something on the line of callbackFN({...}) rather than an xml, right?
If none of this is correct, what would the correct way to proceed be? I can't touch the server, thus I am limited to client side.
If you set dataType as JSONP, you can only get data as JSON.
So if the url (https://mydomain/page.php) doesn't response a JSON object, you will get parsing error, because it tries to parse it and fails.
JSONP is for JSON format data only! So if you receive a parseerror this means that the output of your PHP might not be well-formed JSON
And no, it is not easily possible to have XML as response to a JSONP call ..
I'm seeing a weird error in one of my ajax-updated pages.
The request looks like this:
var a = new Ajax(url,{
method: 'get',
onComplete: function( response ){
$('loader').style.display="none";
readData( response );
}
});
a.request();
return;
This works fine on almost any system so far, but on a new server it breaks, with a mootools error "unknown XML entity". The weird part is, if you trace the request with firebug, rather than returning JSON as expected, the response body looks like this:
<script>document.location.href='http://www.mysite.com?myparams=value&etc;</script>
However, if you actually make that request manually by pasting the URL in the script tag (response body) along with the params in a browser, the proper JSON data is returned.
Any ideas why the request would return a script tag instead of the data?
As Dimitar suggested in the comments above, this was an issue in a Joomla site thanks to a URL rewrite tool called sh404SEF. According to the developer, the fix is to set the "301 redirect" parameter to "no" in the advanced configuration options.
So this had nothing to do with my code or the ajax functions, but was rather the SEF rewrite component that was breaking the request.
I've read about this a lot and I just can't figure it out. It has nothing to do with MY code, it has to do with the feed or something because if I swap it with a Twitter feed it returns an Object object which is perfect.
$.getJSON('http://rockbottom.nozzlmedia.com:8000/api/portland/?count=1&callback=?',function(json){
console.log(json)
});
And i get an "invalid label" error. Any ideas?
Also, a side note, I've tried the AJAX method as well:
$.ajax({
url: 'http://rockbottom.nozzlmedia.com:8000/api/portland/',
dataType: 'jsonp',
data: 'count=1',
success: function(msg){
console.log(msg)
}
});
and both give the same exact error, and both work fine with Flickr and Twitter examples, so it must be something to do with the feed, but I dont have access to the feed, but I could ask them to fix something IF it's their issue.
Make sure that the server side can handle the JSONP request properly. See here for example.
Edit: It seems that the server doesn't wrap the returned JSON object with the callback function name. The server should return:
callback( { json here } )
and not
{ json here }
That URL looks like it's expecting you to provide a JSONP callback (from the callback=? bit). That's probably the problem; it's returning Javascript rather than JSON (because that's how JSONP works). See the $.ajax docs for more about using JSONP services.
The returned content has unescaped double-quotes in one of the strings. It's invalid JSON:
..."full_content":"just voted "with Mandy " on...