I have a form that takes three steps to fill it.
At each of these steps you fill some info, click "Next" and then see either errors you have to fix in order to get to the next step or if there are no errors it takes you to the next step (change "display" to "block" in CSS).
At first step it uses $.ajax() to call file lib/ajax.php which returns some results in JSON that matter a lot to filling the rest of the form.
The thing is this works locally on my http://my.dev address, but live on https://something.example.com it does not.
Where should I first try looking to go about it? What are the most common workarounds on this?
Both lib/ajax.php and the index.php file (that has the jQuery call) are on the same domain (https://something.example.com) so we are not talking about cross-domain calls.
Here's some of the code.
$.ajax({
type: 'GET',
url: 'lib/ajax.php',
async: false,
data: {id: id},
dataType: 'json', // what type of data do we expect back from the server
}).done(function(data){
// do stuff with data
});
and the lib/ajax.php
//stuff with db and retrieving row by id
header('Content-type: application/json');
echo json_encode($result);
That's pretty much it. It doesn't work when I place it on live HTTPS server.
In https i think you must change the dataType: 'json' to dataType: 'jsonp'
1.Check the whether the url given in the function $.ajax() is the right path or not.
2.Here you specified data type as "JSON",so response must be "JSON".
3.If the response is not in correct JSON format,it makes issue.
contentType: "application/json; charset=utf-8"
Add the above code in $.ajax() function
Please check the above specified points
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 hope you can help me with this issue:
My sistem runs over Zend Framework, I have installed jQuery in it's latest version. I have an input that receives a file and it makes an Ajax call when changes, and I want that call made in the background, without expecting any response (because that script will send an email when finished). My ajax call is like this:
var formData = new FormData();
formData.append('file', $(this).get(0).files[0]);
$.ajax({
url: 'uploadaddresses.php',
type: 'POST',
data: formData,
dataType: 'json',
async:true,
processData: false,
contentType: false,
beforeSend: function(){
bootbox.alert("You've made your petition correctly. When finished, an email will be sent to you.")
},
error: function(err) {}
});
return false;
Although, the call waits for a response (even FireBug shows me that uploadaddresses.php is still executing...). What i'm doing wrong? How should I do it best? I want to avoid using daemons and system calls, because system restrictions...
Thank you very much in advance :)
If you're wanting uploadaddresses.php to return an HTTP response immediately but continue processing, take a look at pcntl_fork in PHP.
Here's the main doc page: http://php.net/manual/en/function.pcntl-fork.php
Here's a good example that you might want to follow: http://php.net/manual/en/function.pcntl-fork.php#94338
Create a success method for the ajax call and have something like this:
console.log("Done");
This way you know if is complete and successful but only if you are looking at the dev tools. Unless you specify output it should not continue to run after the call has been made. Maybe you have an error in your PHP code?
EDIT: If you can't get this resolved you may want to post your PHP page as well.
When I first load a page I make an ajax call to bring some data for the client-side. The call is made to a different domain and the answer comes as JSONP. The call looks similar to:
$.ajax({
type: "GET",
url: url + "?callback=?",
dataType: "jsonp",
contentType: "application/javascript;charset=UTF-8",
async: true,
success: successCallback,
error: errorCallback,
cache: true,
jsonpCallback: jsonCB
});
'application/javascript' would be the possible culprit here as I did my research on the subject but this is present in a previous version of the code which never had this problem.
On all browsers except IE I receive the following error (sometimes, usually the first time and then the problem dissappears) :
script5007 object not found - line 1, char 1
The JSONP received looks like that:
func({"result":"abc"})
The param of the func is a valid JSON as I checked this using jslint.
Any idea will be highly appreciated! Thank you!
You're missing the object brackets { } inside your $.ajax function. Modify it like so:
$.ajax({
url:'',
contentType: 'application/javascript;charset=UTF-8',
crossDomain:true
......
});
The jQuery $.ajax method either takes a url parameter and an optional parameter of additional options specified as an object, or an object parameter including the url.
I'm trying to do the following thing with AJAX:
Visitor click button/ AJAX show spinning/loading image to visitor.
AJAX Visit URL 1 http://www.mywebsite.com/url1.php and it'll return a random code, for example 1357.
Then, I want it to visit URL 2 http://www.mywebsite.com/url2.php?code=1357&action=ask (1357 is a variable from url1). URL 2 will verify the request return a final code. I want to show the code to the visitor after removing the spinning/loading image.
How do I do that?
Thanks in advance.
Try this.
$.get("http://www.mywebsite.com/url1.php").done(function(data){
$.get(
"http://www.mywebsite.com/url2.php",
{code: data, action: "ask"}
).done(function(next){
$("#result").html(next);
});
});
Try this:
$.ajax({
url: 'http://www.mywebsite.com/url1.php',
dataType: 'html',
type: 'GET',
success: function (data) {
// Show the random code, like 1357
$(".result").html(data);
$.ajax({
url: 'page2.php?rand_n=' + data, // Change rand_n to what you want
dataType: 'html',
type: 'GET',
success: function (data2) {
// Hide the spinning/loading image
$("#loading_img").hide();
// Show final code
$(".result").html(data2);
}
});
}
});
Here is my idea for you:
Method one:
1.ajax request http://www.mywebsite.com/url1.php
2.in url1.php generate a random code like :1357
3.use [curl][1] request http://www.mywebsite.com/url2.php?code=1357&action=ask
4.echo result from curl2 to frontend
above only need one time ajax,the second request use curl quietly..
Method two:
you also could use header to redirect the url:
go on with step 2:
step 3:could use header('Location: http://www.mywebsite.com/url2.php?code=1357&action=ask');
step 4:url2.php should echo the result.
this tow method only have one ajax request and won't affect you frontend ,i recommand you use method two,method one is better used in different domain..
I'm not sure if this is crossdomain issue or not. I'm trying to use $.ajax to load file. But some file I get readyState=4 and some file I get readyState=1
This is the path where I run my jasmine test
file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html
And in the code I used jQuery.pyte to require relevant file. But it's stuck at readyState:1 when the code comes to $.ajax
if I do something like this, it returns readyState=4 correctly and print out the content inside SpecRunner.html
$.ajax({url: 'file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html', async: false}).responseText
but if I do something like this, I only get readyState=1 and nothing is returned.
$.ajax({url: 'file:///home/myname/development/path1/path2/src/main/webapp/static/js/core/application/FileThatIWant.js', async: false}).responseText
you should avoid file:// URLs in general, because browsers do not allow them in many different places. Try XAMPP it's a simple to use local webserver, you will definitively need one.
Yes, this is a cross-domain issue. You can solve this problem by forcing jQuery to use crossdomain AJAX (JSONP).
$.ajax({
url: "yoururl",
cache: false,
crossDomain: true,
data: {}, //put your GET parameters here or directly into the url
dataType: "jsonp",
processData: true,
success: function(data, textStatus, jqXHR){
//This will be executed if it worked
},
error: function(data, textStatus, jqXHR){
//This will be executed if it failed
},
timeout: 4000, //You can put any value here
traditional: true,
type: "GET"
});
jQuery will automatically add a callback parameter containing a random string (&callback=XXXXXX).
The target URL needs to output the following:
XXXXX(your_output_encoded_in_JSON);
where XXXXX is the random string. The PHP code to do so is:
echo $_GET["callback"]."(".json_encode($myoutput).");";
Make sure that the PHP (or whatever language you're using) page ONLY outputs that!
If, instead, the page you are querying is not built dynamically, such as an HTML page, you need to add the following options to the $.ajax options object:
jsonp: false,
jsonpCallback: "mycallback",
mimeType: "text/javascript",
Your .html file will contain something like this:
mycallback("<html><head></head><body>TEST PAGE. This is a double quote: \" and I didn't forget to escape it!</body></html>");
This technique is very handy to bypass the strict crossdomain restrictions hardcoded in browsers, but it only supports GET parameters. XMLHTTPRequest v2 supports cross-domain requests, but we won't be able to assume that all users have a XHRv2-compatible browser before at least 2016.
http://caniuse.com/xhr2