Print json response as array with key and value - javascript

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 />";
}
}
}
}
}

Related

How can I perform remove to cart and update cart without page refresh

i have a simple code to add items to cart, when a user removes items to cart the page refreshes and that makes it scroll back to the top. updating quantity also does the same. I belive i can have these functions work without page refresh but i dont know how to execute this. here is my cart code
<?php
session_start();
// check if the delete_id is passed via the URL
if(isset($_GET['delete_id'])) {
$delete_id = (int)$_GET['delete_id'];
// search for the product to delete
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $delete_id) {
unset($_SESSION['cart'][$key]);
}
}
}
// check if the update_id and quantity are passed via the URL
if(isset($_GET['update_id']) && isset($_GET['quantity'])) {
$update_id = (int)$_GET['update_id'];
$quantity = (int)$_GET['quantity'];
// search for the product to update
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $update_id) {
if(isset($product['quantity'])) {
$_SESSION['cart'][$key]['quantity'] = $quantity;
} else {
$_SESSION['cart'][$key]['quantity'] = 1;
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cart</title>
</head>
<body>
<!-- Header menu with logo, about us, and cart menu -->
<div id="header">
<div id="logo">Logo</div>
<div id="test">
products Page
</div>
<div id="about-us">About Us</div>
<div id="cart-menu">
Cart (<?=count($_SESSION['cart'])?>)
</div>
</div>
<!-- Cart list -->
<div id="cart-list">
<?php
if (empty($_SESSION['cart'])) {
echo '<p>Your cart is empty</p>';
} else {
$total = 0;
foreach($_SESSION['cart'] as $product) {
echo $product['name']. " <br>";
echo '<button type="button" onclick="decrementQuantity('.$product['id'].')">-</button>';
echo '<span id="product-'.$product['id'].'-quantity">'.(isset($product['quantity']) ? $product['quantity'] : 1).'</span>';
echo '<button type="button" onclick="incrementQuantity('.$product['id'].')">+</button>';
$subtotal = $product['price'] * (isset($product['quantity']) ? $product['quantity'] : 1);
echo '<p>Subtotal: $<span id="product-'.$product['id'].'-subtotal">'.number_format($subtotal,2).'</span></p>';
$total += $subtotal;
echo '<p><button type="button" onclick="removeFromCart('.$product['id'].')">Remove Item from Cart</button></p>';
echo '<hr>';
}
echo '<p>Total: $<span id="total">'.number_format($total,2).'</span></p>';
}
?>
</div>
<script>
function incrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
var newQuantity = currentQuantity + 1;
updateQuantity(id, newQuantity);
}
function decrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
if(currentQuantity > 1) {
var newQuantity = currentQuantity - 1;
updateQuantity(id, newQuantity);
}
}
function updateQuantity(id, value) {
var url = "cart.php?update_id=" + id + "&quantity=" + value;
// Change the displayed quantity
document.getElementById('product-' + id + '-quantity').innerHTML = value;
// Update the subtotal
var price = parseFloat(document.getElementById('product-' + id + '-subtotal').innerHTML) / parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
document.getElementById('product-' + id + '-subtotal').innerHTML = price * value;
updateTotal();
window.location.href = url;
}
function removeFromCart(id) {
var url = "cart.php?delete_id=" + id;
window.location.href = url;
}
function updateTotal() {
var total = 0;
var subtotals = document.getElementsByClassName('product-subtotal');
for (var i = 0; i < subtotals.length; i++) {
total += parseFloat(subtotals[i].innerHTML);
}
document.getElementById('total').innerHTML = total;
}
</script>
</body>
</html>
what i have read is i should add event listeners to the buttons and use $.ajax() method... I am not so good in coding therefore i cant implement this so i dont even know if it will work
<?php
session_start();
// check if the delete_id is passed via the URL
if(isset($_GET['delete_id'])) {
$delete_id = (int)$_GET['delete_id'];
// search for the product to delete
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $delete_id) {
unset($_SESSION['cart'][$key]);
echo "success";die;
}
}
}
// check if the update_id and quantity are passed via the URL
if(isset($_GET['update_id']) && isset($_GET['quantity'])) {
$update_id = (int)$_GET['update_id'];
$quantity = (int)$_GET['quantity'];
// search for the product to update
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $update_id) {
if(isset($product['quantity'])) {
$_SESSION['cart'][$key]['quantity'] = $quantity;
} else {
$_SESSION['cart'][$key]['quantity'] = 1;
}
echo "success";die;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<div id="header">
<div id="logo">Logo</div>
<div id="test">
products Page
</div>
<div id="about-us">About Us</div>
<div id="cart-menu">
Cart (<?=count($_SESSION['cart'])?>)
</div>
</div>
<!-- Cart list -->
<div id="cart-list">
<?php
if (empty($_SESSION['cart'])) {
echo '<p>Your cart is empty</p>';
} else {
$total = 0;
foreach($_SESSION['cart'] as $product) {
echo "<div class='product product-".$product['id']."'>";
echo $product['name']. " <br>";
echo '<input type="hidden" id="product-'.$product['id'].'-price" value="'.$product['price'].'">';
echo '<button type="button" onclick="decrementQuantity('.$product['id'].')">-</button>';
echo '<span id="product-'.$product['id'].'-quantity">'.(isset($product['quantity']) ? $product['quantity'] : 1).'</span>';
echo '<button type="button" onclick="incrementQuantity('.$product['id'].')">+</button>';
$subtotal = $product['price'] * (isset($product['quantity']) ? $product['quantity'] : 1);
echo '<p>Subtotal: $<span id="product-'.$product['id'].'-subtotal" class="subtotals">'.number_format($subtotal,2).'</span></p>';
$total += $subtotal;
echo '<p><button type="button" onclick="removeFromCart('.$product['id'].')">Remove Item from Cart</button></p>';
echo '<hr></div>';
}
echo '<p>Total: $<span id="total">'.number_format($total,2).'</span></p>';
}
?>
</div>
<script>
function incrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
var newQuantity = currentQuantity + 1;
updateQuantity(id, newQuantity);
}
function decrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
if(currentQuantity > 1) {
var newQuantity = currentQuantity - 1;
updateQuantity(id, newQuantity);
}
}
function updateQuantity(id, value) {
var $proC = $('.product.product-' + id );
var product_price = $('#product-'+id+'-price').val();
$proC.find('button').attr("disabled","disabled");
var url = "cart.php?update_id=" + id + "&quantity=" + value;
$.ajax({
url:url,
type:'GET',
success:function(response){
$proC.find('button').removeAttr("disabled");
if($.trim(response) == 'success'){
document.getElementById('product-'+id+'-quantity').innerHTML = value;
document.getElementById('product-'+id+'-subtotal').innerHTML = product_price * value;
}else{
alert("Something went wrong.try again..");
}
updateTotal();
},
error:function(err){
$proC.find('button').removeAttr("disabled");
alert(err);
}
})
}
function removeFromCart(id) {
var url = "cart.php?delete_id=" + id;
$.ajax({
url:url,
type:'GET',
success:function(response){
if($.trim(response) == 'success'){
$('.product.product-'+id).remove();
alert("Product removed.");
}else{
alert("Something went wrong.try again..");
}
},
error:function(err){
alert(err);
}
})
}
function updateTotal() {
var total = 0;
var subtotals = document.getElementsByClassName('subtotals');
for (var i = 0; i < subtotals.length; i++) {
total += parseFloat(subtotals[i].innerHTML);
}
document.getElementById('total').innerHTML = total;
}
</script>
</body>
</html>

How to call element values (sId and sTmp values) as key value pairs in Javascript?

I have an html page.
I am making an ajax call to a link and i get the html data which contains sId and sTmp values in it. I need to get all the values of sId and sTmp as key value pairs in my html page.
(There are about 106 sId's and sTmp values)
How to get all the values of sId and sTmp as key value pairs ?
Code of html data which contains sId and sTmp values:-
sId = "1407900387";
if ((3 == 13) && "")
{
var sLinkLocation = sAddJavascriptEscapes('');
sUrl = "OpenInformationItemLocation(\"" + sLinkLocation + "\", );";
}
else
sUrl = "OpenHeaderLinkFromTable(\"http://172.220.1.4/QPR2014-1/Portal/QPR.Isapi.dll?PGPLUGIN&*24&SES=mWh8OHy43bW3LC5kC9yM-A&FMT=p&SKIN=portal&LAN=en%2c1&MODELID=1470448858&OBJECTID=1407900387\",\"http://172.220.1.4/QPR2014-1/Portal/QPR.Isapi.dll?PGPLUGIN&*24&SES=mWh8OHy43bW3LC5kC9yM-A&FMT=p&SKIN=portal&LAN=en%2c1&MODELID=1470448858&OBJECTID=1407900387\",\"" + sId + "\");";
window._sDefaultLink = window._sDefaultLink || sUrl;
RC("<table border='0' cellpadding='0' cellspacing='0'><tr><td><a id=\"a" + sId + "\" href='javascript:" + sUrl + "' title='" + sTmp + "'><img src='http://172.220.1.4/QPR2014-1/qprsoftware/pg/images/icn_subprocess.gif' title='" + sTmp2 + "'> " + sTmp + "<\/a>" + sTools + "</td></tr></table>", sTmp);
sTmp = "";
if (sTmp != "")
sTmp = "<table border='0' cellspacing='0' cellpadding='0'>" + sDecodeURI(sTmp) + "</table>";
RC(sTmp, "");
Code of html page:-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="jquery.js"></script>
<script type="text/javascript">
function dataRet (d){
console.log(d);
}
function ajaxreq(){
debugger
$.ajax({
url: *some link*
error: function(jqxhr) {
alert(jqxhr.responseText); // #text = response error, it is will be errors: 324, 500, 404 or anythings else
},
dataType:'html',
success: function(data) {
alert(data);
console.log(data);
var decoding = sDecodeURI(data);
console.log(decoding);
},
type: 'post'
})
function sDecodeURI(vsStr)
{
debugger
try {
if (typeof(vsStr) !== "string")
return vsStr;
var slSplit = vsStr.split('%u');
if (slSplit.length === 1)
return decodeURIComponent(vsStr);
var sResult = new StringBuilder(decodeURIComponent(slSplit[0]));
for (var i = 1; i < slSplit.length; ++i) {
var sTmp = slSplit[i];
var len = sTmp.length;
if (len < 4)
sResult.append("%u" + sTmp);
else {
var charCode = sTmp.substr(0, 4);
sResult.append(String.fromCharCode(parseInt(charCode,16)));
sResult.append(decodeURIComponent(sTmp.substr(4, sTmp.length-4)));
}
}
return sResult.toString();
}
catch (e) {
// Fallback to old-style encoding
return unescape(vsStr);
}
}
;
}
</script></head>
<body>
<input onclick="ajaxreq()" type="button" value="Click me to load info!"></input>
<div id="info"></div>
</body>
</html>

How do I see what data AJAX is passing

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.

AJAX is not passing data via POST to its intended URL

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

jQuery don't work on phonegap

This code works perfectly in different browser (Chrome, Firefox, Safari), but in PhoneGap, when I click the button 'login' the logme function does not work.
I have tried to replace click by vclick,
or //ajax.gooogleapis.com/.... by file://ajax.goo.... but it does not work.
Do you have an idea of the problem?
thanks
<!DOCTYPE html>
<html>
<head>
<style>
* { font-family: Verdana, Geneva, sans-serif; line-height: 30px }
.title { background:#333; color: white; }
.success { color: #060; font-weight: bold; }
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var apiURL = "localhost/wordpress/api/";
var noncestring = "get_nonce/?";
var authstring = "user/generate_auth_cookie/?";
var poststring = "posts_auth/create_post/?";
var username, password;
var nonce, cookie;
$('document').ready(function(){
$('#logme').click(function() {
jQuery(function($) {
username = document.forms["logme"].elements["username"].value;
password = document.forms["logme"].elements["password"].value;
});
getNonce("user", "generate_auth_cookie");
function getNonce(controller, method) {
$.getJSON(apiURL + noncestring + "controller=" + controller + "&method=" + method, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "nonce") {
nonce = val;
$('.status').append("<br>Nonce acquired for controller '" + controller + "', method '" + method + "': " + val);
// Add additional methods here. Could make this a switch statement.
if (method == "generate_auth_cookie")
createAuthCookie();
if (method == "create_post")
createPost();
getid();
}
});
});
}
function createAuthCookie() {
$('.status').append("<br>creating -> auth cookie with nonce " + nonce);
var authCookieURL = apiURL + authstring + "nonce=" + nonce + "&username=" + username + "&password=" + password;
$.getJSON(authCookieURL, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "cookie") {
cookie = val;
$('.status').append("<br>Auth cookie -> acquired! value: " + val);
// Get a new nonce to create the post:
getNonce("posts_auth", "create_post");
}
});
});
}
function getid() {
$('.status').append("<br>Get -> id");
var authCookieURL = apiURL + authstring + "nonce=" + nonce + "&username=" + username + "&password=" + password;
$.getJSON(authCookieURL, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "user") {
user = val;
$('.status').append("<br>id -> acquired! value: " + user.id + "<br>username -> acquired! value: " + user.username + "<br>nicename -> acquired! value: " + user.nicename + "<br>email -> acquired! value: " + user.email + "<br>avatar url -> acquired! value: " + user.avatar);
// Get a new nonce to create the post:
getNonce("posts_auth", "create_post");
}
});
});
}
function createPost() {
$('.status').append("<br>creating -> post with nonce: " + nonce);
var cookiepart = "&cookie=" + cookie;
var postContent = "&status=publish&title=NonceTest&content=test+test&author=Alex&categories=Demos&tags=test,api,json";
$.getJSON(apiURL + poststring + "nonce=" + nonce + cookiepart + postContent, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "status") {
console.log("status value: " + val);
if (val == "ok") {
$('.status').append("<br><span class='success'> -> A new post was successfully created.</span>");
}
}
});
});
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<div class="title">Json Test 3</div>
<form id="loginForm" method="get" accept-charset="utf-8" name="logme">
<fieldset>
<div data-role="fieldcontain">
<label for="email"> Username </label>
<input type="text" name="username" id="email" value="">
</div>
<div data-role="fieldcontain">
<label for="password"> Password </label>
<input type="password" name="password" id="password" value="">
</div>
<input type="button" data-theme="g" name="submit" id="logme" value=" Login ">
</fieldset>
</form>
<div class="status">Getting nonce for auth cookie...</div>
</div>
</body>
</html>
Load jquery as 'http://'. I had this problem too when trying to load remote files with Phonegap (or Ionicframework), just '//' does not seem to work.
Your jquery works 100%. The problem is your apiURL is not from external server, its just from localhost. try test on external server. don't use localhost.

Categories