I need to know the exact difference between:
<form method="POST" action="https://mywebsite/signon.php">
<input name="harv_acc" value="940322903" type="hidden" />
<input name="harv_eml" value="a#b.com" type="hidden" />
<input type="submit" value="SignOn" />
and
var url = "https://mywebsite/signon.php";
$.ajax({
url: url,
type: 'POST',
//dataType: 'html', -- this was something I tried later
//data: "harv_acc=" + accountnumber + "&harv_eml=" + email , this is also what I tried last but below is what I tried first
data: { harv_acc: account, harv_eml: email },
success: function (data) {
closePopup("div_PleaseWait");
alert(data);
//window.location = encodeURI('<%= Url.Action("DownloadDocument", "Documents") %>?DocumentID=' + documentID + '&DownloadType=' + downloadType + '&DownloadPath=' + data);
}
});
When I post the latter I get a 200 but no response. If I submit the first one I get the correct response.
From the comments:
I'm posting to another site
Aha! There's your issue. Browsers block AJAX to external websites for security reasons. Sorry, but you're not going to issue that request via an XHR request.
If the other website wants you to communicate with them, they could expose this part of the site via JSON-P, which works something like this:
My site adds <script src="http://othersite.com/signon.js?username=foo&password=bar&callback=myCallback"> to the source code (yeah, it's messy to use GET for this, but JSON-P can't work any other way), and creates a function named myCallback to handle the response data.
The other site signs in, then returns something like myCallback({success: false, errorMessage: "Incorrect password, try again!"})
That script is run on my site, calls myCallback, and everything is happy.
JSON-P is a powerful protocol, but only works if the remote site agrees to it. Still, if they do, jQuery has a nice shortcut for it: just set dataType: "jsonp" and it will handle the whole callback thing for you.
But if you're not closely involved with this website, that's unlikely to happen, and you'll probably just be stuck with having to give up on this kind of cross-site interaction. Sorry, but this kind of cross-domain policy is critical to online security. (I don't want other sites issuing requests to bankofamerica.com on my behalf, kthx.)
The first parameter passed to your complete function will be a jqXHR object, which is a wrapper around the browser's XMLHttpRequest object. A more convenient way to handle the response is to use the done method:
var url = "https://mywebsite/signon.php";
$.ajax({
url: url,
type: 'POST',
dataType: 'html',
data: "harv_acc=" + accountnumber + "&harv_eml=" + email
}).done(function(data) {
closePopup("div_PleaseWait");
alert(data);
});
Cross domain ajax requests are not supported by browser. But there is another way to get around this.
You can use JSONP for cross-domain requests. It is easy to use and allows you to request anything (as long as it is in JSON format) from any server/script that supports the callback. The good thing about JSONP is that it works in older browsers too.
The only serious limitation seems to be that it always uses the HTTP GET method
Can you please check with this too.
Try sending ther data as a key:value object. This is an example from the jQuery docs
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Update: as user Matchu pointed out, this is not the problem, as the data will be converted into a query string anyway, as stated in the jQuery docs:
"The data option can contain either a query string of the form key1=value1&key2=value2, or a map of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. "
So yeah, some rash answering on my part there. At least I learned something! ;)
when using POST method you should ,in your case, Post your data as JSON
var url = "https://mywebsite/signon.php";
$.ajax({
url: url,
type: 'POST',
dataType: 'html',
data: {
harv_acc : accountnumber,
harv_eml : email
},
success: function (data) {
closePopup("div_PleaseWait");
alert(data);
//window.location = encodeURI('<%= Url.Action("DownloadDocument", "Documents") %>?DocumentID=' + documentID + '&DownloadType=' + downloadType + '&DownloadPath=' + data);
}
});
NOTE : i used dataType : JSON
Related
I have a draggable div-container and whenever I drop it, its location is to be send to a local php script.
$(function() {
$( "#fenster" ).draggable({
stack: "#fenster", stop: function(event, ui){
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
$.ajax({
type: "POST",
contentType: "application/json",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
}
});
});
In the php file (index.php) I check whether $_POST['x'] is set. Unfortunately, no matter what I do, the condition is never met.
if((isset($_POST['x']))){
$_SESSION['xLoc'] = $_POST['x'];
echo "Test";
}
Upon dropping the window, I get a response (alert of the msg shows output) and according to FireBug, the request DOES contain x.
The PHP superglobal $_POST, is only available when you use these content types
application/x-www-form-urlencoded (standard content type for simple form-posts) or
multipart/form-data-encoded (mostly used for file uploads)
You are using application/json which means you need to get the stream with...
$rawData = file_get_contents("php://input");
$d = json_decode($rawData);
if((isset($d['x']))){
$_SESSION['xLoc'] = $d['x'];
echo "Test";
}
Or if you dont actually need to be submitting JSON, just remove the contentType from your jquery, and you should be able to retrieve the $_POST on the php side, using the code you already had.
$.ajax({
type: "POST",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
Or change your php to the code above, to retrieve the raw stream, if you need to be sending json data to the server
I had two redirects that killed the POST request. After making adjustments to the if-conditions, this no longer happens and the data sent by the Ajax request is now also being successfully processed by PHP.
Thank you all that took the time to help me, it's greatly appreciated.
I have the following ajax request:
var value = $.ajax({
type: "POST",
url: "url.php",
data: { $(someform).serialize(), something: test_number },
cache: false,
async: true
}).success(function(data){
alert("success!");
}).error(function() {
console.log("FAILED");
});
But it is logging FAILED although the url is right. What happens is that the page refreshes the page and the php query isn't done. I guess there are no errors within the url... any idea on why this happens?
You are kind of mixing methods to send your POST data. You can't serialize a query strong and then also append additional data to it using javascript object construct. You will likely need to manually append the last data element to the query string like this:
data: $(someform).serialize() + '&something=' + encodeURIComponent(test_number),
Of course there could still be a problem on the server-side script which is causing a non-200 HTTP response code (and triggering error handler). You just need to fix this first, and if you still have a problem, debug the server-side issue.
I'm building an AJAX form and I'm trying to send 3 fields by JSON.
Client-side, the form is serialised and entered into JSON format:
$('#form-signin').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel2';
$.ajax({
type: "POST",
url: url,
data: $.base64.encode($('#form-signin').serialize()),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
});
}
});
event.preventDefault();
});
Server side, my router splits the URL request up, sees that the first part contains 'ajax' then proceeds to specially pass the routing request to an AJAX handler.
my problem is that even inside the router, checking $_REQUEST, which is what is used to get the information about the post, the post data is not there. The same goes with $_POST.
Even the first page where the request hits (index.php), $_REQUEST does not have the data.
What am I doing wrong?
Server Side,
The request is sent to an index.php which includes the Autoloader and init script.
The init script initialises the database connection, sets the error, exception and session handling, then passes the request onto the router.
The router, in its construction method: sets the URL as an array (exploded $_SERVER['REQUEST_URI']), and then sets the relevant controller, method and additional parameters.
In this case, as we are doing an ajax request, special processing happens before we dispatch the request.
The method parameters are set to:
$requestParams = $_REQUEST;
unset($requestParams['url']);
This request parameter(s) along with additional information (url, controller, method and database object) are passed for dispatch.
In all cases, we are primarily dispatching using this method:
$dispatchedController = new $this->controller($this->database);
$method = $this->method;
return $dispatchedController->$method($this->params);
If I remember right from using a plugin a long time ago, the method $.base64.encode() returns a single string so what you are probably sending to the server is something like a single parameter with no value.
I believe you should be doing something like
data: "foo=" + $.base64.encode($('#form-signin').serialize()),
You are not sending json to the server just a base64 encoded string. Also you are expecting key/pair values. To send key/pair values just pass the serialized form data to the $.ajax function.
$('#form-signin').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel2';
$.ajax({
type: "POST",
url: url,
data: $('#form-signin').serialize(),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
});
}
});
event.preventDefault();
});
The code should work (assuming your HTML is not the problem here, e.g., '#form-signin' is the right selector for the right form).
You mentioned you are not able to get the data on the server side. However, are you absolutely sure you are even sending the data you need from the client? For example, have you analyzed the request using a tool such as Firebug?
I'm running into a problem with JQuery Mobile (new to me) and the AJAX-call. I'm using the following code:
$.ajax({
type: "POST",
url: "http://**correct url**/post/todoitem",
beforeSend: addHeaders,
dataType: "json",
contentType: "application/json",
data: { "todoitem":"test" }, // this is just as a test
success: function(result) {
alert("Success: " + JSON.stringify(result));
},
error: function() {
alert("Error: " + JSON.stringify(arguments));
}
});
While executing this, it calls a PHP script where I need the data from the todoitem, so in this case the string "text" (in the end, multiple variables are to be send, but for now I'm just using one parameter for simplicity).
My PHP code looks like this (also just for testing purposes):
echo json_encode($_POST));
The result is: nothing, null. The $_POST seems to be empty. I've searched and tried many things, but most answers (even here on stackoverflow) are about forms and people say I need to serialize the contents of the form. However, I'm not using a form at all.
I also tried
data: JSON.stringify({ "todoitem" : "test" })
as some suggested but this did not work either.
I do know that the data is being transfered because of this little PHP hack I tried:
echo file_get_contents('php://input');
That exactly shows the data: todoitem = test. So where does this all go wrong? I'm working on this for days now! Thnx in advance
The problem is with this part of your code:
contentType: "application/json",`
Removing that line should make the sent Content-Type header default to application/x-www-form-urlencoded and PHP will decode the request into $_POST.
I'm doing an AJAX call using jQuery's JSON feature.
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
pop_word_list(json, paging_value);
}
});
}
As you can see, I'm sending the response to another JavaScript function, but what I'd like to do is send the response to PHP. Is this possible, say to directly convert the response into a PHP array (not using JavaScript) and then use PHP to handle the array, etc?
Thanks in advance.
You could perform another Ajax call to the php script in the success function, passing along the JSON data as a POST param.
do this?
js (ajax) -> php (array conver to ajax) -> js (ajax) -> php ?
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
json["paging_value"] = paging_value;
$.post("x.php", json);
}
});
}
The whole idea doesn't stick together at all... but:
If there is a reason to do that - then You want to do the $.post('phpfile.php',json,function(){},'text or whatever type You want in return');
and the whole json object goes to PHP's $_POST[] as suggested above, but I can see NO case where it should be done that way.
If You get that json from some code You can't change and want to use data in php do:
use cURL to get the data from another thing
use json_decode($data,true) to get assoc table of the whole thing
If You don't know what You're doing :)
just pass the object to another function without useless sending stuff back and forth. You might want to do empty AJAX call to trigger the php file, nothing more.