PHP jQuery and Ajax sending / receiving variables & data - php

So within my jQuery I am making an AJAX call to set a cookie and use the same data to echo the result:
jQuery
jQuery.ajax({
url: 'script.php',
data: {status: 'enabled'}
});
PHP
if(!empty($_GET['status'])) {
$value = $_GET['status'];
echo $value;
setcookie("status", $value, time()+3600, "/");
}
The confusing part is that the cookie is being set, however the value is not being echoed, i also tried to print it but doesnt work either.
Ultimately what I wish to do is use the data passed through the ajax call and assign it to a php variable to be used for some conditionals.
Am I missing something? I am learning how to program.
update
Request URL:http://localhost/wp-content/plugins/lu-ban/inc/lu_ban.php?status=enabled
Request Method:GET
Status Code:200 OK

You need to see it in script then you need a success callback Here
jQuery.ajax({
url: 'script.php',
data: {status: 'enabled'},
success: function(returnedData){
alert(returnedData)
}
});

Then you'll have to use your Web Developer's tools in your browser to trace the HTTP requests and examine the headers (for the data sent TO the script) and the Responses (for the data being returned).
From the jQuery $.ajax documentation
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of
jQuery 1.5 is a superset of the browser's native XMLHttpRequest
object. For example, it contains responseText and responseXML
properties, as well as a getResponseHeader() method.

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
}
});

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?

Passing javascript variable to PHP function

I have this javascript code
<Script>
function getGroupId(){
var group=document.getElementById("selectedOptions").value;
var groupFirstLetter=group.substring(2);
}
</Script>
I need to pass the groupFirstLetter to a PHP function which will count how many users in this group and return the value to the javascript function.
Any ideas please?
Thanks,
You can use jQuery for that to post an AJAX request. See this example taken out of jQuery documentation:
$.ajax({
type: "POST",
url: "some.php",
data: {groupFirstLetter:groupFirstLetter},
complete: function(data){
//data contains the response from the php file.
//u can pass it here to the javascript function
}
});
The variable will be available in your PHP code as $_POST['groupFirstLetter'].
You can manipulate it as you wish then echo a response to the browser again and it will be available in the data variable.
references:
jQuery AJAX
As javascript runs on user's browser you have to do an http request to a php page. POST or GET can be used to send parameters.
To make a http call with javascript refer to this: HTTP GET request in JavaScript?
Use jQuery (jquery.com).
Dynamically load the php-file sending the variable using ajax like so:
$.post("file.php", {variable_name: value}, function(returned_data){
console.log(returned_data); //or do whatever you like with the variable
});
and your php-file will access the variable as:
$_POST['variable_name'];

JSON response is null, but the URL is echoing correctly

I have a form being AJAX'd in by jQuery on a page with multiple forms. I'm performing the following function, which is a wrapper for the $.ajax function:
function do_json_get(uri){
var ret = '';
var url = AJAX_URL + uri;
$.ajax({
type: 'GET',
url: url,
async: false,
success: function(data) {
ret = data.html;
},
dataType: 'json'
});
return ret;
}
When I go to the AJAX server directly (which is rendering the form in PHP), I get the raw JSON response - so I know the server is outputting to the browser, and the AJAX server is doing other things like setting the proper cookies, so I know that the connection is good (I get a 200 response code). Yet the data object is coming back null.
Here's a guess. If you're serving the page from the file system, Firefox (and I think Chrome) will see it as originating from a different domain. You'll get the 200 response, but no data.
Try Safari, or maybe give jsonp a shot in place of json.
EDIT:
Since you're getting the data from a different domain, it won't work. I think it is not allowed by the XMLHTTPRequest.
Oh boy. This question again.
AJAX: Asynchronous JavaScript And XML*. Asynchronous. Asynchronous. Asynchronous.
Your function, do_json_get() returns ret before the success handler function in the AJAX call executes. The order of operation is not proceeding, here, from top to bottom. In other words, you just can't do it that way.
Because of its asynchronous nature, AJAX operates on callbacks, not return values. You need to change your paradigm. The success handler function needs to do whatever is required with data.html itself, or pass it off to another function.
* Yes, I know the XML part of the original acronym is largely vestigial these days

Is this a jQuery bug, or am I missing something?

I am using jquery-1.3.2 in an AJAX web application. I use the jQuery ajax $.post() method to submit requests to the server.
On the server I am using php to build an array and then json_encode the answer. Then on the client I use the callback function of the AJAX post method to process the response.
All works well until I use the $.post() method to send variables to the server. If I send variables to the server, the response I get back is [object Object] and therefore I am unable to parse it. I have a work around at the moment that when posting variables I request a HTML response and then I parse that.
So the code involved taken from my site is:
The Jax call:
$.post("inc/sendfeedback.php", {NAME: name,TYPE: type,EMAIL: email,COMMENT: comment}, function(data) {PostData(data);}, "json");
So the PostData code looks like this:
function ProcessData(data)
{
//alert(data);
var jo = eval("(" + data + ")");
if(jo.result == "true")
{
if(jo.data != "" && jo.element != "")
{
$(jo.element).html(jo.data);
}
}
SMessage(jo.error);
}
If I uncomment the above code the alert with have in it [object Object].
if I remove the Post variables from the call it works fine.
The server code look like this:
$arr = array ("result" => $result,"data" => $data,"error" => $error,"element" => $element);
echo(json_encode($arr));
Is this a bug with the jQuery library, I tried it with the 1.2 version however its was still present there? I also search the jQuery site and can not find anyone having this issue.
So I assume I am missing something. But what?
$.ajax({
url: "script.php",
global: false,
type: "POST",
data: {NAME: name,TYPE: type,EMAIL: email,COMMENT: comment},
dataType: "json",
contentType: "application/json",
success: function(data){
alert(data.result);
}
}
No need to eval, jQuery evals/parses it before calling the success callback.
eval = pure evil
http://docs.jquery.com/Ajax/jQuery.ajax#options
Because you are using an associative PHP array, json_encode will return a string representation of a Javascript Object and not a Javascript Array. However, you should still be able to process it in a similar fashion to an array:
for (var key in data)
{
var item = data[key];
}
I would strongly recommend you download Firefox+Firebug addon and use the console API for debugging/dumping what is being returned by the server.
I have since registered and now can't post comments into this thread without reputation and can not see any easy method to claim this question as mine.
Deviant, your suggestion of using the $.ajax() method worked. Reason it didnt work for me the first time was I submitted the post data as a JSON object when the server code was expecting POST data.
So I fixed my javascript to call the server script correctly and everything works exactly as it should.
So the conclusion is, the $.post() method has a bug in it. I have not tracked it down but line 3633 is were the post method makes the call. I started digging however have not yet found the issue.
I qualify this by the fact the $.ajax() to the same server script and the same javascript processes the response and it all works, use the $.post method and my script fails with the return even through the return object appears to be a valid JSON object.
Thanks for the help guys. Now to go and remove all my $.post calls for $.ajax calls.
The result of all this can be seen at www.pygames.net
Cheers
Shane
a.k.a FrogSkin

Categories