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();
Related
I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.
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"];
I'm trying to pass the a variable from JavaScript to PHP using AJAX, but I'm unable to do so. Whenever I try to var_dump($_POST['winner_id']) it returns NULL. I've tried to check the AJAX call with Developer Tools in Chrome and it showed winner_id:0 - which is right.
Here is my code:
JavaScript
function ajaxCall() {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
( {
type: "POST",
url: "ajax.php",
data: {winner_id : winner_id},
success: function(response)
{ alert("The winner was passed!")}
}
);
};
ajaxCall();
PHP Code
<?php
session_start();
if(isset($_POST['winner_id']))
{
$winner_id = $_POST['winner_id']."";
var_dump($winner_id);
}
var_dump($_POST['winner_id']);
?>
If I do a var_dump($_POST) in the beginning of the PHP script then it gives me array(0) { }
I'm new to web development and have been trying to figure this out for hours now. Any hints would be much appreciated. Thanks!
Where are you intializing the winner_id.Either you have to pas it as an argument or intitialize it as aglobal variable.
function ajaxCall(winner_id) {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
({
type: "POST",
url: "ajax.php",
data: {"winner_id" : winner_id},
success: function(response)
{
alert("The winner was passed!");
}
});
};
ajaxCall(winner_id);
Where did you initiate value to winner_id? like
function ajaxCall() {
var winner_id = '123';
...
or if you initiated winner_id before calling ajaxCall() ,you should call ajaxCall() with parameters like ajaxCall($winnerid), which $winnerid is from your PHP
and then
function ajaxCall(winner_id) {
...
i guess you have to convert your winner_id to a string because php read zero (0) as null
function ajaxCall() {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
( {
type: "POST",
url: "ajax.php",
data: {winner_id : winner_id.toString()},
success: function(response)
{ alert("The winner was passed!")},
dataType: "json"
}
);
};
ajaxCall();
I want to alert the return value from a php method, but nothing happens. Here is the ajax and php methods. Can anyone see what I am doing wrong?
--------------------------------------…
Ajax script
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data');
}
});
--------------------------------------…
php method
function junk($id)
{
return "works11";
}
in PHP, you can't simply return your value and have it show up in the ajax response. you need to print or echo your final values. (there are other ways too, but that's getting off topic).
also, you have a trailing apostrophe in your alert() call that will cause an error and should be removed.
Fixed:
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
PHP:
function junk($id)
{
print "works11";
}
You have an extra ' in there on the alert(data') line
This should work
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
And your PHP code should call the method also and echo the value
function junk($id) {
return 'works11';
}
exit(junk(4));
All you're doing currently is creating the method
ajax returns text, it does not communicate with php via methods. It requests a php page and the return of the ajax request is whatever the we babe would have showed if opened in a browser.
For some reason this jQuery function is not working properly. Here's my code... the response div is not updating with my response.
WHEN AJAX FUNCTION IS CALLED
if ($action == 'sort') {
echo 'getting a response';
return 0;
}
JQuery FUNCTION
function sort() {
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data:"sort_by=" + document.getElementById("sort_by").value +
"&view_batch=" + document.getElementById("view_batch").value,
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
}
DIV TO REPLACE
<div id="ajaxPhotographSortResponse"></div>
Move the action=sort into the data property of the $.ajax function. You're making a POST request, but appending data onto your query string like a GET request. Data only appends to the query string if it's a GET request.
Example:
$.ajax({
type: "POST",
url: "contributor_panel.php",
data: {action:'sort', sort_by: $('#sort_by').val(), view_batch: $('#view_batch').val()},
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
http://api.jquery.com/jQuery.ajax/
Instead of concatenating the arguments you are passing to your server side script I would recommend you using the following syntax. Also if you already use jQuery you no longer need the document.getElementById function:
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data: { sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() },
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
or even shorter using the .load() function:
$('#ajaxPhotographSortResponse').load('contributor_panel.php?action=sort',
{ sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() });