value is not updating of session array to json array via ajax - php

I have a session array $_SESSION['Cartquantity'] . In php file on line no 200 I am storing this array in a variable $QtyArray
$QtyArray = $_SESSION['Cartquantity'] ;
then I am encoding the array in json to use it on js file
echo "var cartQty = " . json_encode($QtyArray) . ";" ; (on line 201)
Now via the AJAX I am updating the session array on line no 120 in the same way
$QtyArray = $_SESSION['Cartquantity'] ; (on line 120)
echo "var cartQty = " . json_encode($QtyArray) . ";" ; (on line 121)
This is my javascript code to call file
$.ajax({
url:'index.php',
cache:false,
datatype:'json',
data:{ q: "add_card", item_id: id, item_qty: qty,stop:'1' },
success:function(data){
$("#cart_quanity").html(parseFloat($("#cart_quanity").html()))
}
});
return false ;
array is clearly updating because I can see this on console of firebug. But when I am getting this value on js file value is not changing. While if I reload the page where I update this value via ajax and then go to view quantity it is changing. Why is that happening ?
Please help!!!

Your server-side handler for the ajax request should just return the data literal itself.
On the client parse that data and then handle it there - not as a "complete" javascript snippet but just as an data object. JQuery supports you with the parsing part. Just let it auto-guess the type of the response or define it when calling $.ajax or $.post.
$.post(url, data, function(response) {
// you cann assume response to be an object
// containing the data from the json-response of the server
}, "json");
self-contained example (doing nothing useful):
<?php
if ( isset($_POST['foo']) ) {
// the client requests a new item
$rv = array(
'status'=>'ok',
'value'=>rand(1,10)
);
header('Content-type: application/json');
echo json_encode($rv);
die;
}
?>
<html>
<head>
<title>...</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var total = 0;
$(".foo").on("click", function() {
$.post("?", { foo: true }, function(data) {
if ( data.status && "ok"==data.status ) {
var newValue = data.value;
total += newValue;
$("#output").append("+ "+newValue+" = "+total+"<br />");
}
}, "json");
});
});
</script>
</head>
<body>
<button class="foo">click</button>
<div id="output">0<br /></div>
</body>
</html>

Related

$.post doesnt work when datatype declared

I noticed that the following code doesn't work. When I remove , "json"); at the end of it, it works but i just get failure. I followed it to jquery spec on the site. Any idea why the $.post method won't work/enter?
The reason i know it wont enter $.post is because alert(form.serialize()); doesnt get called.
In my PHP i am returning the following when it posts:
$arr = array('status' => 'SUCCESS');
echo json_encode($arr);
exit();
This is my ajax below:
var form = $('#lines');
$.post('', form.serialize(), function(json) {
alert(form.serialize());
if(json.status === 'SUCCESS') {
alert(json);
console.log('success');
} else {
alert(json);
console.log('failure');
}
}, "json");
If I remove the json part at the end, it just returns the entire HTML of the page.
Your response is probably not json. If you remove ,"json", it works but post return string datas so your code can't work (json.status on string won't work). If you put ,"json", then it won't probably work if return is not proper json.
What you can do : leave "json" in the end, as this is what you want, add console.data(json) ; and console.data(typeof json) ; just at start of your success function.
Forget about alert, first it stop your script, and it's not as precise as console. Use console when you can.
I can suggest you to write it like this to make it more readable :
console.log('form.serialize()',form.serialize()) ;
var post = $.ajax({
method : 'POST',
url : '',
data : form.serialize(),
dataType : "json"
});
post.done(function(json){
console.log('success',json) ;
console.log('typeof json',typeof json) ;
if(json.status === 'SUCCESS') {
console.log('success');
} else {
console.log('failure');
}
}) ;
post.fail(function(data){
console.log('fail',data) ;
alert('post fail') ;
}) ;
Here is my complete php file index.php. Structure should looks like your one. Just note the top part where i make sure than when i have post data, i echo only the json and returns, so nothing else is sent (like your exit).
<?php
if ( isset($_POST['name']) )
{
echo json_encode(array('status' => 'SUCCESS')) ;
return false ;
}
?>
<form>
<input type="text" name="name" />
<input type="button" />
</form>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
jQuery('input[type="button"]').on('click',function(){
var form = jQuery(this).closest('form') ;
console.log('form.serialize()',form.serialize()) ;
var post = $.ajax({
method : 'POST',
url : '',
data : form.serialize(),
dataType : "json"
});
post.done(function(json){
console.log('success',json) ;
console.log('typeof json',typeof json) ;
if(json.status === 'SUCCESS') {
console.log('success');
} else {
console.log('failure');
}
}) ;
post.fail(function(data){
console.log(this) ;
console.log('fail',data) ;
alert('post fail') ;
}) ;
}) ;
</script>
You need to specify the headers in your php code and tell jQuery that a "json" response is on the way.. here is the correct php code
header('Content-Type: application/json');
$arr = array('status' => 'SUCCESS');
echo json_encode($arr);
exit();
notice the line that sends json headers, try it now and it'll work

How to ouput JSON in javascript?

I am trying to print the results of a json object from a php query into javascript.
So basically the query results looks like:
{"points":
[{"lat":40.766696929932,"long":-73.990615844727},
{"lat":40.688514709473,"long":-73.96475982666},
{"lat":40.714504241943,"long":-74.005630493164},
{"lat":40.704719543457,"long":-74.009262084961},
{"lat":40.693260192871,"long":-73.968894958496},
{"lat":40.760955810547,"long":-73.967247009277},
]}
When i try to get the php variable (using AJAX) containing the json object i get:
VM62:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
I tried googling to see how the error relates to my code but i still don't get it.
Can someone explain to me how to get the json in javascript?
<?php
$connect = pg_connect("host=127.0.0.1 dbname=datab user=thomas password=iamtom") or die("Could not connect: ");
$result = pg_query($connect,"SELECT geometry FROM table");
if (!$result){
echo '{"error":"no results"}';
}
$points= array();
while($row = pg_fetch_array($result)){
$coordinate = json_decode($row['geometry'])->coordinates;
$p = new stdClass;
$p->lat = $c_2[0];
$p->long = $c_1[1];
array_push($points, $p);
}
$output = new stdClass;
$output->points = $points;
echo json_encode($output);
pg_close($connect);
?>
Here is my HTML/JS:
<html>
<head>
<title>Simple Map</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$.ajax({
type: "GET",
dataType: "JSON",
url: "dab.php",
data: {
sataVariable: "here is some data send with GET method"
},
success: function(data) {
var j = JSON.parse(data);
document.writeln(data); // attempting to take the coordinates and store it in a variable
},
error: function(data) {
console.log(data);
}
});
</script>
</head>
<body>
</body>
</html>
Because you're feeding dataType: "JSON" into your call to jQuery.ajax() the data retrieved from the AJAX call is automatically being parsed from JSON to a JavaScript object (though I'd switch "JSON" to "json" to match the documentation):
"json": Evaluates the response as JSON and returns a JavaScript object.
Don't manually parse the response again using JSON.parse() in your success handler; just work directly with data.
Now that you have your data in a JavaScript object called data you can interact with it, e.g.
for (var i = 0; i < data.points.length; i++) {
console.log(data.points[i].lat, data.points[i].long);
}

Send data from localStorage via AJAX to PHP and save it in an HTML file

I want to send fields data from a form to a file via AJAX and I found this solution online: http://techglimpse.com/pass-localstorage-data-php-ajax-jquery/
The only problem is that I have multiple fields instead of a single field and I want to save the output (localStorage) in an HTML (or any other format) file instead of showing it in an #output div.
How can I do that?
You can see my work that I've done till now here: Save form data using AJAX to PHP
And here's my HTML/JS code: http://jsbin.com/iSorEYu/1/edit & PHP code http://jsbin.com/OGIbEDuX/1/edit
PHP:
<h1>Below is the data retrieved from SERVER</h1>
<?php
date_default_timezone_set('America/Chicago'); // CDT
echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
$current_date = date('d/m/Y == H:i:s ');
print "<h2>Server Time : " . $current_date . "</h2>";
$dataObject = $_POST; //Fetching all posts
echo "<pre>"; //making the dump look nice in html.
var_dump($dataObject);
echo "</pre>";
//Writes it as json to the file, you can transform it any way you want
$json = json_encode($dataObject);
file_put_contents('your_data.txt', $json);
?>
JS:
<script type="text/javascript">
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input[type=text]").val("");
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: fields,
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
</script>
NOTE: Replace the file format of your_data file to html in the PHP code if you want your JSON data in HTML format.
You are overcomplocating things. The check for localStorage can be way simpler (other options). jQuery has a serialze() function that takes all form elements and serializes it. You can store them under "eloqua-fields" so you can find it again. No need to do some fancy random retrival.
I'd like to add that not all of you code makes sense. Why use localstorage if you clear it every time the DOM is ready? Your validation does not abort the sending process if there are errors but I assume you just want to play around with stuff.
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input").val(""); //this ONLY clears input fields, you also need to reset other fields like select boxes,...
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: {data: fields},
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
For the server part if you just want to store your data somewhere.
$dataObject = $_POST['data'];
$json = json_decode($dataObject);
file_put_contents('your_data.txt', $json) ;

Use parts of AJAX response in different divs

I want to send this AJAX request:
function sumMonthly() {
var cur_month = $('#month option:selected').attr("value");
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
data: {action: ["get_sum_income", "get_sum_expense", "get_cash_remaining"], cur_month:cur_month}
});
request.done(function(response){
$('#sum_income').html('<h1 class="positiveNum float-right">$' + response.get_sum_income + '</h1>');
$('#sum_expense').html('<h1 class="float-right">$' + response.get_sum_expense + '</h1>');
});
request.fail(function(jqxhr, textStatus){
alert("Request failed: " + textStatus);
});
};
and somehow access the return response, but I'm not sure how to access only a certain part of the response and put it in one div, then put another part in another div. Here's some of my PHP:
if(isset($_POST['action']) && in_array("get_sum_income", $_POST['action'])) {
//do stuff here, put result in $i;
if(!empty($i)) {
echo $i;
} else {
echo '$0.00';
};
};
This is not a real "answer" to your problem, but I can't write what I want in a comment.
You'll need to work on your PHP to consolidate the code and make an array something like this:
$json = array
(
'varname1' => $variable1,
'varname2' => $variable2,
'varname3' => $variable3,
'varname4' => $variable4,
'varname5' => $variable5
);
$jsonstring = json_encode($json);
echo $jsonstring;
Then on client side you can do something like:
.done(function(response) {
$('#div1').text(response.varname1);
$('#div2').text(response.varname2);
$('#div3').text(response.varname3);
$('#div4').text(response.varname4);
$('#div5').text(response.varname5);
});
Again, this is not a specific solution, but it should get you started.
I always write my php, then run it without the client, grab the output on the screen and submit it to jsonlint.com to make sure it's json.

Passing AJAX GET results to location

Here's my problem
<script type="text/javascript"><!--
$('#button-confirm').bind('click', function() {
$.ajax({
type: 'GET',
url: 'index.php?route=payment/bitcoinpayflow/confirm',
success: function(url) {
location = '<?php echo $continue;?>';
}
});
});
//--></script>
The url returns this:
https://bitcoinpayflow.com/ordersArray // note the lack of space between orders and array. Is this a problem? If it is, I can get it to display in JSON notation with some fiddling.
(
[order] => Array
(
[bitcoin_address] => 1DJ9qiga2fe94FZPQZja75ywkdgNbTvGsW
)
)
Now, what I want to do is append the entry bitcoin_address to $continue '<?php echo $continue;?>'. which stands for: /index.php?route=checkout/success. so it would read /index.php?route=checkout/success&btc=1DJ9qiga2fe94FZPQZja75ywkdgNbTvGsW. it seems like it should be simple but I can't see how to do it.
The next page has a javascript function that parses the bitcoin address from the url and displays it on the page. This all works fine, I just can't get the bitcoin address to actually show!
Make it return JSON. You will reduce the amount of pain a lot. Apparently it's PHP, so just use PHP's json_encode(), then just use the JSON response to concatenate stuff to url in your 'success' function.
location = "<?php echo $location; ?>&btc=" + data.bitcoin;
...or something like that. Try console.log(data) if you're not sure what you're getting.
Set a variable in global scope and then access it within functions
<script type="text/javascript"><!--
var btcaddress = null;
$('#button-confirm').bind('click', function() {
if( isValidBtcAddress( btcaddress ) ){
Url = 'index.php?route=payment/bitcoinpayflow/confirm' + btcaddress;
}else{
Url = 'index.php?route=payment/bitcoinpayflow/confirm';
}
$.ajax({
type: 'GET',
'url': Url,
success: function(url) {
location = '<?php echo $continue;?>';
}
});
});
function someotherFunction( response ){
btcaddress = response['order']['bitcoin_address'];
}

Categories