I have a page where I do different requests via AJAX, also I have the developer DB and the production DB but the JS is the same. In certain module, if I open it using the developer DB it shows me the response but if I use the production database it shows nothing but not error is displayed. If I use the production DB in any other module it works perfectly. I already checked in the network console and it says that in both cases the request is sent. Here is the JS code:
function consultaAdministradores(id, tipo, btn){
var datos = {
'id': id,
'tipo': tipo
}
console.log("DATOSSSS");
console.log(datos);
$.ajax({
url: '../send/get_AdminEmpresas.php',
type: 'POST',
data: datos,
dataType: 'JSON',
success: function(res) {
console.log(" res --------- ");
console.log(res);
imprimeAdmins(res);
}
});
console.log("Se pasó el AJAX");
And in the PHP file I have this:
$res = $con->consulta($sql);
if ($res->num_rows > 0 ) {
$i = 0;
while ($dato = $res->fetch_assoc()) {
$administradores[$i] = $dato;
$i++;
}
if ($tipo_page == 'prev') {
array_multisort($administradores);
}
$array = array('status' => "Success", 'administradores' => $administradores, 'id' => $id_page, 'tipo' => $tipo_page);
}
else
{
$array = array('status' => "Fail", 'message' => 'Sin resultados');
}
$json = json_encode($array);
echo $json;
The problem wasn't the JS or the PHP files, the problem was the codification of the DB, I inserted some data in UTF-8 codification and later I converted to UTF-8 codification giving me as a result some weird characters.
Related
I'm using a $.post() to push data to a php file. But the $_POST is empty when I make a var_dump of it.
JS script :
$('#Notes').on("click", function (e) {
e.preventDefault();
let $id = $(document).getUrlParam("varname");
let $text = $(this).attr('data');
let $notes = prompt("Modifier la note", $text);
console.log($text, $id, $notes);
if ($notes !== null || $notes !== "") {
$.post(
'../buckets/update_note.buckets.php',
{
id: $id,
notes: $notes,
},
function (data) {
console.log('Data Id : ',data.id);
console.log('Data Name : ',data.name);
})
.then(r =>{
location.replace('../buckets/update_note.buckets.php');
})
}
in php file :
<?php
var_dump($_POST);
var_dump($_GET);
The 1st console.log in js show me the values of the 3 variables but the console.log in the callback show me undefined. But I see in the network debugger :
Form Data
id: xxxx
notes: xxxx
Any idea ?
I believe, data will be text in your case. You need to use json_encode() in you php to print complex objects. Then in your JS you can use JSON.parse() to restore object or define application/json content type in your POST query. Something like:
// php
$json = json_encode([
'post' => $_POST,
'get' => $_GET
]);
// js
function (response) {
const data = JSON.parse(response);
}
You can try in this way.
JQuery CODE
$('#Notes').on("click", function (e) {
e.preventDefault();
let $id = $(document).getUrlParam("varname");
let $text = $(this).attr('data');
let $notes = prompt("Modifier la note", $text);
console.log($text, $id, $notes);
if ($notes !== null || $notes !== "") {
$.post(
'../buckets/update_note.buckets.php',
{
id: $id,
notes: $notes,
},
function (data) {
var data=$.parseJSON(data);
console.log('Data Id : ',data.id);
console.log('Data Name : ',data.notes);
})
.then(r =>{
//location.replace('../buckets/update_note.buckets.php');
})
}
PHP CODE
echo json_encode($_POST);
This is how i am trying to check json data. If the data inserts correctly i want the mentioned jquery in success code. But if it is not inserted then i want else code to run. But the if else conditions are not working properly.I am including php code and ajax code which i have tried. Am i doing it right?
AJAX
$( "#frm_add" ).on('submit',(function(e) {
e.preventDefault();
var img= new FormData(this);
datas = $("#frm_add").serializeArray();
$.each(datas,function(key,input){
img.append(input.name,input.value);
});
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
//data:new FormData(this),
data:img,
// data: {img:img,datas:datas}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) // A function to be called if request succeeds
{
if(data == true)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
});
}));
php
function insertCategories($params)
{
$fileName = $_FILES['cat_image']['name'];
$name = $params['cat_name'];
$type = $params['cat_type'];
$switch = $params['cat_switch'];
$chk=mysqli_query($this->conn,"select * from categories where cat_name='$name'");
if(mysqli_num_rows($chk)==0)
{
$sql = "INSERT INTO `categories` (cat_name,cat_image, cat_type, cat_switch) VALUES('$name','$fileName', '$type','$switch'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert Categories data");
if ($result) {
if (file_exists("images/" . $_FILES["cat_image"]["name"])) {
echo $fileName . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['cat_image']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "images/" .$fileName; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
}
}
echo json_encode($result);
}
}
Add the error command in your ajax call to execute if the command fails or returns no data in general
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:img,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data), // A function to be called if request succeeds
{
if(data)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
error: function (data)
{
$("#namerr".html("<p id='error' style='color:red'>"+data+"</p>");
}
});
I think You have problem with response convention: Sometimes You call die() method (PHP: 12 line), sometimes You call json_endcode() (PHP: 25 line), sometimes echo with plain string.
In this type of actions You should:
Always output JSON from backend script. Mixing response types is really pain in the ass, it's hard to parse and test.
Use response object with uniform structure - that might help with building complex applications and easy to modify
Example pseudocode:
PHP
if($success) {
die(json_encode([
'error' => false,
'message' => 'Thank You',
'data' => $some_extra_data
]));
} else {
die(json_encode([
'error' => true,
'message' => 'Sorry',
'data' => $some_extra_data
]));
}
Then in ajax.success() method, its really easy to handle:
success: function (data) {
try {
var response = JSON.parse(data)
if(response.error == true) {
$('#nameerr').text(response.message)
} else {
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
} catch (err) {
alert('Sorry. Server response is malformed.')
}
}
Hopefully an easy question here. I actually used an example I found on SO but can't figure out why its not working. No errors in console or anything.
I have an ajax Post function I am using to pass data to a php script.
Its passing the data correct, but the response each time is coming back as an error alert. I can confirm that server side is getting the data and processing it correctly, just can't figure out why its never returning a success response.
Here is the Ajax:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
</script>
And in my php script I used this:
<?php
$success = true;
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => 'YAY'));
} else {
$output = json_encode(array('type'=>'error', 'message' => 'WHOOPS'));
}
die($output);
?>
The problem is that datatype: 'json' should be dataType: 'json'. Javascript is case-sensitive.
The error is because you received the returned data as json but the content type is a simple string (text/html) so you need to JSON.parse() the received data first like so:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
response = JSON.parse(response);
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
The second option is to send json headers from php itself thus removing the need of parsing JSON in javascript. You can do that by using the following line of code BEFORE ECHOING OR PRINTING ANYTHING ELSE FROM THE PHP SCRIPT:
header('Content-Type: application/json');
and then
echo $output;
If you are working with JSON responses, you need to set the header so your browser and your JavaScript could interpret it correctly:
<?php
$success = true;
if ($success == true) {
$output = json_encode(array(
'type' => 'success',
'message' => 'YAY'
));
} else {
$output = json_encode(array(
'type' => 'error',
'message' => 'WHOOPS'
));
}
header('Content-Type: application/json');
echo $output;
Afternoon guys/gals,
I'm relatively new to using AJAX to POST information to a JSON file and I am not sure what the .php file should look like to process it. I have very little experience with .php. Am I on the right track? I've looked a lot of examples but most of them only have pieces of the .php file to process it. I am trying to inject the "task" into the JSON file which I then use handlebars to read on another page.
function fnCreateTask() {
var url = "save.php";
var title = $("#TaskTitle").val();
var date = $("#TaskDate").val();
var desc = $("#TaskDescription").val();
var info = {
Title: title,
Date: date,
Description: desc
};
var body = JSON.stringify(info);
$.ajax({
type: "POST",
url: url,
contentType: 'application/json',
data: body,
dataType: 'json',
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
}
<?php
$fp = fopen('careers.json', 'w');
fwrite($fp, $_POST = json_decode(file_get_contents('php://input'), true););
fclose($fp);
?>
$.ajax POST (or GET for that matter) data will be x-form encoded by default when sent to the server. You can do
on the client
//object for the data
var data = {
title: $("#TaskTitle").val(),
date: $("#TaskDate").val()
};
$.ajax({
type: "POST",
url: "save.php",
data: data,
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
and on the server
// as a separate object to be safe
$dataobj['title'] = $_POST['title'];
$dataobj['date'] = $_POST['date'];
// write json_encode object to file
file_put_contents ( 'filename.json' , json_encode($dataobj));
To create a JSON in PHP :
<?php
$array = array(
"name" => "toto",
"lastname" => "lafraise",
"age" => 33
);
$fp = fopen('careers.json', 'w');
fwrite($fp, json_encode($array));
fclose($fp);
The PHP Code is here and utilizes the Twitter API Exchange PHP File
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => 'whatever',
'oauth_access_token_secret' => 'whatever',
'consumer_key' => 'whatever',
'consumer_secret' => 'whatever'
);
$query = "%23georgeezra";
$url = "https://api.twitter.com/1.1/search/tweets.json";
$requestMethod = "GET";
$getfield = '?q='.$query.'&count=5';
$twitter = new TwitterAPIExchange($settings);
$result = $twitter->setGetfield($getfield)->buildOauth($url, $requestMethod)->performRequest();
echo $result;
?>
I have run this query on the Dev tool on Twitter and the query executes as required but on Chrome and Firefox it gives a 500 ( Internal Server Error ) error while running on Apache2 server and using JQuery version 2.1.1
The JQuery Code :
$(function(){
$.ajax({
url: 'ezra.php',
type: 'GET',
success: function(response) {
if (typeof response.errors === 'undefined' || response.errors.length < 1) {
var $tweets = $('<ul></ul>');
$.each(response, function(i, obj) {
$tweets.append('<li>' + obj.text + '</li>');
});
$('.tweets-container').html($tweets);
} else {
$('.tweets-container p:first').text('Response error');
}
},
error: function(errors) {
$('.tweets-container p:first').text('Request error');
}
});
});
$result = json_decode(...)
should call json_encode, not json_decode. And $assoc = TRUE is not an appropriate second argument to json_encode.
You also need to add:
dataType: "json"
to the $.ajax call.
Turns out that the TwitterAPIExchange.php file needed cURL to work.
I ran : sudo apt-get install php5-curl followed by sudo /etc/init.d/apache2 restart and that did it.