Ajax get a return value from php? - php

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.

Related

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

Waiting for AJAX request, then finishing the jQuery

I have a piece of jQuery code:
var newData = checkCP(somedata);
if(newData=="hi"){
alert("Welcom");
}
function checkCP(jsData){
$.ajax({
type: "POST",
url: "Process.php",
data: jsData,
dataType: "json",
success: function(data){
if(data.match==1)
return "hi";
else
return "bye";
}
});
}
I don't know why the welcome alert never shows up. I checked everything; the PHP file returns 1, but apparently before it waits on the AJAX response it passes the
if(new=="hi"){
alert("Welcom");
}
Is there any way to wait for the AJAX response, then read the rest of codes in jQuery?
Yes, you can set the 'async' option in $.ajax() to false.
$.ajax({
type: "POST",
async: false,
url: "Process.php",
data: jsData,
dataType: "json",
success: function(data){
if(data.match==1)
return "hi";
else
return "bye";
}
Firstly, please don't use 'new' as a variable name. 'new' already means something.
Now onto the actual question...
when you call checkCP jquery does the ajax post successfully and automatically waits for a response before execuiting the success function. the thing is that the success function is a stand-alone function and returning a value from that does not return anything from checkCP. checkCP is returning null.
As proof try sticking an alert in your success function.
Something like this should do the trick:
function deal_with_checkCP_result(result)
{
if(result=="hi"){
alert("Welcom");
}
}
function checkCP(jsData,callback){
$.ajax({
type: "POST",
url: "Process.php",
data: jsData,
dataType: "json",
success: function(data){
if(data.match==1)
callback( "hi");
else
callback( "bye");
}
});
}
Pass deal_with_checkCP_result as callback

CodeIgniter/jQuery - Ajax call returns full html page instead of my echo

In my view I have an ajax call:
$(".previous").click(function() {
$.ajax({
type: "POST",
url: "planner/get_cal",
data: {current_month: current_month},
success: function(msg){
alert(msg);
}
});
the get_cal function in my Planner controller:
function get_cal()
{
echo "dinosaurs";
}
However, instead of returning "dinosaurs", it returns a full HTML page. I can't figure out why. Thoughts? Thanks a lot.
I solved this by using a leading slash as suggested in the comments to my question.
$.ajax({
type: "POST",
url: "/planner/get_cal",
dataType: "text",
data: {current_month: current_month},
success: function(msg){
alert(msg);
}
});
You can also get it by adding exit after echo in your php file like below:
function get_cal()
{
echo "dinosaurs";exit;
}
It will work. :)
Try setting the dataType to "text"
$.ajax({
type: "POST",
url: "planner/get_cal",
data: {current_month: current_month},
dataType: "text",
success: function(msg){
alert(msg);
}
});
When using the CodeIgniter structure of Controler/Method uri segments I've found it much easier to use ../../controller/method as my URL's in jquery ajax requests. I also recommend specifying a dataType so that the string is parsed and returned as an object.
Here is an example;
$.ajax({
type: "POST",
dataType: "json",
url: "../../controller/method",
success: mySuccessFunction
});
These type of problem come when your php file and html file are not on proper path so that apache server could parse php files.
Without mentioning type:'text' and any other format also, ajax will work.
But be sure that your server is reaching to php file. Otherwise whole file will be treated as text and returned.
For anyone that is using the Zend Framework, I was experiencing the same issues where the AJAX response was returning the full HTML instead of the json_encode() response. This was resolved by adding the following to my controller:
if ($this->getRequest()->isXmlHttpRequest())
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
Just wanted to mention:
the url will really depend on how you have your .htaccess and folder structure set-up.
So the best way is to try several urls, i.e.:
../../controller/method
../controller/method
server_folder/index.php/controller/method
http://example.com/server_folder/index.php/controller/method
and then choose the one that works best in a given situation.
// Main Page view
$("#button").click(function(e)
{
value=$("#input_value").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>path",
data: "type=get_path_details&mobile="+value,
cache: true,
dataType:"html",
async: false,
success: function(data)
{
$('.apend_new_div').empty().append(data);
$('.scroll_card').css('overflow-x','scroll');
}
});
});
// Controller
public function path()
{
$id = $this->input->post("mobile");
// Some function goes here
// $template[''] = ;
$this->load->view('ajax_page',$template);
}
// ajax view page
<?php if($_POST['type']=='get_path_details'){if(!empty($template)){ ?>
// Html code
<?php }} ?>

Jquery AJAX response not working

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

Can a Jquery Ajax Call Accept an Object on Succes from PHP?

I'm writing a simple ajax function and looking to populate two text input fields with the 'success' results. I'm wondering what my php syntax has to be to return an object.
Here is my Javascript function
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}
Here is my php doc (so far, this is where I need to know how to return an object)...
<?php
$data = array('title'=>'this');
echo json_encode($data);
When I run the function I just get the alert "undefined".
Suggestions?
Thanks,
-J
Try this. You can specify that you're expecting a JSON object and then you can interpret data accordingly.
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data.title);
}
});
}
I have returned JSON data from the server via a jQuery Ajax call, not in PHP but it should be the same. As long as you set the content-type of your response to application/json jQuery should consider the responseText as a JSON string. Alternatively you can also set dataType: "JSON" in your Ajax call which tells jQuery that you expect JSON.
Your php page returns: {"title":"this"} in this case.
So you can reference the result with:
alert(data.title);
You may need to specify the data type:
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
dataType: 'json',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}

Categories