Pass Array FROM Jquery with JSON to PHP - javascript

hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy

Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);

var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});

Try this :-
$data = json_decode($_POST['data'], TRUE);

I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});

Related

Issue transferring data from ajax to PHP

I'm trying to send an associative array of key-value pair from client(javascript) to server(php). The size of the array or the values are not fixed. Need to forward the user selected options from one page to another. Not using forms
Tried using ajax, but php does not receive the array correctly. Using php7, jquery 2.4.1, sql server, javascript
javascript/jquery
var contributeArr = {};
$(document).on("change", ".contribute_txt", function() {
// some other code
contributeArr[this.id] = this.value;
});
$('#contri_submit').click(function(e) {
e.preventDefault();
var error = false;
var contributeArray = JSON.stringify(contributeArr);
var url = 'chapter.php';
var formData = new FormData();
if (error == false) {
formData.append("contributeArray", contributeArray);
}
else {
console.log("Something went wrong. Check your code.");
}
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(result) {
window.setTimeout(function() {
window.location.href = url;
}, 2000);
},error: function(xhr,request,error) {
alert(error);
}
});
return false;
});
php
foreach ($_POST['contributeArray'] as $key => $value) {
$_SESSION['contribution'][$key] = $value;
}
print_r($_SESSION['contribution']);
print_r($_POST);
Sample data from console log:
contributeArray, {"LECH":"10","MASC":"20","PMEM":"30","LVME":"50"}
note: not sure what // some other code is... assuming you have everything correct there for your purposes
and assuming you are validating your $_POST data...
var contributeArr = {};
$(document).on("change", ".contribute_txt", function() {
// some other code
contributeArr[this.id] = this.value;
});
$('#contri_submit').click(function(e) {
e.preventDefault();
var my_url_value = 'chapter.php';
var real_url_to_ajax_app = 'https://realdomain.com/realfile.php';
$.ajax({
type: "POST",
url: real_url_to_ajax_app,
data: contributeArr,
success: function(result) {
window.setTimeout(function() {
window.location.href = my_url_value;
}, 2000);
},error: function(error) {
console.log(error);
}
});
return false;
});
in your PHP:
// assuming you are initializing $_SESSION['contribution'] per your needs
foreach ($_POST as $key => $value) {
// validate key/value here
$_SESSION['contribution'][$key] = $value;
}
echo 'some helpful response';
exit; // required
Please use json_decode and include latest jQuery.
I can solve your code if you did not solved yet

AJAX returns only last array item

I want to create async AJAX query to check server status when web page finish loading. Unfortunately when it comes to data display from processed PHP, I receive only single value.
JS:
<script>
window.onload = function() {
test();
};
function test()
{
var h = [];
$(".hash td").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('.result').replaceWith(data);
}
});
}
});
}
</script>
PHP:
<?php
require_once ('inc/config.php');
require_once ('inc/libs/functions.php');
if (isset($_POST['hs'])) {
$hash = json_decode($_POST['hs']);
serverstatus($hash);
}
function serverstatus($hash) {
$address = DB::queryFirstRow("SELECT address,hash FROM servers WHERE hash=%s", $hash);
$address_exploded = explode(":", $address['address']);
$ip = $address_exploded[0];
$port = $address_exploded[1];
$status = isServerOnline($ip,$port);
if ($status) {
$s = "Online $ip";
} else {
$s = "Offline";
}
echo $s;
}
?>
I embed result from PHP to a table row. I see that AJAX iterating over the array, but all rows receive same value (last checked element in array).
$('.result') matches all elements with the class result. replaceWith will then replace each of them with the content you provide.
If you want to only affect the .result element within some structure (perhaps the same row?), you need to use find or similar:
function test()
{
var h = [];
$(".hash td").each(function(){
var td = $(this); // <====
var hash = td.closest('#h').text();
var result = td.closest("tr").find(".result"); // <====
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
result.replaceWith(data); // <====
}
});
}
});
}
Obviously the
var result = td.closest("tr").find(".result"); // <====
...will need to be tweaked to be what you really want it to be, but that's the idea.
This line in your question suggests an anti-pattern:
var hash = $(this).closest('#h').text();
id values must be unique in the document, so you should never need to find the one "closest" to any given element. If you have more than one id="h" element in the DOM, change it to use a class or data-* attribute instead.
Thank you all for help. My final, obviously very dirty but working code:
function testServerPage()
{
var h = [];
$(".hash li").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
//async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('#' + hash).replaceWith(data);
}
});
}
});
return false;
}
I just added dynamic variable to element:
success: function(data) {
$('#' + hash).replaceWith(data);
}

Using AJAX to post data into API

I have a script that uses AJAX to comunicate with PHP based API.
First part loads trade history:
$(document).ready(function () {
var orders = $('#History ul');
var user = "<?php echo $user; ?>";
$.ajax({
type: "GET",
url: "api.php",
data: {
user: user
},
success: function (response) {
console.log(response);
var res = JSON.parse(response);
$.each(res, function (index, value) {
console.log(value);
if(value['PL']>=0){
orders.append("<li style=\"color:green;\">" + value['User'] + "</li>");
}else{orders.append("<li style=\"color:red;\">" + value['User'] + "</li>");}
});
}
});
Second part posts a trade to database:
$("#submit").click(function(){
//event.preventDefault();
var oPrice = newOrder.elements["oPrice"].value;
var cPrice = newOrder.elements["cPrice"].value;
var oType = newOrder.elements["oType"].value;;
var oSymbol = newOrder.elements["oSymbol"].value;
var oAmount = newOrder.elements["oAmount"].value;
var json ={
'user': user,
'oPrice': oPrice,
'cPrice': cPrice,
'oType': oType,
'oSymbol': oSymbol,
'oAmount': oAmount};
alert(JSON.stringify(json)); //---check zda je naplněný
$.ajax({
type: "POST",
url: "api.php",
data: json,
success: function (response) {
alert(response);
}
});
});
The problem is, that when i press the button and send json, its missing the 'user' data and looks like this:
TraderBook.php?oPrice=1&cPrice=1&oType=LONG&oSymbol=1&oAmount=1
I have no idea why does ajax exclude it. The json variable has it filled out
I think your problem might be here
$(document).ready(function () {
var user = "<?php echo $user; ?>";
var is the JS scoping declaration. So you're limiting your user value to just the anonymous function being triggered by the page DOM load completing. What you should do is try scoping it outside the function
var user; //global scope
$(document).ready(function () {
user = "<?php echo $user; ?>";
This way, when your $("#submit").click(function() fires, there's a value to feed into your script.
I was wrongchecking the problem a mistook data from a form for the json. Problem was inside the API --> There was a tabulator in a SQL command..
Thanks to everyone for suggestions.

Sending a JavaScript array to PHP via POST

I am trying to send a JavaScript array to a PHP file via POST.
JS:
var songlist = ['song1', 'song2', 'song3'];
var sendData = function(){
var data = songList.join(',')
$.post('test.php', {data: data}).always(function() {
window.location = 'test.php';
});
}
sendData();
test.php:
<?php
$songData = $_POST['data'];
$songData = explode(',', $songData);
print_r(array_values($songData));
?>
when sendData(); directs me to test.php I get:
Notice: Undefined index: data
Why doesn't the data variable have any value when I try to print or use it?
That's not how POST request works. Read more about Ajax, but for now, that's how you should do it.
var songlist = ['song1', 'song2', 'song3'];
var sendData = function() {
$.post('test.php', {
data: songlist
}, function(response) {
console.log(response);
});
}
sendData();
// test.php
<?php
$songData = $_POST['data'];
print_r($songData);
?>
1) $.post('url') - Ajax request is done by $.post() method and you have given "testing.php" as url which is invalid.
2) window.location = 'test.php' - This is used for redirecting to specific page and you have redirected to 'test.php' without any parameter/data. Thats why its showing "Notice: Undefined index: data"
3) Try to understand how ajax works. Follow it -
var songlist = ['song1', 'song2', 'song3'];
var sendData = function() {
$.post('test.php', {
data: songlist
}, function(response) {
console.log(response);
});
}
sendData();
// test.php
<?php
if(isset($_POST)){
if(isset($_POST['data'])){
$songData = $_POST['data'];
print_r($songData);
}}
?>

I don't understand AJAX callbacks

I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});

Categories

Resources