Getting ajax post data on success - php

I have the following ajax call. What I would like to do is set the variable "lan_setting" during the ajax requests, and be able to use that variable on success.
In reality I want to set that variable to be post data, which will vary depending on the form input, but as of now I can't even get it working with just this basic example. It just returns "undefined".
_jqXHR = $.ajax({
url: url,
data: {lan_setting: 'en'},
scriptCharset: "UTF-8",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(lan_setting, data, textStatus, jqXHR) {
alert(data.lan_setting);
}
});
How do I can I use post variable sent via ajax on success?
thanks!

Well, if you're posting, you should use the jquery post function here
$.post(
url,
{lan_setting:"en"},
function( data, status, jqXhr ){
alert(data.lan_setting);
},
"json"
);
then php:
<?php
// do stuff
$response = new stdClass;
$response->lan_setting = $_POST["lan_setting"];
print json_encode($response);
?>

Well, you're declaring the success function wrong (from the jQuery .ajax() documentation):
success(data, textStatus, jqXHR)
In other words, the success function gets data, textStatus, jqXHR and nothing else. You can't just will it to take your POST variable -- it only gets what it gets. You also can't pass a POST variable in by just specifying it in the config object: you have to pass it in via the data property. Lastly, .ajax() defaults to a GET request, so you have to explicitly specify that you want to use a POST request.
I'm a little confused about what you want to do; if you know the value of lan_setting before making the AJAX call, why do you need to have it passed into the success function? Just use it:
var lan_setting = 'en';
_jqXHR = $.ajax({
url: url,
type: "POST",
data: {
lan_setting: lan_setting
},
scriptCharset: "UTF-8",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(lan_setting, data, textStatus, jqXHR) {
alert(lan_setting);
}
});
If, on the other hand, you want to pass the lan_setting value in, have it modified by the server, and passed back, you will have to somehow encode it in the response, probably with JSON.

Well the success() method in jQuery.ajax, accepts 3 parameters.. The first being the response from the request.
success(data, textStatus, jqXHR)Function, Array A function to be
called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
Also, when using $.ajax, there are a certain number of objects you can pass. See http://api.jquery.com/jQuery.ajax/
As far as your post, you are able to do...
$.post("service.php", {lan_setting: "en"}, function(response) { alert(response); }
which will post the second parameter, {lan_setting: "en"} to that php service, and echo it's response.

Related

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
}

jQuery/ajax is not updating divs on the page

I'm trying to update a div with id=OCRID, which is a div on my page that contains some data. I used the code at the following URL first, however we switched to a jQuery approach. <-Ugly ajax->. Switched to this. Using alert, I saw that the message being returned on success was the correct message, but the document.getElementById(OCRID).innerHTML=msg doesn't change the value. I have some other javascript that does some similar things but not with data from the server. Please help?
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+document.getElementById(OCRID).value,
success: function(msg, OCRID){
document.getElementById(OCRID).innerHTML=msg;
}
});
First of all you mentioned OCRID is an id of div and you've used
document.getElementById(OCRID).value // a div doesn't have a value attribute
which returns value of an HTML element but a div doesn't contain any value attribute and in the success callback you have used
success: function(msg, OCRID){
document.getElementById(OCRID).innerHTML=msg; // innerHTML is right for a div
}
From the jQuery Documentation:
success(data, textStatus, jqXHR)
A function to be called if the
request succeeds. The function gets passed three arguments: The data
returned from the server, formatted according to the dataType
parameter; a string describing the status; and the jqXHR (in jQuery
1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in
turn. This is an Ajax Event.
in this case you shouldn't use OCRID as the second parameter because jQuery uses 3 parameters in the success callback and these are basically data, textStatus, jqXHR and in this case data is your msg, OCRID in this case become textStatus and it is the response's status message and the third parameter is the xhr object. So it should be
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+$('#'+OCRID).html(), // or text()
success: function(msg){
$('#'+OCRID).html(msg); // or text()
}
});
Also remember that you OCRID looks like a variable and this should be available in the scope of your ajax call and if this is not a variable then it should be $('#OCRID') in both places as given below
$('#OCRID').html();
and in the success callback
$('#OCRID').html(msg);
Replace this line:
document.getElementById(OCRID).innerHTML=msg;
With:
document.getElementById("OCRID").innerHTML=msg; // notice the quotes
If your success callback has OCRID as a parameter(which is incorrect) it will be used instead of the one you used in your data parameter, so remove it.
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+document.getElementById(OCRID).innerHTML,
success: function(msg){
document.getElementById(OCRID).innerHTML=msg;
}
});
Why not use the jQuery version for the interface to the element? To me it looks like OCRID is a variable, right?
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus=" + $('#' + OCRID).text(),
success: function(msg, OCRID){
$('#' + OCRID).html(msg);
}
});

JSON data not being sent in POST?

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?

ajax request is being sent to PHP to do some maintaining, but errors because it doesnt like php tag?

My AJAX request to pings the server, and the URL but returns an error because it doesnt like the '<' as the open tag for the php script.
AJAX script.
$.ajax({
url: "data.php",
type: "POST",
data: JSON.stringify({"data":transaction}),
dataType: "json",
success: function(data, textStatus, jqXHR){
alert("success");
currentProcesses -= 1;
$("<span>").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
},
error: function(jqXHR, textStatus, errorThrown){
alert("error with ajax call "+textStatus+" "+errorThrown);
}
});
php script
<?php
$win = $_POST['data'];
?>
Am I using the wrong flag settings for the AJAX call?
The body of your POST request is encoded as application/json instead of application/x-www-form-urlencoded.
You aren't doing anything to make the request say that the data is encoded in JSON and you aren't doing anything in PHP to try to parse JSON.
As a result, PHP fails to populate $_POST, because the data is in the wrong format.
The solution is: Don't send JSON. Just give the data property an object as its value, and jQuery will serialise it to application/x-www-form-urlencoded data for you.
data: { "data": transaction },
(Assuming that transaction is not a complex data type (like an array or object).
Additionally, the body variable is undefined. You should either use a string (to make it a selector: "body") or pass the body element directly: document.body.
Is it choking on what it's receiveing? Try this...put an id attribute on your span tag, and reference that.
In the page:
<span id="someName">...</span>
In your ajax call:
$("#someName").html(...
Try making the span more unique using class or id like
<span id="output"></span>
and try this.
$("#output").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
}

Ajax request multiple data info

I'm going crazy over this script, i'm trying to het this working by when some one click on a button then with ajax fetch data from another URL then fill form inputs with the fetched data can any one help please
my code look like this:
$(document).ready(function()
{
$("#getmetaData").click(function(){
var element = $(this);
var url = $("#url").val();
var dataString = 'url='+ url ;
//alert(dataString);
if(url=='http://')
{
alert("Please Enter URL to fetch Meta Data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loader.gif" >');
$.ajax({
type: "POST",
url: "fetch-metadata.php",
data: dataString,
cache: false,
success: function(data){
$("#title").val(data);
$("#description").val(data);
$("#keywords").val(data);
$("#flash").hide();
}
});
}
return false;});});
If you see no error, which I am guessing is the case, it means your request is failing. Since you have no error function, when your request fails, your jQuery code will do nothing.
Add something like this to your $.ajax object argument:
error: function(jqXHR, textStatus, errorThrown) {
// now you can set a breakpoint or log textstatus/errorThrown
},
As per HackedByChinese's answer I would add an error callback function.
Also, in your success callback function you are simply using the 'data' variable without doing anything with it. Depending on the format of the response from 'fetch-metadata.php' I think you'll need to do something first. It's either XML in which case you'll need to parse it. If its json you can use object dot notation to reference it's properties.
Lastly, I'd use something like Firebug to look at the request and response for this Ajax request to make sure it's being processed and not returning a 404 or 500. Assuming its returning a valid response, using Firebug you can look at the response to see the raw data that is being returned to your js.
Hope this helps

Categories