I want to pass an array through AJAX but I am not getting any feed back on what it is I am sending. I tried to do a var_dump($_POST); on the PHP side (next.php) but nothing is showing up. I'm guessing there is something wrong with my code.
function sendToServer(data) {
$.ajax({
type: "POST",
data: { arr: JSON.stringify(data) },
url: "next.php",
success: function() {}
});
}
next.php:
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']));
foreach ($data as $item) {
echo $item;
// insert to db
}
?>
Full snippet of my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
//$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem is when you try to echo the item. As $item is an object (stdClass), and the echo command expects a string, the echo command fails with "stdClass could not be converted to a string". You can either change to:
echo print_r($item, true);
or:
var_dump($item);
Related
I have a list with the tag, the item values are obtained through an online spreadsheet. When selecting an option, the value does not appear in the html in real time. can anybody help me? I'm trying to solve it, but I can't find the error.
CODEPEN LINK EXAMPLE
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1J0qyxUCCkvcFGZ6EIy9nDOgEuTlpI5ICVG3ZsBd_H-I/1/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
console.log(data);
jQuery.each(entryData, function() {
$("#divTax").append(
'<option hidden="hidden" selected="selected" value="0">CHOISE</option><option value="' + this.gsx$values.$t + '">' + this.gsx$names.$t + ' $' + this.gsx$values.$t + '</option>'
);
});
});
});
var totalWithTax = $('#divTax :selected').val();
$('.total').html(totalWithTax);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select style="width: 80%;" id="divTax"></select>
<br>
Total:<div class="total"></div>
You to put the code that displays the selection in an event listener.
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1J0qyxUCCkvcFGZ6EIy9nDOgEuTlpI5ICVG3ZsBd_H-I/1/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
jQuery.each(entryData, function() {
$("#divTax").append(
'<option hidden="hidden" selected="selected" value="0">CHOISE</option><option value="' + this.gsx$values.$t + '">' + this.gsx$names.$t + ' $' + this.gsx$values.$t + '</option>'
);
});
});
$("#divTax").change(function() {
var totalWithTax = $(this).val();
$('.total').text(totalWithTax);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select style="width: 80%;" id="divTax"></select>
<br> Total:
<div class="total"></div>
I have code for filtering JSON data from select box to change a div value from HTML.
This is my code:
window.onload = populateSelect();
function populateSelect() {
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/jqvlv',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(birds) {
var xxx = document.getElementById('sel');
for (var i = 0; i < birds.length; i++) {
// POPULATE SELECT ELEMENT WITH JSON.
xxx.innerHTML = xxx.innerHTML +
'<option value="' + birds[i]['ID'] + '">' + birds[i]['Bird_Name'] + '</option>';
}
}
});
}
function show(xxx) {
// GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
var msg = document.getElementById('msg');
msg.innerHTML = 'Selected Bird: <b>' + xxx.options[xxx.selectedIndex].text + '</b> </br>' +
'ID: <b>' + xxx.value + '</b>';
var vv = document.getElementById('vv');
vv.innerHTML = 'ID: <b>' + xxx.value + '</b>';
}
select,
p,
input {
font: 1em Calibri;
}
<html>
<head>
<title>Bind SELECT Element with JSON using JavaScript</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<!--The SELECT element.-->
<select id="sel" onchange="show(this)">
<option value="">-- Select --</option>
</select>
<div id="msg" </div>
<br />
<div id="vv" </div>
</body>
</html>
How to make my other div get specific value from JSON data? Example for data harga, my code is running with returned same value.
You can persist JSON data with <OPTION> element. Create option using jQuery i.e. $('<option>') create element construct and the use various DOM method to set value i.e. .val() and text i.e. .text().
Using .data() method you can save arbitrary data with element which can be retrieved later.
window.onload = populateSelect();
function populateSelect() {
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/jqvlv',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(birds) {
var xxx = $('#sel');
for (var i = 0; i < birds.length; i++) {
//Create option using jQuery create element construct and use various DOM method to set value and text
var opt = $('<option>');
opt.text(birds[i]['Bird_Name']);
opt.val(birds[i]['ID']);
opt.data('json', birds[i]);
opt.appendTo(xxx);
}
}
});
}
function show(xxx) {
var data = $(xxx).find('option:selected').data('json');
console.log(data.Harga);
console.log(data);
$('#msg').html('Selected Bird: <b>' + JSON.stringify(data));
$('#vv').html('ID: <b>' + $(xxx).val() + '</b>');
}
select,
p,
input {
font: 1em Calibri;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<select id="sel" onchange="show(this)">
<option value="">-- Select --</option>
</select>
<div id="msg"></div>
<br>
<div id="vv"></div>
I believe you want yo display all data in different divs, please consider the following:
window.onload = populateSelect();
function populateSelect() {
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/jqvlv',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(birds) {
var xxx = document.getElementById('sel');
for (var i = 0; i < birds.length; i++) {
show({
id: birds[i]['ID'],
name: birds[i]['Bird_Name']
});
}
}
});
}
function show(xxx) {
var msg = document.getElementById('msg');
msg.innerHTML += 'Bird: <b>' + xxx.name + '</b> </br>' + 'ID: <b>' + xxx.id + '</b><br /><br />';
var vv = document.getElementById('vv');
}
select,
p,
input {
font: 1em Calibri;
}
<html>
<head>
<title>Bind SELECT Element with JSON using JavaScript</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
<div id="msg"> </div>
<br />
</body>
</html>
you should remove 'onchange' event in your select tag and use this code
$(document).ready(function(){
$('#sel').change(function(){
var msg = document.getElementById('msg');
msg.innerHTML = 'Selected Bird: ' + $("#sel option:selected").text(); + ' ' +
'ID: ' + $("#sel option:selected").val() + '';
var vv = document.getElementById('vv');
vv.innerHTML = 'ID: ' + $("#sel option:selected").val(); + '';
});
});
You can try this one it works fine.
I am trying to retrieve data from my db via ajax, console.log show the all results as I would like, however in my html it displays only one result which is the last data. Why is this? Can someone please help me?
Easy on answer as i'm a newbie :)
My code below;
HTML
<div class="mI">
<section>
<div class="pM" id="m1"></div>
</form>
</section>
<aside class="mBI">
<div class="mT">
<p id="m2"></p>
</div>
<p id="mG"></p>
<p style="margin-top:-8px" id="m3"></p>
</aside>
</div>
JAVASCRIPT
$(document).ready(function() {
"use strict";
function connect2mO() {
$.ajax({
url: "tes.php",
type: "GET",
//data:"",
dataType: "json",
//async:false,
success: function(data) {
$.each(data, function() {
var mP = this.p;
var mT = this.t;
var mG = this.g;
console.log(mP);
console.log(mT);
console.log(mG);
$('#m1').html('<img src="p/' + mP + '"/>');
$('#m2').html(mT);
$('#m3').html(mG);
});
},
error: function connect2mO() {
alert('error loading mO');
}
});
}
if (window.attachEvent) {
window.attachEvent('onload', connect2mO);
} else if (window.addEventListener) {
window.addEventListener('load', connect2mO, false);
} else {
document.addEventListener('load', connect2mO, false);
}
});
PHP
<?php
include ('session_start.php');
include ('db_connect_mO.php');
$sql = mysqli_query($con, "SELECT * FROM mo ORDER BY mRD");
$row = mysqli_fetch_array($sql);
while ($row = mysqli_fetch_assoc($sql))
{
$test[]= array(
'p'=> $row['mP'],
't'=> $row['mT'],
'g'=> $row['mG'],
);
}
header('Content-Type: application/json');
echo json_encode ($test);
//detailed error reporting
if (!$sql)
{
echo 'MySQL Error: ' . mysqli_error($db);
exit;
}
?>
What the code below will output in php its what I am trying to achieve using ajax.
<?php while ($row = mysqli_fetch_assoc($sql)) { ?>
<div class="mI">
<section>
<div class="pM"><img src="p/<?php echo $row["mP"];?>" alt=""/></div>
</section>
<aside class="mBI">
<div class="mT">
<p><?php echo $row["mT"];?></p>
</div>
<p id="mG"></p>
<p style="margin-top:-8px"><?php echo $row["mG"];?></p>
</aside>
</div>
<?php } ?>
var data = [{'p': 'p1', 't':'t1', 'g': 'g1'},{'p': 'p2', 't':'t2', 'g': 'g2'},{'p': 'p3', 't':'t3', 'g': 'g3'}];
$.each(data, function() {
$.each(this, function(key,value) {
var display = '<div>'+ key +' = ' +value+ ' </div>';
$('body').append(display);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For your code you can do it like this
var data = [{'p': 'p1', 't':'t1', 'g': 'g1'},{'p': 'p2', 't':'t2', 'g': 'g2'},{'p': 'p3', 't':'t3', 'g': 'g3'}];
$.each(data, function() {
var html = '<hr>'+
'<div class="mI">'+
'<section>'+
'<div class="pM" >' + this.p + '</div>'+
'</form>'+
'</section>'+
'<aside class="mBI">'+
'<div class="mT">'+
'<p>' + this.t + '</p>'+
'</div>'+
'<p></p>'+
'<p style="margin-top:-8px" id="m3">' + this.g + '</p>'+
'</aside>'+
'</div>';
$('body').append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Replace this:
$('#m1').html('<img src="p/' + mP + '"/>');
$('#m2').html(mT);
$('#m3').html(mG);
which just overwrites the values with this which appends:
$('#m1').html($('#m1').html() + '<img src="p/' + mP + '"/>');
$('#m2').html($('#m2').html() + mT);
$('#m3').html($('#m3').html() + mG);
I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.
I need to print the json response in 'resulte' div as array same as that was sent by php.
Upload.php:
$arr=array('username'=>array('isEmpty'=>'required','exists'=>'username exists'),'password'=>array('isEmpty'=>'requiredd'));
echo json_encode($arr);
index.php:
<script src="jquery.min.js"></script>
<script src="jquery.form.min.js"></script>
<script type="text/javascript">
function a(){
$('#submitForm').ajaxForm({
dataType: 'json',
success: function(result){
document.getElementById('resulte').innerHTML=”I need to print the response array here like key=>value”;
}}).submit();
}
</script>
<form id="submitForm" name="submitForm" action="upload.php" method="post" enctype="multipart/form-data" >
File: <input name="myfile" type="file" />
<input type="button" id="submitBtn" name="submitBtn" value="Upload" onclick="a();" />
</form>
<div id="resulte" name="resulte"></div>
suppose I don’t know the keys and values and how many record is received in index.php. so I would like to use some condition here like :
foreach($result as $key=>$value){
if($key==” username”){
echo $key.”=><br />”;
foreach($value as $k=>$val){
if($k==” isEmpty”){
echo $k.”=>”.$val.”<br />”;
}
}
}
}
how can I do all those by javascript ?
-thanks.
RESOLVED:
(According to the answer of 'josh')
<script type="text/javascript">
function a(){
$('#submitForm').ajaxForm({
dataType: 'json',
success: function(result){
for (var key in result) {
if (result.hasOwnProperty(key)) {
if(key == "username") {
document.getElementById('resulte').innerHTML = key + " => <br />";
for (var k in result[key]) {
if (k == "isEmpty") {
document.getElementById('resulte').innerHTML += k + " => " + result[key][k] + "<br />";
}
}
}
}
}
}}).submit();
}
</script>
Try this.
var p = {"username":{"isEmpty":"required","exists":"username exists"},"password":{"isEmpty":"requiredd"}};
for (var key in p) {
if (p.hasOwnProperty(key)) {
if(key == "username") {
document.getElementById('resulte').innerHTML += key + " -> " + p[key] + "<br />";
for (var k in p[key]) {
if (k == "isEmpty") {
document.getElementById('resulte').innerHTML += k + " -> " + p[key][k] + "<br />";
}
}
}
}
}