Getting an ajax post data in php - php

$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
dataType: 'json',
}).done(function(){
console.log('done');
});
Above is my AJAX post, below is my PHP:
var_dump($_POST['test']);
die();
The problem is, this fails to work (I get a NULL value) - why?
I know my call is getting to the PHP code as I can dump any old string:
var_dump('hello');
die();
Where am I going wrong?

Just remove this dataType: 'json'. Your $_POST['test'] is a string value, not a JSON string.

The POST value that you are testing with is not JSON, it's a string.
Remove the
dataType: 'json',
and it should work.

When you set dataType: "json" within the AJAX request it means the expected response should be parsed as json, (not the outgoing POST, as others have said).
Heres is a stripped down copy&paste example, for you to build upon. Hope it helps
<?php
//is it POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// set var
$test = isset($_POST['test']) ? $_POST['test'] : null;
//do some logic - skip that bit ;p
//was the request from AJAX, ok send back json
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//always a good idea
header('Content-Type: application/json');
//json encode, notice the ABC, then look at the jQuery below
die(json_encode(
array('ABC' => 'From Response: '.$test)
));
}
}
?>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function(){
var ajax = $.ajax({
url: "./",
type: "POST",
data: {test : 'test'},
dataType: "json"
});
ajax.done(function(data) {
$("#result").html(data.ABC); /* << See data is an object */
});
ajax.fail(function(xhr, status, error) {
$("#result").html(xhr.responseText);
});
});
</script>
<span id="result"></span>

I'm not totally sure if this is the issue, but .done is deprecated. Additionally, as others mentioned, you are asking for json from the server and not receiving json.
Your code should look like this
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
success: function () {console.log('done');}
});

I would like to recommend you my code. and please do check the following points.
check the location of the url you are giving. If it is in parent directory then you can access it using ../ and the most important thing give the extension of the file. like 'gateway.php'
and write success and failure function. It gives a better insight of what's going on.
$.ajax({
type:'POST',
url:'gateway',
data:{test:'test'},
success: function(data){
if(data)
{
alert(data);
}
},
failure: function(){
alert(failed);
}
}) ;
comment if there are any errors
hope it helps :). If it does then don't forget to green it :P

Or change PHP code
header('Content-Type: application/json');
exit(json_encode(array('data' => 'Bla bla bla')));

Related

This.id passed using ajax to php but returns an undefined index when load by jquery

I've been searching around the Internet and even in Website Development forums but luckily I Haven't found a solution to my problem.
This is the html code
<div id='bottom-right-display'>
<ul id='display-app'>
<li><a href='#' class='btn-test-1' id='123'>Testing1</a></li>
<li><a href='#' class='btn-test-2'>Testing2</a></li>
<li><a href='#' class='btn-test-3'>Testing3</a></li>
</ul>
</div>
This is the jquery code
$(".btn-test-1").click(function(){
//with the use of post
$.post("somefile.php",{id,this.id},function(data){
$("#outputarea").load("somefile.php");
});
//or
//with the use of ajax
$.ajax({
type: "POST",
url: "somefile.php",
data: {id:this.id},
success: function(result){
$("#outputarea").load("somefile.php");
}
})
});
This is the php code
<?php
require_once "connection.php";
$sorter = $_POST["id"];//------>THIS IS THE LINE OF CODE WHERE THE ERROR IS STATING ABOUT!!
$retrieve = $conn->prepare("SELECT * FROM `table1` WHERE `id` != '$sorter'");
$retrieve->execute();
$retrieve->bind_result($groupname);
while($retrieve->fetch()){
echo "<li>".$groupname."</li>";
}
?>
The problem is passing a this.id using $.post or $.ajax to php but returns an error saying Notice: Undefined index: id in C:\xampp\htdocs\somefile.php when using load but when using alert it display the result that I wanted, I even tried using isset but it is empty and no data at all. Please if you know any already answered question or solution for this please comment it T_T.
Check to see if the data is actually in the post request.
i.e.
if(isset($_POST['id'])) $sorter = $_POST['id'];
else die('ERROR: No ID set')
Then I would also check if you can send data to the server via AJAX that way. Otherwise try adding this code to your Javascript.
$(".btn-test-1").click(function(){
var $dta = new FormData();
$dta.append("id",this.id);
$.ajax({
type: "POST",
url: "somefile.php",
data: $dta,
contentType: false,
cache: false,
processData:false,
success: function(result){
$("#outputarea").html(result);
}
})
});
I think the problem is that you first send an ajax request with the id attached, but in the success callback you request somefile.php again. The second time no id is attached.
Instead you should use the result variable to get the "output" of somefile.php from the first request. The second request is not needed.
Like this:
$(".btn-test-1").click(function(){
$.ajax({
type: "POST",
url: "somefile.php",
data: {id:this.id},
success: function(result){
$("#outputarea").html(result);
}
});
});
change jquery to this and try :
$(".btn-test-1").click(function(){
var id_val = $(this).attr('id');
//with the use of ajax
$.ajax({
type: "POST",
url: "somefile.php",
data: {id:id_val },
success: function(result){
$("#outputarea").load("somefile.php");
}
})
});
Your codes seem okay. One thing that I cannot simulate though is your required 'connection.php'. Can you simplify your php code first? I mean just do echo $_POST['id'] just to make sure your preceding code(s) is not affecting your post data.

Can't post a JSON using $.ajax() or can't read it using php

I can't figure out where the problem is.
This is my JS function to post the JSON:
function send(var1, var2) {
var result;
att = window.location;
$.ajax({
'crossDomain': true,
'type': 'POST',
'async': false,
'global': false,
'data': {
"event_id": var1,
"status": var2
},
'url': att + 'post.php',
'dataType': 'json',
success: function (data) {
result = data['result'];
}
});
}
On the server side, this (file: post.php):
<?php
echo $_POST;
?>
only prints "Array".
The problem is that I have to send "data" in that exact format (I can't stringify it and then use the php json_decode() function). I also tried the « file_get_contents("php://input") » way, but still nothing.
I don't understand if the problem is that I can't properly post the json or that I'm not able to read it php-side.
Experiments with the GET method were fine.
Sorry for my bad english and thanks everyone for the attention.
To print array you can make use of print_r() function in php
<?php
print_r(json_encode($_POST)); //use json_encode() since dataType in ajax call is json
?>
To print individual values, you can make use of echo()
<?php
echo(json_encode($_POST['event_id']));
?>
try the following js function :
function send(var1,var2) {
$(document).ready(function(){
$.ajax(
{
url:"post.php",
data:{event_id: var1,status: var2},
success:function (data, textStatus){
alert(data['status']);
},
type:"post",
dataType: 'json'
}
);
});
}
and in server side "post.php" :
echo json_encode($_POST);

jQuery ajax returning nothing when posting multiple data

hello I would like to post multiple data to a php file with jQuery ajax but when I execute the function it's retuning nothing and the php also doesn't get the data
my function looks like this:
function sendForm(){
jQuery.ajax({
url: <?php echo $path; //this the url where the php file is ?>,
type: 'POST',
data: {
addressOne: jQuery('#Form #table .key :input').serialize(),
addressTwo: jQuery('#Form #table_2 .key :input').serialize(),
additionalData: jQuery('#Form #More :input').serialize(),
preloaded: <?php echo serialize($array); ?>,
action: 'sendIt'
},
async: false,
cache: false,
success: function(data){
alert(data); //or console.log(data);
}
});
}
and in the php I do something like this:
<?php
function handleData() {
parse_str($_POST['addressOne'], $arrayOne);
parse_str($_POST['addressTwo'], $arrayTwo);
parse_str($_POST['additionalData'], $arrayThree);
$preloaded = unserialise($_POST['preloaded']);
//than do some stuf here for example print_r all...
}
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'sendIt' : handleData();
break;
//etc...
}
}
?>
I don't know what I'm doing wrong? Is there a better way to post multiple data?
If I use only one data like I'm serialising the whole form and do not post the serialized php array than it works fine, but I would like to use this four separate data.
You mistyped your ajax query url with ulr
Consider using a plugin for your browser like Web Developer, I'm pretty sure it would have picked up the error and you wouldn't have needed to ask here.
Edit: if you are still having troubles, validate the data you are going to send with some alert, validate that your php script does what you want it to do by navigating to it manually from the browser, since you provide a success callback, any reason you're not async, etc... validate everything
You got a typo in the ajax function,
url: <?php echo $path; ?>, //needs to be url, not ulr
You also don't need to serialize the values from the text fields. Just do this,
jQuery.ajax({
url: <?php echo $path; //this the url where the php file is ?>,
type: 'POST',
data: {
addressOne: $('#Form #table .key :input').val(),
addressTwo: $('#Form #table_2 .key :input').val(),
additionalData: $('#Form #More :input').val(),
preloaded: <?php echo serialize($array); ?>,
action: 'sendIt'
},
async: false,
cache: false,
success: function(data){
alert(data); //or console.log(data);
}
});

Sending back multiple results from PHP via AJAX

i have setup some ajax, which i am just testing now, pretty much the idea behind it is to send some data from dropdown boxes to a php script, do some calculations and then return the result, it does it well and returns the result, but now rather than just sending back one result and outputting that, i want to send back multiple results and output them, i am able to send multiple data to the php script, so i am sure i can send multiple back.
Anyway it only sends the first result back and not the rest.
Here is the AJAX
<script>
$("document").ready(function (){
$(".add_extension").change(function(){
var m = document.getElementById('meter_square');
var meter_square = m.options[m.selectedIndex].value;
var s = document.getElementById('story_height');
var story_height = s.options[s.selectedIndex].value;
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
statusCode: {
200: function (result, result2)
{
$("#expected_gain").html(result.value);
$("#house_price").html(result2.value2);
}
}
});
})
});
</script>
And here is the php script
<?php
$meter_square = $_GET["meter_square"];
$story_height = $_GET["story_height"];
$result = $meter_square + $story_height;
$result2 = $meter_square * $story_height;
echo json_encode(array("value" => $result, "value2" => $result2));
?>
You can see that i have already tried to give it a go from what i thought might work, if you need any other code or want me to remove the code i added which doesn't work, then let me know.
Thanks for all and any help
You're only going to receive one response object:
function (response) {
$("#expected_gain").html(response.value);
$("#house_price").html(response.value2);
}
Try this. Think it will help. No need to use status codes if u gonna use only success case
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
success: function(data){
$("#expected_gain").html(data.value);
$("#house_price").html(data.value2);
}
});

Jquery, reading JSON variables received from PHP

Sorry if this is basic, but I have been dealing with figuring this out all day and have gotten to where I can do everything I need with Jquery and cakephp (not sure if cakephp matters in this or if its same as any PHP), I want to return a variable from a cakephp function to jquery, I had read about how to do it, like here:
the cakephp:
$test[ 'mytest'] = $test;
echo json_encode($test);
and the jquery:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
}
});
I just can't figure out how to get one or more variables back into usable form within jquery, I just want the variable so I can do whatever else with it, I've been looking at what I can find through searching but its not making it fully clear to me.. thanks for any advice.
The JSON variables are in the data variable. In your case, it'll look like this:
var data = {
myTest: "Whatever you wrote here"
};
... so you can read it from data.myTest.
(Not sure whether it's relevant but you can remove the http://localhost/ part from the URL;
AJAX does not allow cross-domain requests anyway.)
Your variables are in data.
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
var values = eval( data ); //if you 100 % trust to your sources.
}
});
Basically data variable contain the json string. To parse it and convert it again to JSON, you have to do following:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
alert(json.mytest);
}
I haven't test it but it should work this way.
Note that when you specify dataType "json" or use $.getJSON (instead of $.ajax) jQuery will apply $.parseJSON automatically.
So in the "success" callback you do not need to parse the response using parseJSON again:
success: function(data) {
alert(data.mytest);
}
In case of returning a JSON variable back to view files you can use javascript helper:
in your utilities controller:
function ajax_component_call_handler() {
$this->layout = 'ajax';
if( $this->RequestHandler->isAjax()) {
$foobar = array('Foo' => array('Bar'));
$this->set('data', $foobar);
}
}
and in your view/utilities/ajax_component_call_handler.ctp you can use:
if( isset($data) ) {
$javascript->object($data); //converts PHP var to JSON
}
So, when you reach the stage in your function:
success: function(data) {
console.log(data); //it will be a JSON object.
}
In this case you will variable type handling separated from controllers and view logic (what if you'll need something else then JSON)...

Categories