Retrieve data via JSON and put in a form - php

I´ve tried retrive some info from mysql for put it in a form,and update the info.
I use ajax call in the same page,I call ajax passing the id and php return all info.
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
ajax call shows like this
$(document.body).on('click', '.edit' ,function(){
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {retriveForm : id},
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
When put .val(response.item1) get anything,but if I put response the input take all values
$('#myForm').find('input').eq(1).val(response);
shows
{"item1":"item1","item2":"item2","item_array":["item_in_array1","item_in_array2"]}
I also tried
var obj = jQuery.parseJSON(response);

Try setting $.ajax() dataType options to "json"
"json": Evaluates the response as JSON and returns a JavaScript
object.
$(document.body).on("click", ".edit", function() {
var id = $(this).data("id");
$.ajax({
type: "POST",
url: "is_the_same_page.php",
dataType: "json", // set `dataType` to `"json"`
data: {
retriveForm: id
},
success: function(response) {
$("#myForm").find("input").eq(1).val(response.item1);
}
});
});

Related

when I send data with ajax php wont get anything

post and get works fine but json returns wrong value , or something is wrong with my php code.
$(function () {
$('#username').on('keypress',function () {
var input = $('#username').val();
if(input.length>=4){
$.ajax({
url:'registration_php.php',
type: 'POST',
data:{username:input},
success:function () {
$.getJSON('registration_php.php',function (text) {
alert(text.user);
});
}
});
}
});
});
success:function(result) {
var items = JSON.parse(result);
alert(items['user']);
}
pass the result directly to your reponse as an argument like this
you should specify a dataType: "json" in your ajax call
var postData = JSON.stringify({
username: 'value'
});
var request = $.ajax({
url: "registration_php.php",
method: "POST",
dataType: "json",
data: postData,
});
request.success(function( results ) {
console.log(results)
});

Getting error named 'undefine' when i fetch json data from php page to index page

When I click on an image it opens popup and it will show zoom image but it is not working properly. It shows whole array but it cant display by index.
So how do I fix this problem?
popup.php
$id = $_REQUEST['id'];
$hidden_id = $_POST['hidden_id'];
$sel = "select * from uploaded_images where id='$id' ";
$exe = mysql_query($sel);
$fet = mysql_fetch_assoc($exe);
echo json_encode($fet);
this is my jquery code:
$(document).ready(function () {
//open popup
$(".anchor_img").click(function (e) {
var targetPopup = $(this).attr('id');
//$(".overlay_form").html("$id="+targetPopup);
$("#hidden_id").attr('value',targetPopup);
//$("#myform").submit();
//var dataStr = $("#myform").serialize();
//alert(targetPopup);
$.ajax({
type: "POST",
url: "popup.php?id="+targetPopup,
dataType : 'JSON',
data: $('#myform').serialize(), // serializes the form's elements.
success: function(data)
{
$(".overlay_form").fadeIn(1000);
//$("#id").html(jsonStr.id);
console.log(data.id);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
//close popup
$(".close").click(function () {
$(".overlay_form").fadeOut(500);
});
});
You should send the JSON with the proper header from PHP :
header('Content-Type: application/json');
echo json_encode($fet);
And/or use lowercase parameter value for "dataType" :
$.ajax({
type: "POST",
url: "popup.php?id="+targetPopup,
dataType : 'json',
data: $('#myform').serialize(), // serializes the form's elements.
success: function(data)
{
$(".overlay_form").fadeIn(1000);
//$("#id").html(jsonStr.id);
console.log(data.id);
}
});

Can't post JSON variable with AJAX to PHP

In the first document I added a JSON string filled with numbers to localstorage like this:
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}});
Then in another document I am trying to post the JSON string retrieved from local storage like this:
<script>
var data = JSON.parse(localStorage.getItem('key'));
var localData = data.join(", ");
$.ajax({
type: 'post',
data: {localData: localData},
url: '',
dataType: "json",
success: function(result){
console.log(result)
}});
</script>
The PHP on the same page as the post tries to fetch the data like this:
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$values = json_decode($user_id);
var_dump($values);
?>
When I run var_dump I get Array(), so in essence it doesn't post anything. Anyone know whats going wrong?
You don't need to use JSON when sending an array in an object argument to $.ajax. Just put the array there, and jQuery will URL-encode it.
var data = JSON.parse(localStorage.getItem('key'));
$.ajax({
type: "post",
data: { localData: data },
...
});
Then in PHP you can do:
$values = isset($_POST['localData']) ? $_POST['localData'] : array();
var_dump($values);
You can also send JSON this way:
var json_string = localStorage.getItem('key');
$.ajax({
type: "post",
data: { localData: json_string},
...
});
then in PHP do:
$values = json_decode(isset($_POST['localData']) ? $_POST['localData'] : '[]');
var_dump($values);

Localstorage to PHP variable

I am sending and retrieving some data with this ajax call and saving result in localstorage like this:
$.ajax({
url: "list.php",
data: {values: values},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}
});
Then I am retrieving it in a separate PHP document like this and trying to add it to a PHP variable. I think the problem occurs because when I console.log, it logs 10 times or so. And I can't echo it in PHP. How do I pass it correctly?
<script>
var localData = JSON.parse(localStorage.getItem('key'));
$.each(localData, function(key, value){
console.log("This is the data that is stored", localData)
$.ajax({
type: 'post',
data: {localData},
dataType: "json",
success: function(result){
console.log(result)
}
});
</script>
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = implode(", ", $user_id);
?>
You are causing an asynchronous functionality of ajax() real pain by calling it in a loop
Why dont you use join() to join items with ", " in js like what you do in php
<script>
var localData = JSON.parse(localStorage.getItem('key')).join(", ");
$.ajax({
type: 'post',
data: {localData},
dataType: "json",
success: function(result){
console.log(result)
}
});
</script>
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = $user_id;
?>
You Should also cast user_id as an (int) if user_id need to be a single value and int
$verdier = (int) $user_id;

Access Data from Database with Ajax

I have tried just about every solution and I know my database returns values if i hard code in the php so the issues is returning the values or determining if it is actually sent as post. It gets to the success function and alerts Worked but I am getting undefined for Item ID.
$(document).ready(function() {
$('.check').click(function(){
alert("Step1");
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "GET",
url: "XXX.PHP",
data: { "ID": thisID},
cache: false,
async:true,
datatype: "json",
success: function(data)
{
alert("WORKED");
alert(data.ItemID);
}
});
});
});
Here is the PHP
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
function retrieve($ID)
{
$stmt = $mysqli->query("SELECT * FROM database1.menu WHERE ItemID = $ID");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
You could try something like this. Not sure if this is what you need.
$(".check").click(function(event){
event.preventDefault();
var $this = $(this);
var thisID = $this.attr('id');
$.ajax({
type: "POST",
url: base_url + "url.php",
data: {
id: thisID
},
dataType: "text",
cache:false,
success:
function(data){
alert(data);
}
});
return false;
});

Categories