AJAX POST TO PHP - php

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']);

Related

Ajax Post to PHP returning empty array

I need to pass a json object from JS to PHP, and it will pass, but the result is an empty array.
Ajax request in 'adopt.php':
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {'info': info},
success: function(data){
console.log(data);
}
});
ajax.php code:
if(isset($_POST['info'])){
$_SESSION['array'] = $_POST['info'];
}
back in adopt.php, later:
if(isset($_SESSION['array'])){
$arr = $_SESSION['array'];
echo "console.log('information: ' + $arr);";
}
in both of the console.logs, it returns an empty object. Does anybody know what could be causing this? (i've tried just passing the json without stringifying it, but it throws a jquery error whenever i do this.)
Try below code i think you miss return ajax response
adopt.php
<script>
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {info: info},
success: function(data){
console.log(data);
}
});
</script>
ajax.php
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(["result" => "success"]);
}
To get the response data from PHP, you need to echo your data to return it to the browser.
In your ajax.php:
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(['result' => $_SESSION['array']]);
}
Your ajax.php is not returning any data.To get data at the time of success you need to echo the data you want to display on success of your ajax.

How to access AJAX response variables in PHP

I can't access my variables through ajax using php.
AJAX CODE
$("input[name='absent[]'").change(function() {
var obj = $(this); //checkbox
var valueZero = obj.val();
var Code = obj.attr('data-Code');
var value = obj.attr('data-session');
/*var theTR = $(this).parent('tr').children().find('td:eq(0)').addClass('hidden');*/
/* alert( theTR.text());*/
/*$(this).addClass('hidden');*/
$.ajax({
data: "{ code: '"+ Code +"', abt_prt: "+ valueZero +", InOut: "+ value +" }", // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
});
PHP CODE
<?php
if(isset($_REQUEST))
{
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
//need this variables to perform a insert query
}
?>
Do try this :
JAVASCRIPT
var mainString = "code="+Code+"&abt_prt="+valueZero+"&InOut="+value;
IN AJAX
data : mainString
PHP
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
use data like
data: { code:Code , abt_prt : valueZero , InOut : value },
and in php I don't really know what is $_REQUEST is but you can use
if(isset($_POST)){
}
Try changing data variable to:
data: {"code":Code,"abt_prt":valueZero,"InOut":value},
You are misunderstanding how AJAX parameters have to be sent. You do not need to send an index, you can send a simple Javascript object, like this:
$.ajax({
data: { code: Code, abt_prt: valueZero, InOut:value}, // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
However, if for some reason you want to send a string like you did, then decode it using json_decode.

fetch data from JSON in PHP

I have a JSON code that send a form to on PHP file and I want to use data in PHP
the code is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/yadavari/test.php?";
var json_text = JSON.stringify($("form[name='add']").serialize(), null, 2);
var datas = JSON.parse(json_text);
ajx = $.ajax({
url: url,
type: 'post',
data: datas,
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r);
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error msg');
alert( "ERROR: " + err + " - " );
}
Now I want to fetch data from this JSON code in my PHP page.
I searched but every body just said that $string='{"name":"John Adams"}'; and so.
But I dont know that how can I have this $string in my PHP.
You should have something like:
<?php
echo $_POST["INPUTNAME"];
?>
Care about this, it suffers from security injection.
You need to call the php json_decode function on the returned string. This will convert it into an associative array:
$json2array = json_decode($json_text);
echo $json2array['name']; // "John Adams"

PHP server does not get the $.ajax request from jquery

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/

ajax success but not sending post data

Hi i have this simple code:
var datastring="123";
$.ajax({
url: 'actualizarimagen.php',
type: 'post',
dataType: 'text',
data: datastring,
cache: false,
success: function(response){
$('.msg1').html(response);
},
error: function(response){
$('.msg1').html(response);
}
});
And in actualizarimagen.php:
$desc_larga = print('<pre>') & print_R($_POST) & print('</pre>');
$insertSQL = sprintf("INSERT INTO prueba (texto) VALUES ($desc_larga)");
I get the success message, but in the database always saves 1. I tried changing everything, the dataType, the success, error, complete functions but it doesn't work. I was searching but any answers couldn't help me.
Thanks.
Edit: Added response
Your datastring should contain data encoded as application/x-www-form-urlencoded
e.g.: var datastring="foo=123";
It is better not to pass a string to jQuery at all. Pass it an object and let it handle the encoding for you.
e.g.: data: { "foo": "123" }
data
Object, String
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. See processData option to prevent this automatic processing. 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 (described below).
You are just sending up 123 to the server.
It should be something like
var datastring="myField=123";
or
var datastring = {"myField" : 123 };
and with the PHP you would read it
$_POST["myField"]
to send the data, there are format to be followed.
Like
var datastring="var1=123&var2=abcd";
or
var datastring=[{name:'var1',value:123},{name:'var2',value:'abcd'}];
The second format (array of object name value) is like <input type="text" name="var1" value="123"> where html input element has name and value to be posted.
Then, you can get the value by :
$_POST['var1']
or
$_POST['var2']
An example to achieve this easily could be:
JS:
var datastring="123";
$.post('actualizarimagen.php', { datastring:datastring }, function(data){
if(data != 0){
$('.msg1').html('correcto');
} else {
$('.msg1').html('error');
}
});
In your actualizarimagen.php:
if($_POST() && isset($_POST['datastring'])){
/* Connect to DB */
$link = mysql_connect('server', 'user', 'pwd');
if (!$link) {
// No connection
print(0);
exit();
}
$db = mysql_select_db('db', $link);
if (!$db) {
// DB selection error
print(0);
exit();
}
/* Sanitize the value */
$datastring = mysql_real_escape_string($_POST['datastring']);
// I don't understand here what you tried to do with $dec_larga but this is what I thought
$desc_larga = "<pre>".$datastring."</pre>";
/* Insert to DB */
$sql = "INSERT INTO prueba (texto) VALUES ('$desc_larga')";
if(mysql_query($sql,$link)){
// Everything is Ok at this point
print(1);
} else {
// Error happened in your SQL query
print(0);
}
}
In the ajax call:
data: my_var : datastring,
in the php:
$desc_larga = '<pre>'.$_POST['my_var'].'</pre>';
try replacing
type: "post",
with
type: "POST",
and your datastring should be like this :
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
as explained here:
http://api.jquery.com/serialize/
var datastring = "123";
$.ajax({
url: 'actualizarimagen.php',
type: 'post',
dataType: 'text',
data: {data : datastring},
cache: false
}).always(function(response) {
$('.msg1').html(response);
});
And in actualizarimagen.php:
$desc_larga = '<pre>'.$_POST['data'].'</pre>';
$query = '"INSERT INTO prueba (texto) VALUES ('.$desc_larga.')"';

Categories