AJAX data not passing to PHP - javascript

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

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

How to send javascript array to php?

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

Can't get jQuery var to PHP

I am trying to get a jQuery var into PHP so I can use it with mysql. I have searched everywhere but nothing seemed to solve it.
I have the following jQuery code:
$('.eventRow').click(function(){
var eventID = this.id;
$.ajax(
{
url: "index.php",
type: "POST",
data: { phpEventId: eventID},
success: function (result) {
console.log('success');
}
});
$('#hiddenBox').html(eventID);
console.log(eventID);
});
If I run this, the ID is shown in both #hiddenBox and in the console.log. The console also says "Succes" from the Ajax.
I am trying to get it in the php file:
$value = $_POST['phpEventId'];
echo "<div class = 'showNumber'>"."Nummer: ".$value."</div>";
It just says: Nummer:
It also gives no error whatsoever.
Thanks for your help!
Try
var eventID = $(this).attr('id');
Where this id comes from in your code ?
Passing it as JSON often gets the results I'm looking for. The server will interpret the JSON object as POST variables:
$.ajax({
url: "index.php",
type: "POST",
data: JSON.stringify({phpEventId: eventID}),
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log(result);
}
});

GET var from php to use in javascript function

i want to get a var from a php script and use it in a function .. so if i call the var simply with $.get (and document.write) i got an result but how can i integrate this into a function ?
$.get( 'http://www.domain.de/content/entwicklung/verdienst.php', function(verdienst_php) {
//document.write(verdienst_php);
});
function sendview () {
var datastring = {uid : uid_clear, verdienst : verdienst_php};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}
only put the function into the $.get part didnt work
if i didnt use $.get and write in datastring like
verdienst: 1000
it works
any suggestions ?
kind regards Dave
Assuming you are returning exactly what you want from the server, store it in a variable and reference the variable in the other Ajax call.
var verdienst_php;
$.get( 'http://www.domain.de/content/entwicklung/verdienst.php',
function(response) {
verdienst_php = response;
});
function sendview () {
var datastring = {uid : uid_clear, verdienst : verdienst_php};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}
If you want the GET call to happen when the click happens, than you just need to put the post code inside of the GET success callback.
You have to make an extra ajax call to get php variable, you can do it this way :-
function sendview () {
var datastring = {uid : uid_clear, verdienst : getPHPVar('verdienst_php')};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}
function getPHPVar(varname){
var returnValue = null;
$.ajax({
url: 'yourphpurl.php',
async: false,
type: 'post',
data:{
task:'getvar',
varname: varname
},
success: function(response){
returnValue = response;
}
});
return returnValue;
}
and in PHP it will look like:
<?php
if($_POST['task'] == 'getvar'){
echo $$_POST['varname'];
}
Also, I think it's actually not needed cause you are getting php variable using ajax, and again using it in another ajax call. so Why don't you just do it in php ?

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