Creating a Callback with JSONP - php

I'm attempting to access data cross domain (testing locally) but the data keeps failing to load.
$.ajax({
type: 'POST',
url: 'http://localhost/php/ajax/json.php',
dataType: 'jsonp',
data: {action: 'get_json'},
success: function(data) {
console.log(data);
},
error: function() {
console.log("Error loading data");
}
});
The PHP is as follows (function is called through a switch statement earlier in the file).
function get_json() {
$mysqli = db_connect();
$sql = "SELECT * FROM json_test";
$result = $mysqli->query($sql);
$rows = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($rows, $row);
}
}
echo $_GET['callback']."(".json_encode($rows).");";
}
Headers are set at the start of the PHP document.
header('Content-Type: application/json');
The error I am receiving (if I run the PHP file by itself) is Undefined index: callback. The json string echoes fine as text after this error. (I have tried echo $_POST[...] as well).
How can I get this callback to work or how do I define it properly? Any help is appreciated.

add this parameter:
&jsoncallback=?

I was able to fix the error in the PHP file by changing the callback to the following:
$callback = "";
if (array_key_exists('callback', $_GET) == TRUE) {
$callback = $_GET['callback'];
}
echo $callback."('".json_encode($rows)."');";
The AJAX query now also retrieves the JSON data successfully.

Related

Return data AJAX PHP

By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.
This is my AJAX call:
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
data: {rede: $("#dropdown-parceria").val()},
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And this is what I got from trying to filter some data to return it,
but nothing worked:
<?php
require_once('../../includes/conecta.php');
$rede = $_POST['rede'];
function buscaDados($conexao){
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
}
Any idea?
Thanks!
You should add echo at the end :
echo json_encode($dados);
So the $dados array will be sent back to the ajax request as JSON response.
Parse the response to json uisng $.parseJSON() :
.done(function(resposta){
resposta = $.parseJSON(resposta);
console.log(resposta);
})
Hope this helps.
in your ajax code u add a success.
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
dataType: 'json',
data: {rede: $("#dropdown-parceria").val()},
success: function (data) {
//You do not need to use $.parseJSON(data). You can immediately process data as array.
console.log(data)
//if you have a array you use the following loop
for (var j =0;j < data.length;j++) {
console.log(data[j]);
// u can use data[j] and write to any fields u want.
// e.g.
$('.somediv').html(data[j].myarraykey);
}
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.
$rede = $_POST['rede'];
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
echo json_encode($dados);
die();

Pass value from JQUERY to PHP ,and return a JSON

When call php from jquery via ajax ,have any response .I changed the dataTypeand put jsoninstead html.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm'] never carries a value.
PHP:
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
and jQuery :
$(document.body).on('click', '.edit', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {
retriveForm: id
},
dataType: "json",
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
Code is all in the same page if that may be important.
Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.
Also, you're not correctly adding to $data_json in your loop. You're overwriting the variable each time instead of pushing onto it.
<?php
// code here to set up database connection
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json[] = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
exit();
}
?>
<html>
<head>
...
Then in the success function, you'll need to index the elements of response, since it's an array, not a single object.

ajax and php: how to select variables from database and insert in database using ajax

I really have never done this before and I am getting frustrated because I'm not sure how it fits together. I have a function that I want to call my php (one php file selects info from a database and the second inserts into the database)... I need to use ajax in the way my site is setup but I don't know how to pass data from and to the php files.
In first .js file:
q1LoadVar();
This is my ajax function in second .js file that I have so far (not working):
//ajax code has been edited here since original post:
function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {
console.log(data); //nothing happens!
// alert(data); //nothing happens!
}, "json" );
}
And here is the code I have in q1LoadVar1.php that I want to select data back from and be able to populate a text area in my html:
/*works when I type this file path directly into the url;
but the file is not communicating back to the ajax function on the
.js file that is calling it*/
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
echo '<script type="text/javascript">alert("working from php!");</script>';
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}
$json = json_encode($newRow);
echo $json; //works on php file directly!
/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/
mysqli_free_result($result);
mysqli_close($link);
?>
Can someone help me understand how to make this all work together? Thank you, Kristen
You can retrieve post data from ajax in php with
$_POST['action']
//in your case will return: test
To return data to ajax you need to use echo
If the success: callback function doesnt get called try to remove datatype: 'json'
I also think that you need to echo $newrow instead of $row.
If this still doesnt work you can catch the error with the error: callback function to see what is wrong.
Try to start with a simple request and work from there.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "yourphp.php",
data: {simplestring: "hi"},
success: function(result){
alert(result);
}
});
});
and yourphp.php
<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;

Error with JSON Ajax get method

I am using a jquery ajax get method to fetch information from the server however I am having trouble parsing the information so that I may use it. My website has a gallery of products that will filter its items based on category.
Here is the jQuery ajax function:
$('.category').click(function() {
var category;
if ($(this).hasClass('Shirts')) {
category = 'shirts';
}
if ($(this).hasClass('Hats')) {
category = 'hats';
}
if ($(this).hasClass('Acc')) {
category = 'acc';
}
$.ajax({
type: 'GET',
url: 'galleryfetch.php',
data: { 'category' : category },
dataType: 'json',
success: function(data) {
arr = $.parseJSON(data);
alert(arr);
}
});
});
This is the php script that the information is posted to:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$category = $_GET['category'];
$conn = mysqli_connect('localhost', '*****', '*****', 'clothing');
$rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");
while ($row = mysqli_fetch_array($rows)) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
}
I using the alert in the success function to see if the information is passed succesfully but at the moment there is no alert and i get an:
Unexpected token o error.
I'm not sure if I'm parsing the information correctly or if Im not correctly using JSON
tl;dr: $.parseJSON(data); should be removed.
Your server is returning JSON (but claiming it is sending HTML, you should have header("Content-Type: application/json")).
You have told jQuery to ignore the claim that it is HTML and parse it as JSON. (This would be redundant if you fixed the above problem)
dataType: 'json',
The parsed data is passed to your success function.
You then pass that data to JSON.parse so it gets converted to a string (which will look something like [ [Object object], ... and is not valid JSON) and then errors.
Remove:
arr = $.parseJSON(data);
And just work with data.

jQuery JSON PHP Request

I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).

Categories