How to send javascript array to php? - javascript

I've tried a lots of solution from so, but no one worked for me.
So I have a javascript array and i should pass it to php for upload it into mysql.
This code is in a php page, where is an editable grid. If press enter in the grid it creates a new row, with the value of the editeble cell and this value goes into the var val=[]and this should go into mysql via `php.
I've tried two kind of pass from so as you can see below
Code I have:
<script type="text/javascript" >
var dbs=0;
var val=[];
function myFunction(e) {
if(e.keyCode == 13){
var newId = (new Date()).valueOf();
var value=gridbox.cells(1,0).getValue();
gridbox.addRow(newId,value);
val.push(value);
gridbox.cells(1,0).setValue('');
gridbox.editCell(1,0);
dbs=dbs+1;
}
}
function upload(){
var jsonString = JSON.stringify(val);
/*$.ajax({
type: "POST",
url: "upload.php",
data: {'data' : jsonString},
cache: false,
success: function(){
alert("OK");
}
});*/
var jsonData = $.ajax({
url: "upload.php",
data: { 'data' : val},
dataType:"json",
async: false
}).responseText;
}
</script>
UPLOAD.PHP
And it creates new empty row in the db, so it runs, but the $data is empty
//$data = json_decode(stripslashes($_GET['data']));
$data=$_GET['data'];
// here i would like use foreach:
/*
foreach($data as $d){
echo $d;
}*/
$db_irattar = new indotekDbConnection("irattar");
for($i=0;$i<4;++$i){
$sql="INSERT INTO akt_hely(Tipus,Megnevezes)
VALUES('2','$data[$i]')
";
}
$db_irattar->Execute($sql);
$db_irattar->Close();
unset($db_irattar);
?>
Network monitor

It seems to me that you are assigning var jsonString = JSON.stringify(val); and sending val in ajax.
try
var jsonData = $.ajax({
url: "upload.php",
data: { 'data' : jsonString},
dataType:"json",
async: false
}).responseText;
Instead of
var jsonData = $.ajax({
url: "upload.php",
data: { 'data' : val},
dataType:"json",
async: false
}).responseText;
And decode the json string in php like $data=json_decode($_GET['data']);

Related

Unable to send multiple data parameters with jQuery AJAX

I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});

AJAX data not passing to PHP

I am having trouble passing AJAX data to PHP. I am experienced with PHP but new to JavaScript.
HTML / JavaScript
<input type="text" id="commodity_code"><button id="button"> = </button>
<script id="source" language="javascript" type="text/javascript">
$('#button').click(function()
{
var commodity_code = $('#commodity_code').val();
$.ajax({
url: 'get_code.php',
data: "commodity_code: commodity_code",
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
});
</script>
PHP
$commodity_code = $_POST['commodity_code'];
$result = mysql_query("SELECT description FROM oc_commodity_codes WHERE code = '$commodity_code'");
$array = mysql_fetch_row($result);
echo json_encode($array);
I know the general AJAX fetch and PHP code is working as I can manually create the $commodity_code variable and the script works fine. I think my issue lies somewhere in passing the AJAX data to my PHP script.
You forgot to add the method: 'POST' in your AJAX Call. And you have some issues with your call. Check below:
$.ajax({
url: 'get_code.php',
method: "POST", // Change here.
data: {commodity_code: commodity_code}, // Change here.
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
Or to make it simple, use the shorthand function:
$.post('get_code.php', {commodity_code: commodity_code}, function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
});
error in this line data: "commodity_code: commodity_code", .. you can simple pass the commodity_code variable..
$.ajax({
url: 'get_code.php',
method: "POST",
data: commodity_code,
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});

Suppressing and adding parameters for ajax call

I am trying to make an ajax call for two separate click events. The difference is for the second click event the variable testOne should not be part of the call and instead there would be a new variable. How should I approach this?
var varOne = '';
var varTwo = '';
var varThree = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: {
testOne: varOne,
testTwo: varOne
}
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
varOne = 'xyz123';
varTwo = '123hbz';
testAjax();
});
$('.clickTwo').click(function(){
//varOne = 'xyz123'; // I dont need this for this click
varTwo = '123hbz';
varThree = 'kjsddfag'; // this gets added
testAjax();
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
Make some like this
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data= {
varOne: 'xyz123',
varTwo: '123hbz',
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data= {
varThree : 'kjsddfag',
varTwo: '123hbz',
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
You can also do the same in other way with minimum line of code, you can call the ajax on click event and pass the data based on the element triggered the click event.
like this:
$('.ajax').click(function(e){
if($(this).hasClass('clickOne')){
var data= { varOne: 'xyz123'; varTwo: '123hbz'; }
}else{
var data= { varThree : 'kjsddfag'; varTwo: '123hbz'; }
}
$.ajax({
type: "POST",
dataType: 'json',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
e.preventDefault();
});
<div class="ajax clickOne"></div>
<div class="ajax clickTwo"></div>
In this way you can put as many conditions for different data variable.
You should be doing it like this:
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data {
varOne = 'xyz123',
varTwo = '123hbz'
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data = {
varTwo = '123hbz',
varThree = 'kjsddfag'
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
This way you absolute control over which variables are added to which ajax call. You should not use global variables unless you really need them to be global, which doesn't seem to be the case.
You can pass whatever JavaScript object to the data parameter of the ajax method.
I just wanted to add something. I often hide value inside the value attribute of the button tags to produce something like this.
I haven't been able to test this of course but I thought it was worth mentioning.
jquery:
var fields = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: fields
}).done(function(data) {
$('.result').html(data);
});
}
$('#btn').click(function(){
var varCount = 0;
var vars = $(this).val().split('|');
$.each( vars, function( key, value ) {
varCount++;
fields = fields + 'var' + varCount + '=' + value + '&';
});
fields = fields.slice(0,-1);
$(this).val('123hbz|kjsddfag');
testAjax();
});
html:
<button id="btn" value="xyz123|123hbz"></button>
A more optimized and cleaner version -
var varTwo='junk1'
var varOne='junk2'
var varThree='junk3'
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.ajaxClick').click(function(){
var data={};
if(this.classList.contains('clickOne')){
data.varOne=varOne;
data.varTwo=varTwo;
}else{
data.varThree=varThree;
data.varTwo=varTwo;
}
testAjax(data);
});
<div class="ajaxClick clickOne"></div>
<div class="ajaxClick clickTwo"></div>

Access return value of JQuery/AJAX on a different function

I want to access the returned boolean of my function on another function.
$('.asset_edit').change(function(){
var asset_id=$(this).attr('id');
var asset=$("#"+asset_id).val();
var dataString = "device="+device+"&asset="+asset;
$.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_assetCode'); ?>",
data: dataString,
cache: false,
success: function(html){
if(html)
return true;
else
return false;
}
});
});
Is there a way where I could access the "return true or return false" on my
$(".edit_tr").click(function() function?
In Javascript you just call the certain function name but in jQuery, I have no idea how to.
You can use global variable;
var global_status;
$('.asset_edit').change(function(){
var asset_id=$(this).attr('id');
var asset=$("#"+asset_id).val();
var dataString = "device="+device+"&asset="+asset;
$.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_assetCode'); ?>",
data: dataString,
cache: false,
success: function(html){
if(html) {
global_status="true";
return true;
}
else {
global_status="false";
return false;
}
}
});
});
$(".edit_tr").click(function() {
alert(global_status);
})
Here is a working demo: http://jsfiddle.net/vWkjr/1/
While testing, first click edit and see undefined, and then select value from selectbox and click edit.
insted of using return value you can add a class specifying html or not to the element it self. or you can declare a global variable and assign the value to it.
$('.asset_edit').change(function(){
var asset_id=$(this).attr('id');
var asset=$("#"+asset_id).val();
var dataString = "device="+device+"&asset="+asset;
$.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_assetCode'); ?>",
data: dataString,
cache: false,
success: function(html){
if(html)
$(this).addClass('ishtml');
else
$(this).addClass('nothtml');
}
});
});
And this class can be accessed with in other functions. like
function somefunction(){
if($('.asset_edit .ishtml ').length){
//true then do something
}else{
//false then do something
}
}

What is the proper or best way to get data from ajax?

I have this javascript code with ajax.
$('#btnCart').click(function() {
var pName = document.getElementById('prodName').value;
$.ajax({
url: 'index.php',
data: 'prdName='+pName,
success: function(data) {
$('#prod').html(data);
}
});
});
I want to get the value of pName to be returned on my php. Here's my code on my index.php side:
<?php
$prodName = $_GET['prdName'];
echo $prodName;
?>
But it returns Unidentified index: prdName.
How can I get the value from ajax to my php? Please help...
if(isset($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo $prodName;
}
You should send the data as:
data: {prdName: pName},
add this to your PHP code:
if(!empty($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo cartTable($prodName);
}
also some corrections in js:
$('#btnCart').click(function() {
var pName = $('#prodName').val();
$.ajax({
url: 'index.php',
data: {prdName:pName},
success: function(data) {
$('#prod').html(data);
}
});
});
In index.php Get the prdName value from $_POST[] global array.
to send data to index.php file add type type:'POST' in ajax code
$.ajax({
type:'POST',
url: 'index.php',
data: {'prdName': pName},
success: function(data) {
$('#prod').html(data);
}
});
or you can use $.post() method in jQuery
$.post(
'index.php',
{'prdName='+pName},
function(data) {
$('#prod').html(data);
}
});
in index.php
if(isset($_POST['prdName']){
$prodName = $_POST['prdName'];
echo $prodName;
}

Categories