$.getJSON not returning any data - php

I am trying to test $.getJSON() on localhost, but no data is returned.
Please correct me if I am wrong.
PHP:
$person['name'] = !empty($_GET['name']) ? $_GET['name'] : 'name';
$person['age'] = !empty($_GET['age']) ? $_GET['age'] : '00';
return json_encode($person);
?>
HTML / jQuery:
<script>
$(document).ready(function(){
$('.start').click(function(){
$.getJSON('http://localhost/ewoe/server.php?name=natasha&age=22', alert(data.name));
})
}); //end ready
</script>
All files can be found in the same directory.
Although, the error I get after hitting the .start button is 'data not set'.

The problem is actually in the PHP output.
The reason is that PHP, being a server-side language does not output to the HTML the stuff with return. If you want to print them out you have to echo them.
Therefore return is not the answer, the answer is echo.
Your php should be:
<?php
$person['name'] = !empty($_GET['name']) ? $_GET['name'] : 'name';
$person['age'] = !empty($_GET['age']) ? $_GET['age'] : '00';
echo json_encode($person);
If you are getting errors on the No 'Access-Control-Allow-Origin' you should try giving a local path, not the full path:
$.getJSON('server.php?name=natasha&age=22', ...);
-
NOTE
Don't really know what you are doing there, but as a note, be carefull to possible manipulation of your script.
By doing this, someone can see the source of your file and send request to the server.php by going to www.yoursite/ewoe/server.php?name=....
Perhaps you should use the $_POST in the PHP and jQuery $.post requesting json format, like this:
$.post('server.php', {name : 'natasha', age: 22}, function(response) {
console.log(response.name)
}, 'json');

You should wrap alert into anonymous function:
$.getJSON('http://localhost/ewoe/server.php?name=natasha&age=22', function(data) {
alert(data.name);
});

Related

Page not getting redirected php

I have passed some values from a page to another using ajax with request method post. But there is one condition that f some one is directly accessing the url, it should be redirected to some other page. Problem is that its not getting redirected (In else condition in img.php) . Can any one tell me what mistake I am committing?
Thanks in advance.
Code:-
imageupload.php:
document.getElementById("submit").addEventListener("click", function(event){
event.preventDefault();
saveImgfunc();
});
function saveImgfunc(){
var form = new FormData(document.getElementById('saveImg'));
var file = document.getElementById('imgVid').files[0];
if (file) {
form.append('imgVid', file);
}
$.ajax({
type : 'POST',
url : 'core/img.php',
data : form,
cache : false,
contentType : false,
processData : false
}).success(function(data){
document.getElementById('msg').innerHTML = data;
});
}
img.php:
<?php
require '../core.php';
$qry = new ProcessQuery('localhost', 'root', '', 'mkart');
$uid = 6;
if($_SERVER["REQUEST_METHOD"] == "POST"){
//Some code here
}
else{
header("Location : ../core.php");
}
See this post https://stackoverflow.com/a/21229246/682754
There's a good chance that you may have some whitespace before you use the header function? Perhaps in the form of a hidden error/warning.
Try the following at the top of your PHP code in img.php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
Would advise removing that once you've found your issue
It works for me removing the whitespace between Location and :
header("Location: ../core.php");
Error found. In the core.php thre is one code which stopping the further execution of code. Its specially coded for uid = 6. Thanks for your time.
Dont use header("Location : ../core.php"); some time it gives error or not working properly so use javascript redirection
like
?>
<script>window.location='../core.php';</script>
<?php

Sending successfull response to jquery's (iframe-post-form) plugin

I'm dealing with how to send successful response to jquery's iframe post form plugin.
With the help of the source code of the plugin's demonstration, I can see that there is the following code below: (Click here for source)
complete : function (response)
{
var style,
width,
html = '';
if (!response.success)
// I've always came to this block! And that is exactly the problem that I have
{
$('.message').slideUp(function ()
{
$(this)
.html('There was a problem with the image you uploaded')
.css({
color : '#9c0006',
background : '#ffc7ce',
borderColor : '#9c0006'
})
.slideDown();
});
}
else /***** When is the response successful and when will code come here? *****/
{
/*
following code goes here...
*/
}
}
The exact question is that when do the response.success will be TRUE? And how should I set it to TRUE with PHP? (Please answer both with and without JSON style)
when you run ajax and communicate with php. youre going to grab whatever php echoes out and use that. in this case its probably wisest to use json encode. heres a very basic example to give you an idea.
a php file:
echo json_encode(array('success' => true));
now a basic ajax request
$.ajax({url:"ajax.php",success:function(result){
result = $.parseJSON(result); // we do this to convert the php into javascript format
if(result.success){
alert('this is true');
}
}});

passing /retrieving data from jquery to php function

I have actually read all related answers to my question but I need a clear and simple example on how to properly implement my code below.
myHome.php
jquery
var url = "computeArea.php";
var data = $('thisForm').serialize();
$.post(url,data,function(response)); // how do i get the area being returned from
computeArea function? i need to save the
return value to a javascript variable
computeArea.php
function computeArea ($data){ // do i need to parse $data to make it an array?
return $area;
}
im new to jquery and your help is very helpful. thank you!
You can do:
$.post(url,data,function(response){
alert(response)
});
ps: you are missing the . between $ and post.
In your php code you could do that:
echo json_encode($area);
Do a simple teste.
jQuery:
$.post("url/to/file.php",{variable_name: "hello"/*(we'll give this value to variable_name*/)},
function(response){
if(response>0)
alert('Something went wrong');
else
alert(response);
});
Now, on server side:
<?php
if(isset($_POST['variable_name']) && $_POST['variable_name']!=="")
echo $_POST['variable_name'];
else
echo 1;
?>
You are misunderstanding the use of post requests. This will not call the computeArea function in computeArea.php and pass data as its parameter:
var data = $('thisForm').serialize();
$.post(url,data,function(response));
You can do this instead for computeArea.php:
$data = $_POST['watever_you_are_serializing'];
// Do computations, etc.
$area = 123; // Contains computed area
echo $area; // Or json_encode($area);
If you need to call that function from computeArea.php, then you can create a new file for $.post request (eg. computeArea2.php) and include computeArea.php from there. It would be something like this:
include 'computeArea.php';
$data = $_POST['watever_you_are_serializing'];
echo computeArea($data);
Something along the lines of:
var url = "computeArea.php",
data = $('thisForm').serialize(),
new_variable;
$.post(url, data, function(response) {
new_variable = response;
});
Though I presume there's a bit more to your PHP script, as otherwise $area isn't defined anywhere.

Ajax to php call isn't successful

I'm trying to test an ajax call on post by doing the following just for testing purposes, but for some reason the call is never successful. I've been searching around and there isn't much that I could find that would explain why this isn't working.
$.ajax({
type: "POST",
url: "file.php",
success: function(data) {
if(data == 'true'){
alert("success!");
}
},
error: function(data) {
alert("Error!");
}});
file.php contains the following:
<?php
return true;
?>
Can someone please point me in the right direction. I realize that this may seem simple but I am stumped. Thank.
return true will make the script exit. You need:
echo 'true';
Firstly check your paths. Is file.php residing in the same folder as the file that your javascript is contained in?
If your path is incorrect, you will get a 404 error printed to your javascript console if you are using chrome.
Also you should change your php to:
<?php
echo 'true';
Once your path is correct and your php is amended you should be good to go.
Have you tried by accessing to the file directly and see if it outputs something?
return true shouldn't be use in that case (or any other, it's better to use exit or die), everything get by a AJAX call is hypertext generated by server side, you should use (as they pointed you before echo 'true';)
You could also try a traditional AJAX call XMLHttpRequest (without JQuery) if problem persists, and then check if there is any problem between the request and server..
EDIT: also, do not check by comparison, just make an alert to 'data' to see what it gets.
In addition to the echo 'true' suggestion, you can also try to alert the actual data that's returned to ajax. That way you can see if you have the proper value/type for your if statement.
success: function(data) {
alert(data);
}
try this, the new ajax syntax
$.ajax({ type: "POST", url: "file.php" }).done(function(resp){
alert(resp);
});
Here is correct way:
$.ajax({
type : "POST",
url : "file.php",
success : function (data) {
/* first thing, check your response length. If you are matching string
if you are using echo 'true'; then it will return 6 length,
Because '' or "" also considering as response. Always use trim function
before using string match.
*/
alert(data.length);
// trim white space from response
if ($.trim(data) == 'true') {
// now it's working :)
alert("success!");
}
},
error : function (data) {
alert("Error!");
}
});
PHP Code:
<?php
echo 'true';
// Not return true, Because ajax return visible things.
// if you will try to echo true; then it will convert client side as '1'
// then you have to match data == 1
?>

Executing PHP function from JSON

I am trying some things with JSON and PHP and there is something that I can't find a way to do, though I'm not 100% sure there is one. But because it looks like a nice option (If possible) I decided to ask here.
I have these examples from jquery offical site. There are two files, the first one is index.php where I execute my Ajax, hete it is:
<!DOCTYPE html>
<html>
<head>
<title>Simple form sending and receiving a JSON object to/from PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
var dataString = JSON.stringify(data);
$.post('simpleformSubmi.php', { data: dataString}, showResult, "text");
});
function showResult(res)
{
$("#fullresponse").html("Full response: " +res);
}
</script>
<div id="fullresponse"></div>
</head>
<body>
Nothing complicated at all. And I have my simpleformSubmi.php which is :
<?php
$logFile = 'logFile';
$res = json_decode(stripslashes($_POST['data']), true);
error_log("result: ".$_POST['data'].", res=".json_encode($res), 3, $logFile);
error_log("\n", 3, $logFile);
//header("Content-type: text/plain");
foreach ($res as $key=>$value)
{
$str[] = $value;
}
$functionArray ="function(){ \$a = 10; echo \$a;}";
$jsStr = $str[0][1];
echo json_encode($jsStr['firstname']);
echo '<hr />';
echo json_encode($res);
echo '<hr />';
echo json_encode($functionArray);
?>
As you can see $functionArray - is in fact a string containing PHP function which I want to return back using JSON and to execute it after that. So is there any way to do that really? Now what I get in index.php afet executing the files is:
"function(){ $a = 10; echo $a;}"
Thanks
Lern
Seems like you're trying to execute a PHP function through JavaScript. Since PHP is executed server-side the only way you have to execute a PHP function in that context is to ask the server back to execute the function for you, by doing another ajax call for example.
Something like this:
index.php
$(document).ready(function(){
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
var dataString = JSON.stringify(data);
//Change post() success callback function to executePHP()
$.post('simpleformSubmi.php', { data: dataString}, executePHP, "text");
//Let's define executePHP() outside post() call for clarity
function executePHP()
{
//Ask the server to execute function foo(), and get the result
$.get("example.com/somefile.php?function=foo", function(data)
{
//Success function, do whatever you want.
alert(data);
});
}
});
Then, in somefile.php
<?php
//Condition(s), if any. You could even implement this interface using REST.
//Get function to execute
if($_GET["function"] == "foo")
{
//Output function's result.
echo foo();
}
//The function you want to run
function foo()
{
//Do something
$a = 10;
return $a;
}
?>
If all went well, when JavaScript reaches the alert(data); statement you will see 10.
You cannot execute a PHP function after sending it as a response since the response is received on the client end, and PHP is a server side language.
Usually, you would just return the values. In your example, you would just return an associative array that holds the key value pair a,10.
You can return javascript functions from the PHP script and execute that on the client side using eval but eval'ing opens a pandora's box of security vulnerabilities.
You can't execute PHP code outside of a PHP server. So you can't run it in the browser.
You can, however, pass a string of JavaScript and run it through eval. Some people will tell you that's bad, but remember that eval used to be the only way to parse JSON in the first place.
In order to send back something to PHP, you must call the serverside via, p.e via GET or POST actions from a form. But, no, you cannot execute anything serverside via echo, as echo outputs to the client side. You could always use eval (http://php.net/manual/es/function.eval.php) at serverside to execute something from a POST message, but it is not recommended as it can open a great security hole.
You've returned a function (I'm assuming you meant this to be javascript), now you need to call it. This can be done by using the jQuery $.post success callback.
Try changing this..
$.post('simpleformSubmi.php', { data: dataString}, showResult, "text");
To
$.post('simpleformSubmi.php', { data: dataString}, function(data){eval(data)}, "text");
If its PHP (which it looks like) and not Javascript, then this will need to executed from the server. Being that its a server-side language 'n all.

Categories