In my local machine, I am trying to save data from a json to my mysql database, I am using Wampserver.
In my html page (saveInfo.php), I have this jquery code:
<script type="text/javascript">
var jsObj = {"user_id":5, "login":"hsm"};
var jsonobj = JSON.stringify(jsObj);
$.ajax({
type: "POST",
url: "json_handler.php",
data: { 'jsonobj':jsonobj },
success: function(){
alert('success');
window.location = "http://localhost/quranMapping/php/json_handler.php";
}
});
</script>
In the other side, I have my server-side php code (json_handler.php) like that:
<?php
$input = file_get_contents('php://input');
$input = $_POST['jsonobj'];
$result = json_decode($input);
echo $result->user_id;
?>
But when I run that code, I get this error:
You should remove this:
var jsonobj = JSON.stringify(jsObj);
and change
data: { 'jsonobj':jsonobj },
to
data: jsObj,
On the php side to decode the data just use
$user_id = isset($_POST["user_id"])?$_POST["user_id"]:"";
$login = isset($_POST["login"])?$_POST["login"]:"";
Also there is no need to do
$input = file_get_contents('php://input');
Since the form is being posted with an object as data the value will be application/x-www-form-urlencoded so it don't be valid json.
Related
Hi i don't get retrieve Ajax Data to PhP page its throwing error. i pass data as json object.
The error i'm getting is
Edit.php
$('#regForm').on('submit', function (e) {
var url = document.URL; // Get current url
var id = url.substring(url.lastIndexOf('=') + 1);
var data1 = $("#regForm").serialize();
data = {data:data1,id:id};
console.log(data)
$.ajax({
method:"POST",
url: 'update.php',
dataType : 'json',
data: data,
success: function () {
alert('form was submitted');
}
});
});
update.php
if(isset($_POST["submit"]))
{
print_r($_POST['data']);
// Error::: Undefined index:data in
pass Id using hidden input field and then form data serialize then after you can use by name wise on php page.
$_POST['name'];
Read my comment, then look at this:
JavaScript may look like this
$('#regForm').on('submit', function(e){
var s = location.search.split('&'), serialId = s[s.length-1], idArray = serialId.split('=');
if(idArray.length === 2 && idArray[1].trim() !== '' && idArray[0].match(/^id$/i)){
var serialData = $(this).serialize()+'&'+serialId;
$.ajax({
method:'POST', url:'update.php', dataType:'json', data:serialData},
success:function(jsonObj){
console.log(jsonObj);
}
});
}
e.preventDefault();
});
PHP may look like this
<?php
if($_POST['id']){
// each property as $_POST[propertyHere]
// sending back to JavaScript
$c = new stdClass; $c->someProp = 'some value';
echo json_encode($c); // dataType is json so you should get Object as result
}
?>
JS file:
var jsonsave = [];
var dado = new Object();
dado.name = "bob";
dado.age = "000";
dado.test = "test";
var jason = JSON.stringify(dado);
jsonsave.push(jason);
$.ajax({
type: "POST",
dataType: "JSON",
url: "http://localhost/moodle/my/index.php",
data: "data="+jsonsave+"&file=true",
success: function(data){
console.log('work');
},
error: function(data)
{
console.log(data);
}
});
Arquivo php:
$arquivo = $_POST['data'];
$value= json_decode($arquivo, TRUE);
I call a php page from ajax, but i can't take the json's value, it came null,do you have some idea?
In your AJAX call you specified
dataType: "JSON"
which means that your call expects JSON as returned value from server.
On the other hand, on the PHP side you are decoding POST, which is converting JSON to PHP object (structure), and also you are not returning anything.
Solution is simple: send JSON structure back (try with json_encode, maybe in addition with appropriate headers), and that should do to trick.
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.
This question might be repetitive but i got confused reading all posts relating to this.(sincere apologies!) Basically, I want to send a javascript array to a php file and inturn write the array to a text file . I learnt the best way to go about it is using JSON and AJAX. My code is displays "success" for the ajax part, and also creates a file (php code),but an empty text file.
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = [valueSelected];
for ($i=3;$i<row;$i++)
{
var dv="selectstate"+$i;
var dv1=document.getElementById(dv).value;
var sl="selectstreet"+$i;
var sl1=document.getElementById(sl).value;
var po="selectbuilding"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values.push(concat);
}
JSON = JSON.stringify(values);
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: JSON ,
success: function(){
alert("Success!")
}
});
PHP Code:-
<?php
$json = $_POST['JSON'];
$p = json_decode(JSON);
$file = fopen('test.txt','w+');
fwrite($file, $p);
fclose($file);
echo 'success?';
?>
Two flaws:
a) You're not sending your data correctly - it's lacking a field name:
data: {data: JSON}
^^^^---this will be the key in PHP's $_POSt
b) You're using invalid constants in PHP and not even decoding what MIGHT have been the passed in data. You should have:
$p = json_decode($_POST['data']);
^^^^--matching what you have in the `data` field in Javascript.
I've been trying to find an answer for this for hours but really struggling.
I have a simple jquery Ajax function which sends data to a PHP script. The data is then used to conduct a MySQL query and the results are included as an array. I'm sending the array back using json_encode but can't work out how to display the array at the other end. I've posted the code below. The console.log is displaying Object {modules: Array[0]}
. There should be 3 entries in the array.
The PHP
<?php
include_once('../../dbconnect.php');
$name = $_POST['uploadname'];
$query = "SELECT * FROM marking_assignments WHERE name = '$name'";
$details = $conn->query($query);
$modules = array();
while ($row = $details->fetch_assoc()){
$modules[] = $row['unit'];
}
$dataarray = array("modules"=>$modules);
echo json_encode($dataarray);
?>
The jQuery
var uploadname;
$("#uploadname").blur(function(){
uploadname = $(this).val();
$.ajax({
url: "uploadnames.php",
type: "POST",
data: {uploadname: uploadname},
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
you should use:
var parsedData = jQuery.parseJSON(data);
and then:
console.log(parsedData)