Ajax PHP Jquery - echo-ing back data - php

I'm having trouble bringing back data from my PHP file. I guess I don't really understand the data parameter of this jquery function so I just went off some tutorials.
Jquery
$.ajax(
{
url: 'test.php',
dataType: 'text',
data: {test: '1'},
success: function(data)
{
window.alert(data);
}
})
Now from my understanding the test: declares the variable used in php and 1 is the value in that variable. But I'm not entirely sure...
Here's my PHP
$item1 = $_POST['test'];
echo $item1;
Now it's just supposed to alert that value so I know it is at least returning something but in the alert it's just blank so I'm losing the value somewhere, but where?

use $_REQUEST it will handle both the GET and POST
$item1 = $_REQUEST['test'];
by default ajax request is GET type, either specify expilicitly the type like
$.ajax(
{
url: 'test.php',
type:'POST'
dataType: 'text',
data: {test: '1'},
success: function(data)
{
window.alert(data);
}
})
or use $_GET like
item1 = $_GET['test'];
echo $item1;

The correct way:
<?php
$change = array('key1' => 'blabla', 'key2' => '12432rr424234');
echo json_encode($change);
?>
Then the jquery script:
<script>
$.get("location.php", function(data){
var mydata= $.parseJSON(data);
var art1 = mydata.key1; // <----------- access the element
});
</script>

This is work for me
ajax code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
$.ajax(
{
url: 'test.php',
type: 'POST',
dataType: 'text',
data: {latitude: '7.15588546', longitude: '81.5659984458'},
success: function (response)
{
alert(response);
}
});
</script>
</head>
<body>
</body>
</html>
php code (test.php)
<?php
$lat = $_REQUEST['latitude'];
$lon = $_REQUEST['longitude'];
echo 'latitude- '.$lat . ', longitude- ' . $lon;
?>

add POST method:
$.ajax(
{
url: 'test.php',
dataType: 'text',
type: 'post',
data: {test: '1'},
success: function(data)
{
window.alert(data);
}
})

you forgot to put the method POST/GET by which you are sending the data to your php file.
$.ajax(
{
type:'POST',
url: 'test.php',
dataType: 'text',
data: {test: '1'},
success: function(data)
{
window.alert(data);
}
})

just add "type" POST or GET
//example
$.ajax(
{
url: 'test.php',
type: 'POST',
data: {test: '1'},
success: function(data)
{
window.alert(data);
}
})

If you are trying to get information from the php file, I don't think the data field is required. Here is what I have.
$.ajax(
{
url: 'response.php',
type: 'get',
dataType:'text',
success: function(data){
window.alert(data);
}
}
and as far as the php goes..
<?php
echo "1";
echo "2";
echo "3";
echo "4";
echo "5";
echo "6";
echo "7";
echo "8";
?>
Alert box on execution

Been struggling on this for a while, my issue wasn't on the js but in php script : error reporting was set to E_ALL - which apparently blocks it from returning data to the AJAX call. My guess is it prints notices before the final echo and blocks it all. Weird thing is it didn't print me any notice in the logs i set up to get to the bottom of this.
Changed it to E_ERROR and now works like a charm.

Related

Function is not working when called with AJAX

I have:
call.php:
function ajaxnotify(){
notify('hello');
}
function notify($a){
echo "
<script src=\"/js/jquery.min.js\"></script>
<script src=\"//cdn.socket.io/socket.io-1.4.5.js\"></script>
<script>
$(function(){
socket = io.connect(\"MY IP AND PORT\",{secure: true});
socket.emit('say', {'msg': '$a'})
});
</script>
";
}
switch($_GET["do"]){
case "1":
ajaxnotify();
break;
case "2":
notify();
break;
}
and this code absolutely works when I directly go to mysite/call.php. But when I use:
$.ajax({
type: "POST",
url: "call.php?do=1",
data: "",
success: function(html){
}
});
It just doesn't work. it works when I'm directly going to page, but it doesn't work when I call ajax function from html.
Where is my mistake, guys?
You're sending the request using POST, yet using $_GET to retrieve the variable in PHP.
Change the type: "POST" in jQuery, to type: 'GET'. Here's a complete example:
$.ajax({
type: 'GET',
url: 'call.php',
data: { do = 1 },
success: function(html) {
console.log(html); // to at least verify the response
}
});

Can not get Ajax callback json data when use jsonp datatype

this is my JS code below:
function getTopProductsApi(){
var result;
$.ajax({
url: API_url,
type: "get",
data: ({}),
async:false,
dataType: "jsonp",
jsonpCallback:"success_jsonpCallback",
success: function(rs){
result = rs;
}
});
return result ;
}
var result = getTopProductsApi();
alert(result);
PHP
public function test(){
echo $_GET['callback']. '(' . json_encode('213213') . ')';
}
I am sure that I get the return json data:
The json data I get below:
success_jsonpCallback("213213")
But there have no data when I alert.
Can someone tell the reason? Thanks
My code:
test page:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function getTopProductsApi(){
var result;
$.ajax({
url: '/test/test1.php',
type: "get",
data: ({}),
async:false,
dataType: "jsonp",
jsonpCallback:"success_jsonpCallback",
success: function(rs){
result = rs;
}
});
//alert(result);
return result;
}
var result = getTopProductsApi();
alert(result);
</script>
</head>
<body>
</body>
</html>
php page:
<?php
echo $_GET['callback']. '(' . json_encode('213213') . ')';
It works well. You can have a try.
Thanks for everyone's answer.
Finally, I find the problem.
Maybe this is not the currect answer, but this information is useful for me.
The jsonp data type is always Asynchronous.
The code-"return result" will always run faster the ajax block.
So the result variable is always NULL.
So I change my code likes below:
function getTopProductsApi(function_name){
$.ajax({
url: API_url,
global: false,
cache: false,
type: "get",
data: ({'current_date':current_date}),
dataType: "jsonp",
jsonpCallback:"success_jsonpCallback",
success: function(rs){
result = rs;
window[function_name](result);
}
});
}
getTopProductsApi('another function name');
This method can make sure that I can get the ajax json data first, and then run another function I need.
Maybe this is not the best answer, please tell me if you have other cool ideas.
Thanks
try below code:
function getTopProductsApi(){
var result;
$.ajax({
url: API_url,
type: "get",
data: ({}),
async:false,
dataType: "jsonp",
jsonpCallback:"success_jsonpCallback",
success: function(rs){
result = rs;
}
});
}
function success_jsonpCallback(result){
alert(result)
}

jquery json request failed

I'm trying to make a json call with jquery but noting happened. My code:
javascript:
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
}
});
});
});
</script>
PHP
$output = array(
'percentage' => "50"
);
echo json_encode($output);
Any suggestions?
The code looks fine to me,
EDITED
Also try removing the protocol and use url: "//<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error: function (jqXHR,textStatus,errorThrown)
{
//Check for any error here
}
});
});
if you add and error callback to the ajax call you should get some error printouts to let you know what is going on
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error : function (e1, e2, e3) {
console.log(e1);
console.log(e2);
console.log(e3);
}
});
EDIT:
i just had a thought, if i remember correctly jquery ajax doesnt like using full url's if possible try using a relative path

ajax call php code in a file and get result

Some code I want to call from ajax is in a separate file.php:
<?php
session_start();
$email1 = $_POST['email1'];
//some code here processing $email1
$response = 'some text';
?>
This is how I call it from ajax:
$.ajax({ url: 'file.php',
data: {email1: $("#user_email").val()},
type: 'post'
});
I'd like to be able to do something like this after the call to file.php:
alert($response);
How do I do that?
In your PHP you have to echo the $response, and in your JS you have to specify the callback function like so:
$.ajax({
url: 'file.php',
data: {
email1: $("#user_email").val()
},
type: 'post',
success: function(data) {
alert(data);
}
});
Inside the ajax call, include a success.. ex:
success: function(data) {
alert(data);
},
This will pop an alert up with your response.
Try:
$.ajax({ url: 'file.php',
data: {email1: $("#user_email").val()},
type: 'post',
success: function(data) {
alert(data);
}
});
Check out the documentation
You also need to echo out the response in your PHP file:
echo $response;
Something like this?
$.ajax({
type: "POST",
url: "file.php",
data: {email1: $("#user_email").val()},
success: function(data) {
alert(data);
}
});

get value - ajax'

I am sending this variable to other page, to make a validation.
However print_r($_POST); only show Array ().
Normally we use serialize, is sent the name attribute, but in this case only is sent the variable with the text. So something like $form = $_POST['data']; only works to
in firebug:
data="something"
but in my case i just send
something
code
<?php $page = "someText"; ?>
JS
default:
$("#msg").fadeTo(200, 0.1, function() {
$(this).html('success').fadeTo(900, 1);
$.ajax({
url: "page_validation.php",
type: "post",
dataType: "json",
data:'<?php echo $page; ?>',
success: function(data) {
$('#one').load('page.php');
}
});
});
break;
try it like
$page = "someText";
$.ajax({
url: "page_validation.php",
type: "post",
dataType: "json",
data:"postedvariable=<?php echo $page; ?>",
success: function(data) {
$('#one').load('page.php');
}
});
and acces the varible in page_validation.php as $_POST['postedvariable']
also another option will be to use
$.post("page_validation.php",
{postedvariable:'<?php echo $page; ?>'},
function(data) {
$('#one').load('page.php');
});
whic looks even simpler than the $.ajax

Categories