Jquery ajax parameter is undefined in the PHP script - php

I'm using jQuery Ajax to send parameters to a PHP script. Below is the Jquery ajax script
jQuery
<script>
$(document).ready(function () {
$("#builder_group").change(function () {
var selected_builder = $(this).val();
alert(selected_builder);
$.ajax({
type: 'POST',
url: 'getGroupzCode.php',
data: 'selected_builder',
datatype: 'json',
success: function (data) {
// Call this function on success
console.log(data);
var yourArray = JSON.parse(data);
console.log(yourArray);
$.each(yourArray, function (index, yourArray) {
$('#builder_group1').append($('<option/>', {
value: yourArray.id,
text: yourArray.name,
}));
});
},
error: function () {
displayDialogBox('Error', err.toString());
}
});
});
});
</script>
When I see in firebug console I see the parametr passed is correct as selected but in the PHP script I see undefined index
PHP
$builder_id=$_POST['selected_builder'];
error_log($builder_id);

data: 'selected_builder',
That is not proper format. You need:
data: { selected_builder: selected_builder }
The below indicates you're receiving a json, is that correct? If so the parameter is "dataType" like below.
dataType: 'json',
If so you are you would use this in your php file:
$encoded = json_encode($yourvariable);
echo $encoded;
Now if this wasn't the case you would call the variable in php by:
$variable = $_POST["selected_builder"];

Related

Send data to php file using ajax

I have a trouble receiving data sent using ajax in a php file. It seems that ajax sends data, cause I get a success message, but php page shows me an error "Notice: Undefined index: ab".
Here is my jquery code for sending data using AJAX:
$('#download-btn').click(function(){
var ab="abc";
$.ajax({
url:'generate_url.php',
data:{'ab':ab},
type:'post',
success:function(data) {alert("sent");},
error: function(request, status, error) {alert(request,status);}
});
}
And that's how I extract data in a generate_url.php:
<?php
$a = $_POST['ab'];
echo $a;
?>
Thanks in advance for your help!
You are missing the ); from your code. For simple POST I'll advice you to use $.post (there's nothing special about $.post, it's a shorthand way of using $.ajax for POST requests.
$('#download-btn').on('click', function(){
var ab="abc";
$.post('generate_url.php', {'ab':ab}, function(data){
console.log(data);
});
});
You are missing ); at the end of the ajax code.
<script type="text/javascript">
$(document).ready(function($) {
$('#download-btn').click(function(){
var ab='abc';
$.ajax({
url: 'generate_url.php',
type: 'POST',
data: {'ab':ab}
})
.done(function(respose) {
//todo
})
});
})
</script>
You were missing ')' in your javascript code
This will work:
$('#download-btn').click(function () {
var ab = "abc";
$.ajax({
url: 'generate_url.php',
data: {'ab': ab},
type: 'post',
success: function (data) {
alert("sent");
},
error: function (request, status, error) {
alert(request, status);
}
});
});

Jquery simple Ajax Post PHP not working

I have a simple code but is not working. I want to create a more complex function but I just need the basic structure.
HTML
<span class="cleanreport">Delete Record</span>
Javascript:
$( ".cleanreport" ).click(function() {
var token = "test";
$.ajax({
data: {"data": token},
type: "post",
url: "clean.php",
success: function (data) {
console.log(data);
$('.test').html(data);
}
});
});
PHP clean.php
$data = $_POST['data'];
echo $data;
What I am doing wrong?
This should work for you:
var token = "test";
$.ajax({
type: 'POST',
url: "clean.php",
data: {id: token},
dataType: "json",
success: function(response) {
// some debug could be here
},
error: function(a,b,c) {
// some debug could be here
}
});
If not, please debug success and error parameters using console.log().
Based on jquery documentation setting type is an alias for method so this could not be a problem in you case for sure.
$( ".cleanreport" ).click(function() {
var token = "test";
$.post('clean.php",
{
data: token
},
function (data,status) {
//console.log(data);
$('.test').html(data);
});
});

how to a php function which does not parameters from ajax?

I have js function to call a php function via ajax.
$("#history").click(function(){
$.ajax({
url: "./function.php",
type: "POST",
data: {"displayBookingHistory"},
dataType: "JSON",
success: function(data) {
console.log("hellosdasdasds");
$("#universalLogin").append(data);
}
});
})
and php function is
function displayBookingHistory () {
$html = " ";
....
echo json_encode($html);
}
and the call seems to be not successful, even when I try data: "displayBookingHistory",
Anyone knows solutions?
You have a syntax error in your JavaScript: an object needs to consist of a series of property:value pairs.
You can't call a PHP function using Ajax. Only a URL. You need to write your PHP so that it calls the function if you hit that URL.
You are completely ignoring $_POST in your PHP, so there is no reason for it to do anything with the data you are sending to it.
jQuery's AJAX method expects an object with key:value pairs (or a string) for the data field.
Like Quentin said you can't call PHP functions from AJAX, only complete pages. If you want to communicate "run this function" you will have to use $_POST data like this:
$("#history").click(function(){
$.ajax({
url: "./function.php",
type: "POST",
data: {function:"displayBookingHistory"},
dataType: "JSON",
success: function(data) {
console.log("hellosdasdasds");
$("#universalLogin").append(data);
}
});
})
Then in your PHP page:
if(isset($_POST["function"]){
$function = $_POST["function"];
if($function=="displayBookingHistory"){
displayBookingHistory();
}
}
How are you invoking that function?
May be you should have a switch statement that will check the data and call that function.
something like this
if(isset($_POST[data]){
switch($_POST[data]){
case "displayBookingHistory" :
displayBookingHistory();
break;
}
}
your have syntax error ajax send data.
data : {"property:value"} or data : {"property:value" , "property:value" , ...}
problem can be solved in 2 ways:
$ ("# history"). click (function () {
$ .ajax ({
url: "/function.php?action=displayBookingHistory",
type: "POST",
dataType: "JSON",
success: function (data) {
console.log ("hellosdasdasds");
$ ("# universalLogin"). append (data);
return false; //for disable a tag (link) click;
}
});
})
"action" is a parameter used for $_GET type to check php code.
Or
$ ("# history"). click (function () {
$ .ajax ({
url: "/function.php",
type: "POST",
data: {"action":"displayBookingHistory"},
dataType: "JSON",
success: function (data) {
console.log ("hellosdasdasds");
$ ("# universalLogin"). append (data);
return false; //for disable a tag (link) click;
}
});
})
"action" is a parameter used for $_POST type to check php code.
the best way is read a tag href attribute for work in javascript disable.
a tag :
linke
javascript :
$ ("# history"). click (function () {
$ .ajax ({
url: $(this).attr("href"),
type: "POST",
dataType: "JSON",
success: function (data) {
console.log ("hellosdasdasds");
$ ("# universalLogin"). append (data);
return false; //for disable a tag (link) click;
}
});
})
php code :
$action = isset($_GET["action"]) ? $_GET["action"] : "";
if($action == 'displayBookingHistory' )
displayBookingHistory();

Jquery .post() not passing data to PHP file

I am trying to pass an array through post to a php file. Here is my function in jQuery:
function callPHP() {
$.post("php/save.php", {
node: node
},
function (responde) {
console.log(responde);
});
}
And my save.php file has following content:
<?php
echo $_POST['node'];
?>
But I get an error that there's an undefined index 'node'. What is it that I am doing wrong?
try following
//define php info and make ajax call
$.ajax({
url: "php/save.php",
type: "POST",
data: { node: node },
cache: false,
success: function (response) {
}
});
Consider the below example. where info is an array
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info:info},
url: "index.php",
success: function(msg){
$('.answer').html(msg);
}
});
.answer is the class of the element where you want to output your answer.

Get data from php script in javascript

I try to receive a PHP response in my JavaScript.
My PHP looks like this:
some code
if(...) echo "1";
else echo "2";
JavaScript:
function GetChoice() {
var returned="";
$.ajax({
async: false,
cache: false,
url: "http://mydomain.com/script.php",
type: "POST",
dataType:"text",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);
But GetChoice() returns nothing. What's wrong?
UPD: It works if javascript and php script are on the same server. My scripts in different domains.
Try this :
temp1.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function GetChoice() {
var returned = "";
$.ajax({
async: false,
cache: false,
type: "POST",
url: "http://localhost/temp2.php",
data: { name: "John"}
}).done(function( msg ) {
returned = msg;
});
return returned;
}
var r = GetChoice();
alert(r);
</script>
temp2.php
<?php
echo $_REQUEST["name"];
?>
its working....!
try this:
function GetChoice() {
var returned = "";
$.ajax({
async:false,
cache:false,
url:"http://mydomain.com/script.php",
type:"POST",
dataType:"text",
success:function (data) {
alert(data);
}
});
}
The problem is, in your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.
Here is explanation.
How do I return the response from an asynchronous call?
Luck,
GetChoice() will return nothing before the callback in success runs.
The callback, which is the function you define as the success paramater will not fire until the data have been requested from the server.
This is asyncronous (the A in AJAX) so the rest of the code with continue causing the GetChoice() function to return before the callback has been run
this is the script
<script type="text/javascript">
$.ajax({
async:false,
cache:false,
url:"http://path.com/to/file",
type:"POST",
dataType: "html",
data: 'data',
success: function(data){
alert(data);
}
});
and in your PHP file write this code
<?php
function test()
{
$str = 'This is php file';
return $str;
}
echo test();
?>
Make sure the path to the php file is correct AND add the script in another PHP file. Basically you need 2 files. Just tested this in my editor and works ..
function GetChoice() {
var returned="";
$.ajax({
url: "../script.php",
type: "POST",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);

Categories