upload data to server from javascript to php using ajax - javascript

I need to upload websql table to the server using ajax.
when I use indexed array or simple variable code works fine.
I cant figure out what problem is? plz help me.
thanks in advance...
here is javascript:
function upload()
{
var db = cropsap.webdb.db;
db.transaction(function (tx) {
tx.executeSql('SELECT * from survey', [],function(tx, results) {
var data = "";
var survey=[];
for(var i=0; i < results.rows.length; i++) {
var row = results.rows.item(i);
var result = [];
for(var key in row)
{
result[key] = row[key];
}
survey.push(result);
}
//alert(survey[0]['srno']);//here i get output
var url = "";
url = document.getElementById("url").value;
$.ajax({
type: "POST",
url: url,
async: true,
data: { "data": JSON.stringify(survey) },
error: function () { alert("error occured");},
success: function (data) {
alert("sucess");
alert(data);
}
});
});
});
}
php code:
<?php
$survey= json_decode(stripslashes($_POST['data']));
$len = sizeof($crop_insect_survey_details);
print(" len: ".$len);
for($i=0;$i<$len;$i++)
{
$srno = $crop_insect_survey_details[$i]['srno'];//here cant get output
$name = $crop_insect_survey_details[$i]['name'];
print("srno:".$srno);
print("name:".$name);
}
?>

Instead of using data: { "data": JSON.stringify(survey) }, You can pass your data inside data key itself.
data:JSON.stringify(survey)
dataType: "json",
contentType: "application/json; charset=utf-8",

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

Post to php file, and retrieve data with javascript

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

AJAX does what I need it to do, but errors still occur

I am writing a web page which reads data from an html table to be used on a MySQL query using PHP. This is a continuation of this question. I got AJAX send the data I need to use on to the PHP file with the code to update the information it sent. However, two errors have occured.
I get a message saying Error:Error: jQuery21405680291895882033_1487801210725 was not called
The data I send has a ":1" at the end of it, giving me an error.
How can I fix these two mistakes? Thank you so much!
JS code:
function getTableData(){
var array = [];
var headers = [];
$('#tablaListado th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#tablaListado tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
if($(this).find("textarea").length){
var costo = $(this).find('textarea').val();
arrayItem[headers[index]] = costo;
}else{
arrayItem[headers[index]] = $(item).html();
}
});
array.push(arrayItem);
});
actualizarCostos(array);
}
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: false,
jsonpCallback: jsonCallback,
cache: true,
data:{ "table_data": JSON.stringify(array[i])},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
},
traditional: true
});
}
}else{
alert("Input must be array");
}
}
function jsonCallback(data, status){
console.log(data + " " + status);
}
PHP portion:
//Added on top of the page
header('Access-Control-Allow-Origin: *');
...
function updateCosts($json){
conectar();
$array = json_decode($json, true);
echo "<script>console.log('$array');</script>";
$costo = $array["Costo"];
$sku = $array["SKU"];
$instruccion = "UPDATE articulos SET art_cost='$costo' WHERE art_SKU = '$sku'";
return ejecutarInstruccion($instruccion);
}
if(isset($_GET['table_data'])){
foreach($_GET['table_data'] as $index => $item)
{
// do something here
echo "<script>console.log('$item');</script>";
updateCosts($item);
}
// Response back - if needed
echo json_encode(array('status'=>true, 'msg'=>'Some Message'));
}
Edit:
I forgot to mention that I have tried changing 'jsonp' as 'json' on this code but I get an error saying the PHP file doesn't allow foreign data, even though I tried using header('Access-Control-Allow-Origin: *') on said file.
Your page is returning JSON, not JSONP. They aren't interchangeable. Remove the jsonp and jsonpCallback properties from the $.ajax() call, and change dataType to json:
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: true,
data: {
table_data: JSON.stringify(array[i])
},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status" + status + " \nError:" + err);
},
traditional: true
});
I'd suggest you have the following AJAX:
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
}
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:{ "table_data": JSON.stringify(array)},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
}
});
}else{
alert("Input must be array");
}
}
Then do the For-Loop on the PHP side of the server. Maybe each variable in array has a hidden parameter to know its own index, or JSON is doing something strange like displaying the number of elements in the array (in this case 1 because you're iterating over each one)

Unable to access to my json data in javascript

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

How Can I Do to my textbox autocomplete, works

I'm trying to do an autocomplete to my textbox, but it doesn't work. Follow my code.
$(function () {
var credenciada = '<%= credenciadaId %>';
xml_NomeCompleto = "";
var Nomes = "";
var retorno = '';
var count = 0;
var t = '';
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
t = $(this).find("NOMECOMPLETOUSUARIO").text();
Nomes += ["\"" + t + "\","];
});
}
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
});
The variable 't' receives all the names of my users, normally, but the autocomplete don't work.
Wait for ajax response to complete and then initialize the autocomplete because before you initialize the plugin data is not available. Also the way you are creating Nomes(source) is wrong. Declare it as an array and use push method to populate it.
Try this
var Nomes = [];
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
Nomes.push($(this).find("NOMECOMPLETOUSUARIO").text());
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
}
});

Categories

Resources