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
Related
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);
}
So i have a php file, that prints data from a table encoded on JSON format.
This is the php file:
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo "success";
else
echo "error";
}
echo json_encode($data);
?>
This is the javascript script:
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
});
} else if (data == "error") {
alert("error");
}
}
});
});
So basically i a have where i have all items from the database select (list_all.php), and then when i click on a single item, the ID of that item is passed on the URL, and i retrieve it on the otherside with javascript. I dont use GET because this is with phonegapp, so i use a .js file called getURI.js.
First, the function gets the ID that was passed. Then it posts to the PHP file, and the PHP file will get the ID, and make the query for that single item on the database. Is successed, i wanted to store all that data on variables. But for some reason, im getting an error on the console saying
POST http://192.168.1.241:3000/proxy/http%3A%2F%2Fpedrofidalgo.pt%2Fbilapoint%2Flistar_sitio_single.php 500 (Internal Server Error)
THe server is responding correctly because others scripts on the app are working.
In PHP
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo json_encode(array('status' => true, 'data' => $data));
else
echo json_encode(array('status' => false, 'data' => $data));
?>
In Jquery
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
data = JSON.parse(data);
if (data['status']) {
$.each(data['data'], function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
} else {
alert("error");
}
}
});
});
<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.
Working in a jquery request in JSON but I have some problem to access to my data.
My request is :
$(document).ready( function () {
$("#client").change( function() {
$.ajax({
type: "GET",
url: "jsonContacts.php",
data: "q="+$("#client").val(),
success: function(data){
document.form.contactClient.options.length=0;
for(var i=0; i<data.length; i++) {
document.form.contactClient.options[i]=new Option(data[i].prenom, data[i].id, false, false);
}
document.form.contactClient.options[i]=new Option("End", i, false, false);
}
});
});
});
When I put
alert(data[1].prenom);
It gives me undefined :/
Here an example of my json :
[{"id":"1","prenom":"Maxime","nom":"Xnate"},{"id":"3","prenom":"Test_prenom","nom":"Test_nom"}]
My request displays two empty options and one option "End", so it goes well across array but can't get any data.
So do you have any idea about the access of the data ?
Thanks
EDIT :
My json encoding
$json = array();
while($contact = $requeteContact->fetch()) {
array_push($json, array("id" => $contact['idContact'],
"prenom" => $contact['CTC_Prenom'],
"nom" => $contact['CTC_Nom']));
}
echo json_encode($json);
Working :
$(document).ready( function () {
$("#client").blur( function() {
$.ajax({
type: "GET",
url: "jsonContacts.php",
data: "q="+$("#client").val(),
success: function(data){
document.form.contactClient.options.length=0;
for(var i=0; i<data.length; i++) {
document.form.contactClient.options[i]=new Option(data[i].prenom + " " + data[i].nom, data[i].id, false, false);
}
document.form.contactClient.options[i]=new Option("End", i, false, false);
}
});
});
});
Your data is probably just returned as a string. You can solve this in several ways:
1) use getJSON.
$.getJSON('http://..',{q:$("#client").val()},function(result){
})
2) Parse the string as JSON
JSON.parse(data);
3) Set the dataType to 'json'. If you do this, you will have to sett the content-type on the server side to 'application/json'. In PHP this would look like this:
header('Content-Type: application/json');
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";
});