JSON data not being sent in POST? - php

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?

Related

Controller behaviour with ajax request

I am trying to get a hold on sending data to MySql via ajax and have been watching online tutorials. In the examples, the controller method always seems to end with an echo statement which is returned to the js script. Under other circumstances, if I put an echo statement in a controller method it would be output to the view so why does this not happen after an ajax request?
ajax works with js, and the response by ajax request can only be handle through js.
Reason => after generating ajax response on server, it bounce back to client/browser, where server side language doesn't work, so you need to manage your code/logic through client side language JS in your ajax success block.
$.ajax({
url: 'content/get.php',
type: 'post', // performing a POST request
data : {
data1 : 'value' // will be accessible in $_POST['data1']
},
dataType: 'json',
success: function(data)
{
// success block
}
});

How can make sure code after my ajax request only runs if the request was a success?

I have a link, delete, that removes an item from an array, and then removes a row from a table on my html page.
It runs the ajax request first to amend the array, then removes the row. If for some reason the ajax request was to fail then the html table row would still be deleted I think.
Is there a way to make sure subsequent code afer the ajax request only runs if it is successful? I tried moving it into the success function but then it didn't run at all..
This is how I have it set up at the moment...
$(document).ready(function () { //delete
$(document).on("click", "a[class='del']", function () {
var ID = $(this).attr("id"); //<----- get the ID of the column
$.ajax({
//contentType: "text",
url: 'proDel.php', //the url you are sending datas to which will again send the result
type: 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data: 'val1=' + ID, //Data you are sending
success: function (data) {
// do nothing, array was amended in php file
}
})
//Code here that deletes the table row(runs whether the array was changed or not!!
})
})
The problem might be that you are not returning valid JSON.
You were correct in thinking that you should move the code that deletes the table row into the success callback. You say you tried that, but the success callback was not executed.
Since you specify dataType: 'json', jQuery will attempt to parse the response body into a JavaScript object (or array or null). If the response body cannot be parsed (because it is not valid JSON), jQuery will call the error callback, rather than the success callback.
An empty response body is not valid JSON. You must at least return "null". Or if you do not plan on returning any data, just change to dataType: 'text'.
Move the code that deletes row to success callback.
$.ajax({
//contentType: "text",
url : 'proDel.php', //the url you are sending datas to which will again send the result
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// Code here that deletes the table row
}
});
Try you ajax with success parameter as well as an error to see if there is a problem, hope this helps..
$(document).ready(function (){
$(document).on("click", "a[class='del']", function(){
var elem = $(this); //to make $(this) accessible in you success callback
var ID= elem.attr("id"); // get ID of the column
$.ajax({
url : 'proDel.php', //the url you are sending datas to
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// success, Code here that deletes the table row , do something with 'elem'
},
error: function(x,e) {
//log error if any
console.log("failed with: "+x.status+", e="+e+", response="+x.responseText);
}
});
});
});
Since jQuery 1.5 you may use chainable methods of object returning by jQuery.ajax(). In your case (ensure executing code on ajax request completion) you have to use deferred.always() method. Somehow like this:
$.ajax({
...
})
.always({
//Code here that deletes the table row
})
In earlier jQuery versions you have to use complete option (handler) in jQuery.ajax() for your purpose.
First thing is that when looking at the ajax request success does not mean that the request returned a correct/true value. That just means that there was a response from the other end.
That tripped me up during my first couple times working with and debugging ajax calls.
I don't know if that's part of what is not working for you here, but something to consider.
Secondly, and to answer your real question, you'll have to put a function call in the success branch, else it might never get called, or be called at a non-deterministic time (the whole nature of an asynchronous call).
var a = function(){
$.ajax({
success : function (){
// code here fires if there is a response to your ajax request
// you should put in an function callback here to check the response for
// your success conditions.
// if your conditions are met, make the changes that you need to
b();
}
failure: function() {
// code here fires if the ajax request receives no response
}
})
// any code here will fire immediately after the ajax call is fired.
// it will not wait for the ajax response.
}
var b = function(){
// stuff you want to do according to the ajax response parameters
}

Get - Request , to display results in Alert()

I would like to create an app that will send out a get request, then take the response and display it on the page,
this is part of my learning process, ultimately i would like to have the response be parsed and turned into
elements etc. but for now i am having trouble accessing the information within the response.
How can i alert() any of the results in the response?
the results of the script below ranged from undefined, to [object ojbect]
<script type="text/javascript">
var bbz;
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "MyDomain - its defined and on the web",
success: function(response) {
bbz = response;
alert(bbz.length);
alert(bbz);
alert(bbz[0]);
}
});
</script>
It looks to me like you are expecting a JSON response...
I am assuming this because of the way you are accessing properties of the response object -
bbz = response;
alert(bbz.length);
You'll want to set your dataType to "json".
If you set the dataType property to html, you should be able to simply return HTML.
You set dataType: "jsonp" which attempts to parse a jsonp object out of the data that is to be returned. However, what you really want is the markup that is in the file you are requesting data from. In order to do this, you must state the correct return type, so that the AJAX knows what data to give you, i.e. you tell the AJAX how to parse the data.

PHP: Multiple ajax request

I want a code for multiple ajax request. What happens actually is my first ajax request give me the response and in that responce function i m calling another function which having another website url. I want to send data to this new website using multiple ajax request.
Please help me out...
Thanks,
Prafulla
use global variables and manipulate your data in each request.
like:
var a;
$.ajax({
url:url_one;
success: function(data){ a =data; }
});
$.ajax({
url:url_two;
data: a //sends the data from the 1st request
success: function(data){
//do something with the data from the 2nd url
}
});
You can encapsulate your ajax call in function or event handlers as you need.
You can also manuipulate the data returned in variable a before sending it to the 2nd url.
Seems sloppy to me, but sould work.

jquery not post data in IE

i create one simple form in which i have one combobox when i am selecting any thing i put one function onchange event so its call.
then i send this data in one helper file through jquery
<script type="text/javascript">
$.noConflict();
function Searchwine(obj,str) {
{queryString: ""+str+""}, function(data){
jQuery.post("http://www.site.com/search/helper/autosuggest.php", {queryString: ""+str+""}, function(data){
if(data.length >0) {
jQuery('#windatano').html(data);
}
</script>
i am using this code for post data in autosuggest from through javascript and print replay of jquery in windatano id
--> its working fine in crome and ff and other all browser but in IE its not working
Can any help?
Thanks,
You're using jQuery improperly.
The proper syntax is (for POST)
$.post([URL], {
var: value,
var2: value
}, function(data) {
//callback goes here
}
);
If you want to pass in the querystring as though it's a GET, just append it to the URL after a ?.
E.G.:
"http://www.site.com/search/helper/autosuggest.php?" + str
IE does not support cross domain ajax calls regardless if its getJSON or not. learned that the hard way... i ended up adding a local php file that used curl to get the results and return them to the script, its the only way to make ie work with cross domain requests.
You can't do cross domain ajax requests, if the request url is in another domain, this fail, if the domain is the same, use a relative path:
jQuery.post("/search/helper/autosuggest.php"....
If you need Cross domain ajax request, you have to use jsonp (http://api.jquery.com/jQuery.getJSON/#jsonp)
And if you are using post method, the queryString define a get vars, you need use data option
jQuery.ajax({
url: '/search/helper/autosuggest.php',
type: 'POST',
data: data,
sucess: function (data) {
if (data) jQuery('#windatano').html(data);
}
});
When data can be the object format:
var data = {
a_var = 'value',
other_var: 'other value'
};
Sorry my English

Categories