not able to pass value using ajax in php file - javascript

I am not able to pass value using ajax in php file.
Corrected Code
<script>
$("body").on('change', '#area', function () {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'box.php',
type: 'POST',
data: {option: selectedValue},
success: function () {
console.log("Data sent!");
}
});
});
</script>
here the php code
<?php $val=$_POST['option'];echo $val; ?>

There are a few problems here:
It should be url, not rl. Also, you have type: POST' with it ending in a ', but no starting '.
It should be type: 'POST'.
It should then look like this:
$("body").on('change', '#area', function() {
var selectedValue = this.value;
$.ajax({
url: 'box.php',
type: 'POST',
data: {
option : selectedValue
},
success: function() {
console.log("Data sent!");
}
});
});
If you want to view your data on the same page after (as on box.php, you are echo'ing the value.), you can do this:
success: function(data) {
console.log(data);
}
This will then write in the console what option is, which is the value of #area.

Try the following code
$("body").on('change',function(){
$.ajax({
URL:<you absolute url>,
TYPE:POST,
Data:"variable="+$("#area").val(),
Success:function(msg){
<do something>
}
});
});
Hope this will help you in solving your problem.

Your just miss ajax method parameter spelling of 'url' and single quote before value of type i.e. 'POST'. It should be like
$.ajax({
url: 'box.php',
type: 'POST',
data: {option : selectedValue},
success: function() { console.log("Data sent!");}
});

Related

Why is my AJAX data empty, even if the output of the variable before ajax is right?

$(document).ready(function () {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id); //<-------
$.ajax({
url: "m/a/a.class.php",
method: "POST",
data: {pId: p_id},
dataType: "text",
success: function (data) {
console.log(data); //<------
}
});
});
I want to pass the my data to PHP, but when I am trying to use it for a query it is empty, so I added the console.log before and after the AJAX script.
Before it gives me the right value ("id") of the selected product, for example "9", but the console.log in the AJAX script just returns an empty value "".
What is the problem with this? Do I miss-understand the code of AJAX?
UPDATE:
case 'linie':
if (isset($_POST['pId'])){
$t = $_POST['pId'];
}
$sql = 'SELECT l.id, l.bezeichnung as bezeichnung '
. 'FROM l "
. 'LEFT JOIN p ON p.id=l.p_id '
. 'WHERE l.p_id ="'.$t.'" AND l.deleted=0 AND p.deleted=0 '
. 'ORDER BY l.bezeichnung ';
break;
This is the relevant part of my PHP code where I try to get the previous input.
UPDATE 2:
$(document).ready(function () {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
method: "POST",
url: "m/a/a.class.php",
data: { pID: $('#p').val() },
async: true,
dataType: 'text', (...)
When I changed it to this it worked for me :)
I guess you are playing data data.
This data
data: {produktId: p_id},
is not same as this data
success: function (data) {
Better way of writing it will be
$("#produkt").change(function () {
var p_id = $(this).val();
console.log(p_id); //<-------
$.ajax({
url: "modules/ausschuss/ausschuss.class.php",
method: "POST",
data: {produktId: p_id},
dataType: "text",
success: function (response) {
console.log(response); //<------
}
});
});
Notice the success block parameter
So this data data: {produktId: p_id}, is detail which you pass to an ajax call.
And the ajax call may or may not return response which is returned in success block as response.
Example

How to intercept POST data with Javascript

I am using this javascript function to send data to my php script (via POST) I am then using this information to retrieve data from my database and I would like to reuse the information retrieved in my JavaScript code.
Here is my code :
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function() {
// HERE I would like to inctercept the data that my php script put in myFunctions.php produces and use it to generate content;
}
});
});
So basically, when clicking on the button #validerChoixDeCours, my code sends some data to myFunctions.php which generates a response stored in a php variable and I want to use that response in my JS code.
Thank you in advance for your help :)
Its actually quite easy!
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(e) {
e contains the response from the php script
}
});
});
The first parameter of success contains the response from the request. so, in this case, the 'e' variable contains the output which you can use.
Add data variable
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(data) {
alert(data);
}
});
});
make sure your server side code look like this
<?php
$output = "Any String or Array";
echo json_encode($output);
?>

Passing GET parameter with ajax

I have a link that I want to use with ajax. Here is the link:
<a class="export_csv" href="ajax/createCSV.php?saleid=4"><img src="/img/record.csv.png"></a>
The ajax works fine but I can't pass through the GET variable. Here is the jquery:
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: $(e).data['saleid'],
success: function(results){
console.log('it worked');
}
});
});
Here is the target php page:
<?php
include('./includes/global.php');
//$cl = new Client();
//$cl->createCSV();
echo "This Works ";
$test = $_GET['saleid'];
echo $test;
echo "did work for me";
?>
try like this ,send data to php page using data option
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: "saleid=4",
success: function(results){
console.log('it worked');
}
});
})
or
$('.export_csv').on('click', function(e){
urls=$(this).attr('href');
e.preventDefault();
$.ajax({
url:urls,
type: 'GET',
success: function(results){
console.log('it worked');
}
});
}
You need to pass the data as JSON format like
data:{saleid:$(e).data['saleid']}
But actually dont know what is $(e).data['saleid']
$('#myDomSelectorId').data['saleid'] need to be JSON formated like this :
data : { saleid : $('#myDomSelectorId').data['saleid'] }
Or directly data : "saleid="+$('#myDomSelectorId').data['saleid']
Full example :
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: { saleid : $('#myDomSelectorId').data['saleid'] },
success: function(results){
console.log('it worked');
}
});
});

javascript function with jquery

I have a little function, im trying pass 2 parameters for her, but dont works...
Any idea/sugestion?
Don't have problems with ajax, i have tested this code without parameters, putting direct on the function, but calling her, not works, sorry about the terrible english!!
function myfunction(var_data, var_field)
{
$(function()
{
$.ajax
({
url : "myscriptajax.php",
type: "POST",
data: var_data + $(this).val(),
dataType:"json",
success: function(data)
{
if(data.status)
{
$(var_field).val(data.somevar);
}
}
})
})
}
$("#medicocrm").change
(function()
{
myfunction("crm=","#mediconome");
})
// edited after here for best explanation about.
That works:
$(function()
{
$("#medicocrm").change
(function()
{
$.ajax
({
url : "abertura.ajax.php",
type: "POST",
data: "crm=" + $(this).val(),
dataType:"json",
success: function(data)
{
if(data.status)
{
$("#mediconome").val(data.nome);
}
}
})
return false;
})
$("#participantematricula").change
(function()
{
$.ajax
({
url : "abertura.ajax.php",
type: "POST",
data: "matricula=" + $(this).val(),
dataType:"json",
success: function(data)
{
if(data.status)
{
$("#participantenome").val(data.nome);
}
}
})
return false;
})
\i tried this with first answer...
and that not works:
function verifica(dados,campoid,camponome){
$.ajax({
url : "abertura.ajax.php",
type: "POST",
data: dados + campoid,
dataType:"json",
success: function(data){
if(data.status){
$(camponome).val(data.nome);
}
}
});
return false;
};
$("#medicocrm").change(function(){
verifica("crm=",this.value,"#mediconome");
});
$("#participante_id").change(function(){
verifica("id=",this.value,"#participante_nome");
});
Just do a revamp.
function myfunction(var_data, var_field, elementValue){
$.ajax({
url : "myscriptajax.php",
type: "POST",
data: var_data + elementValue,
dataType:"json",
success: function(data){
if(data.status){
$(var_field).val(data.somevar);
}
}
});
};
$("#medicocrm").change(function() {
myfunction("crm=","#mediconome", this.value);
});
Here we removed the DOMContentLoaded listener and passed the value of the element through to the function..
You can use $(this).val(); in place of this.value whatever floats your boat.
You have a whole lot of wrappers going on, and your use of $(this) is likely breaking it. Something like this should work:
function myfunction(var_data,$var_field,whatever_this_is_val){
$.ajax({
url : "myscriptajax.php",
type: "POST",
data: var_data + whatever_this_is_val,
dataType:"json"
}).done(function(data){
if(data.status){
$var_field.value = data.somevar;
}
});
}
$("#medicocrm").on('change',function(){
myfunction("crm=",this,document.getElementById(whatever_this_is).value);
});
Changes:
Unnecessary wrappers removed
Passing of $(this) ... you need to specifiy it
Cleanup syntax to modern use of .done().
Using vanilla JS where easily applied
You should also consider explicitly declaring the page that it calls to be JSON, rather than saying dataType:'json' in your call. Its bulletproof this way, and less work performed on all sides.
EDIT
If you are really just passing the value of the item changed, easiest way to do it:
function myfunction(var_data,$var_field){
$.ajax({
url : "myscriptajax.php",
type: "POST",
data: var_data + $var_field.value,
dataType:"json"
}).done(function(data){
if(data.status){
$var_field.value = data.somevar;
}
});
}
$("#medicocrm").on('change',function(){
myfunction("crm=",this);
});
That way worked!!!!!! With many wrappers, but... Worked!
callajax = (function(origem,dados,campo)
{$.ajax({
url : "abertura.ajax.php",
type: "POST",
data: origem + "=" + dados,
dataType:"json",
success: function(data){
if(data.status){
$(campo).val(data.nome);
}
else{
$(campo).val("");
alert('Não encontrado');
}
}
})
});
$(function(){$("#medicocrm").change
(function(){
callajax('crm',this.value,"#mediconome");
});
});
$(function(){$("#participantematricula").change
(function(){
callajax('matricula',this.value,"#participantenome");
});
});
$(function(){$("#prestadorcodsoc").change
(function(){
callajax('codsoc',this.value,"#prestadornome")
});
});

Variable not working in simple Ajax post

Can't seem to get the variable getID to work. I'm trying to change the html of the div. I know that the variable has the right value.
$('.cardid').change(function() {
var getID = $(this).attr('value');
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: "id="+getID,
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
});
Write data in $.ajax as data: {id : getID}, instead of data: "id="+getID,
Use val to get the value of an input :
var getID = $(this).val();
As you're making a POST request, you should also use the data argument to let jQuery properly send the value :
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: {id:getID},
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
You can try this:
$('[id="'+getID+'"]').html(data);
and yes you should pass it this way:
data:{id:getID}

Categories

Resources