I am trying to do an ajax request to my php, but for some unknown reason it seems to fail as i don't get to the success part where I have a console.log
Can anyone please give me some hint what might be wron with this, I am stuck for too long now??
Here is how my jQuery looks :
getPending();
function getPending(){
var usernameLS = localStorage.getItem('userNameLS');
var userTypeLS = localStorage.getItem('isAdminLS');
if (userTypeLS!=1) {
console.log("inside");//i am getting here
$.ajax({
type: "POST",
dataType: 'json',
url: 'get-pending.php',
data: {
data: usernameLS //this is a string, "user2" for instance
},
success: function(data) {
console.log("Thanks!!!",data);//i never got here
},
failure: function() {
console.log("Error!");
alert(' Fail');
}
});
}
And here is my php :
<?php
$string = file_get_contents("appointments.json");
$usernameAjax = $_POST['data'];
var_dump($usernameAjax);
$json_a = json_decode($string, true);
$isPending;
foreach ($json_a as &$json_r) {
if ($usernameAjax==$json_r['userName'] && $json_r['status'] = "Pending") {
$isPending = 1;
}
else{
$isPending = 0;
}
}
var_dump($isPending);
echo $isPending; //i tried with a hardcodede 1 or 0 zero. Didn't work.
?>
Seems like your output is not correct JSON format, so client-side cant understand what was recieved.
First - remove var_dump, it breaks json format anyway;
Second - jou just output 1 or 0 - that is not correct json too; use json_encode to format reply properly;
Third - php files often contains trailing symbols after ?>, that are appends to output too and could break output format. Dont close php with ?> at all; additionally you could use die($output) instead of echo($output) to avoid any output after your data was written
Related
I'm trying to extract the information with a XHR request (AJAX) to a php file (this php file gets the information throught json file with Get request too) so when I try to do console.log(Checker) on the console, it returns Undefined and if I put alert(Checker) it returns [object Object]. How can I solve it?
PHP:
<?php
headers('Content-Type', 'application/json')
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents
?>
JS:
function start() {
$.ajax({
type: 'GET',
url: 'api/domain/showall.php',
dataType: 'json',
success: function(data) {
alert(data)
displayTheData(data)
}
});
}
function displayTheData(data) {
Checker = data;
JSON.stringify(Checker)
console.log(Checker)
window.Checker = Checker;
}
JSON:
[{"name":"Google","url":"google.es","id":1}]
Here you are strigify data but not store value i any var.
function displayTheData(data) {
Checker = data;
var displayChecker = JSON.stringify(Checker) /// add displayChecker
console.log(displayChecker ) // print it
window.Checker = Checker;
}
There is not displayTheData() function so first call it and pass response params.
You need to echo the JSON Response ! Change return $jsonContents; to echo $jsonContents; it will work !!!
You must parse data into body (not returning it which has no meaning outside a function) and, optionnaly but much better, fill some headers. A very minimalistic approach could be :
<?php
headers('Content-Type', 'application/json');
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents // echo JSON string
?>
I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST
I want to pass a javascript array to php to print the values, but it is not working. What am I doing wrong?
javascript
$('#Enviar0').click(function() {
var buttons0 = [];
for(var i=0;i<4;i++){
buttons0[i]+= $('butEnv'+i).val();
alert($('butEnv'+i).val());
}
var array=buttons0.toJSONString();
$.ajax({
type:"POST",
url:"pintaParte.php",
data: {encapsulado:array},
success: function(data) {
$("#pinta").html(data);
}
});
});
php
$buttons0=parseJSON($_POST['encapsulado']);
foreach ($buttons0 as $value) {
echo $value.'<br>';
}
use JSON.stringify() on the client side:
$.ajax({
type:"POST",
url:"pintaParte.php",
data: JSON.stringify({encapsulado:array}),
success: function(data) {
$("#pinta").html(data);
}
});
Do you check if your array is ok in the php side (after the ajax call) ?
If you can't get your array in the php side, maybe in your javascript try to simply use...
data : "encapsulado=" + array
And in your php code, try to put all values of the array in one string and just make only one echo and then a return.
$str = "";
foreach ($buttons0 as $value) {
$str = $str.$value.'<br>';
}
echo $str;
return;
Try to use a tool like firebug or the Chrome dev tool to see parameters and responses in your http requests and be abble to localize the error (in the client side or in the server side).
Hope this helps !
Hi I would like to output the code in [json['information'] as actual converted html code.
At the moment it seems to be just outputting the entire string as pure text (unformatted html, so you can see all the tags etc)
Im still learning about json so am unsure what is supposed to be done with the content recieved to make it proper html.
Thanks in advance
$('.engineering-services').live('click', function() {
$.ajax({
url: 'index.php?route=information/information/homepage_info',
type: 'post',
data: {info_for : 'engineering'},
dataType: 'json',
success: function(json){
$('#engineering-content').html(json['information']);
},
error: function(json) {
alert('fail');
}
});
});
EDIT, heres the PHP ...
public function homepage_info() {
$this->load->model('catalog/information');
$json = array();
if (isset($this->request->post['info_for'])) {
if ($this->request->post['info_for'] == 'engineering') {
$information_info = $this->model_catalog_information->getInformation(10);
$json['information'] = $information_info['description'];
}
$this->response->setOutput(json_encode($json));
}
}
Your HTML strings seem to be encoding special characters as HTML entities, like < to <, etc. From the PHP you've shown, it's probably encoded in the database (maybe you're encoding before saving).
You should be able to fix it with html_entity_decode:
$json['information'] = html_entity_decode($information_info['description']);
// or, a few lines later:
// $this->response->setOutput(html_entity_decode(json_encode($json)));
Looks like you are using Open cart for you php controller. In order to send back a a response with the proper json headers the Open Cart way is as follows:
$this->load->library('json');
$this->response->setOutput(Json::encode($json));
Hope that helps.
I'm still in AJAX stuff since morning so maybe thats the reason why some things does't work as they schould - let's forget about it. To sum up, my problem is coincident with passing HTML via JSON. An example of the PHP code:
$list = "<strong>This is test</strong>";
$response = array('success'=>true, 'src' => $list);
echo json_encode($response);
Basicly that's the main part of the code which is responsible for passing the HTML to AJAX. Now, let's have a look on part of AJAX code:
success: function(output)
{
alert(output);
json = $(output).find(".content").text();
var data = $.parseJSON(json);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
Some of you will ask what am I doing in this part:
json = $(output).find(".content").text();
The answer is: I retrieve the json string from the ".content" box, so when I alert variable "json: i get:
{"success":true,"src":"1. dsfasdfasdffbcvbcvb<\/span>Edytuj<\/span> <\/a>Usu \u0144<\/span><\/div>2. vbnvbnm454t<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div>3. ndfhgndgfhndfhgndfhd<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div><\/div>"}
The problem is that I do not get this HTML... I get only text witout any HTML tags, styles etc...
String which I get, rather than HTML:
"1. dsfasdfasdffbcvbcvbEdytujUsuń2. vbnvbnm454tEdytujUsuń3. ndfhgndgfhndfhgndfhdEdytujUsuń"
Please don't try to look for anything smart or gunius in the above string because u won't - it's only a test string.
Acording to the part of PHP code - in my case I get "This is test" rather than "This is test".
To sum up my question is, how to pass these HTML tags or whole HTML code via json from PHP to AJAX.
I think you're misunderstanding how jQuery.ajax() works. You just need to tell it that dataType: 'json' (meaning that you're expecting JSON output from the server), and it takes care of the rest. You don't need to use jQuery.parseJSON(). The success() method will be given a JavaScript object representing the server response.
success: function(output)
{
// output is a JS object here:
alert(output.success); // true
// ...
},
To get your HTML from that point, you would just access output.src.
You can specify dataType: 'json' in your ajax request and receive an object(i.e. json already parsed) in your success call. eg
$.ajax(url, {
dataType: 'json',
success: function(output)
{
if(output.success == true)
{
obj_a.parents(".row").append(output.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
if you can't change dataType you would call $.parseJSON on output
function(output)
{
alert(output);
var data = $.parseJSON(output);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},