Hi I am calling the following javascript function to send some data to
a php server. But the server does not receive the data:
function sendData()
{
var obj = new Object();
obj.id = "001";
obj.len = "7";
$.ajax({
type: "POST",
url: "php.php",
data: JSON.stringify(obj)
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
this is my php code:
<?php
if (!empty($_POST))
{
echo $_POST['id'];
}
else
echo "no data"
?>
Can some one please let me know where I am making the mistake. I just
could not figure it out!
this causes the problem
data: JSON.stringify(obj)
and change it to
data: obj
from the JQuery docs:
data
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
reference: http://api.jquery.com/jQuery.ajax/
Related
Hi I am getting the following error when I call action in controller from ajax.
Undefined index : value.
This is my code in Document Ready
unique function is to create array of unique elements.
var modules =[];
var action = [];
var max_limit=[];
var details ={};
$(".btn-small").click(function()
{
modules = unique(modules);
action = unique(action);
limit = unique(limit);
details['id'] = id;
details['cost'] = sum;
details['modules'] = modules;
details['action'] = action;
details['limit'] = limit;
jsonString = JSON.stringify(details);
$.ajax({
url: "<?php echo Yii::app()->createUrl('/xxxxxxxx/actionDemo'); ?>",
data: {'value':jsonString },
type: 'post',
dataType:'json',
success: function() {
alert("st");
},
error: function(){
alert("Error: Could not delete");
}
});
This is my code in action in Controller :
public function actionDemo() {
$val = $_POST['value'];
var_dump($val);
die();
}
It means that "value" is not in you post data. Try to dump your POST and see what is going on.
This is probably because you are sending a JSON, so you POST will contain a JSON instead of an Array.
I think this will help you,
If you are sending JSON to server side you need to specify contentType in AJAX request. dataType:'json' says that what kind of response you expect from server.
Or else you can directly pass "data: {'value':details}," in AJAX without converting into JSON.
The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}
I am using jQuery's AJAX functionality - and I get a response back just fine, but for some odd reason I cannot parse the information inside of it!
I am calling the following:
console.log(results);
console.log(results.data);
And what I get is:
{"data":[{"member":"asdfasdf","status":"Invalid Email"}]}
undefined
Here is my jQuery:
$.ajax({
type: "POST",
url: "<?php echo Uri::base();?>ajax/add_members/organization",
data: {
organization_id: <?php echo $organization->id;?>,
members: $('#members').val(),
position: $('#position').val()
}
}).done(function (results) {
// lets add them to the table
console.log(results);
console.log(results.data);
});
UPDATE: dataType: 'json', was required!
Just because you have retrieved the string successfully in results doesn't mean it is already an object. You need to parse the JSON string into an object (this can be done as a shortcut depending on your actual method of calling (i.e getJSON).
You might need to do something like this to actually get an object.
var obj = $.parseJSON(results);
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
dataString is :
{"feedback_type":"000","error_type":"","textarea":"blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah"}
I used the following code to post to the PHP:
// ajax post
$.ajax({
type: "POST",
url: "core/poster.php" ,
data: dataString,
success:function()
{
alert("Success!");
}
});
return false;
And php file:
<?php
require 'Class_DBOperation.php';
require 'global.php';
// Establish Database Connection
$dbOperation = new class_DBOperation(DBHOST,DBUSER,DBPWD,DBNAME,DBCHARSET);
// Receive dataString
$content=$_POST['feedback_type'];
$run=mysql_query("insert into reports values (NULL, '".$content."')");
?>
The problem is why $content is empty?
What should I do ? any ideas?
Add a response in your success function and alert it
$.ajax({
type: "POST",
url: "core/poster.php" ,
data: dataString,
success:function(response)
{
alert(response);
}
});
And in your poster.php file try adding the following to the top within the PHP tag.
ini_set("display_errors", 1);
var_dump($_POST);
This should give you a place to start and debug what's going on.
This isnt a direct solution, but it may help you find out what is wrong. Try dumping out the contents of your $_POST superglobal, this will inform you of how the data was received. Try something like:
print '<pre>';
print_r ($_POST);
print '<pre>';
Remove your double quotes for parameter names
{
feedback_type: "000",
error_type: "",
textarea: "blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah"
}
You're sending a JSON string as the parameter string.
Parameters should be formatted as follows:
foo=bar,foo2=bar2,foo3=bar3 etc...
You could either reformat the string to follow the norm:
JS:
var dataString = "feedback_type=000&error_type=&textarea=blahblahblah";
PHP:
echo $_POST['feedback_type']; // 000
echo $_POST['error_type']; // null
echo $_POST['textarea']; // blahblahblah
or you could pass the JSON string as a POST parameter:
JS:
var jsonObject = {
"feedback_type" : "000",
"error_type" : "",
"textarea" : "blahblah"
}
var jsonString = '{"feedback_type":"000","error_type":"","textarea":"blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah"}';
// OR
var jsonString = JSON.stringify(jsonObject);
var dataString = "json_string=" + jsonString;
PHP:
// String - suitable for database input
echo $_POST['json_string']; // String: {"feedback_type":"000","error_type":"","textarea":"blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah"}
// Parse into array
$json_array = json_decode($_POST['json_string']);
Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}