Cant get PHP variables using AJAX - javascript

I can't seem to figure out what's the problem. For my next little project I'm creating dynamic web page with database and etc. I need to get all the necessary variables from PHP file. But for some reason I cannot do it if I include another PHP file. (I need it for database queries).
main.php
include ('databaseQueries.php');
if (isset($_POST["points"])){
$points = json_decode($_POST["points"]);
if($_POST["execute"] == 1){
}
}
$advert= array(
'Hello' => 'Hello world!',
'bye' => 'Why bye?',
);
echo json_encode($advert, $another);
pageJs.js
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
databaseQueries.php
$another = "another string";
If I remove the include and $another variable from json_encode. Everything works and I get object in console log. But if I leave the those two things, Ajax call fails.
What I'm doing wrong and how can I get both the $test array and $another variable?
Thank's in advance!

You are using json_encode incorrectly. From the documentation:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
You are trying to send $another to the function as the options parameter.
You could do something like this:
$ret = array($advert, $another);
echo json_encode($ret);

Unless I'm completely wrong, I can't see where you're sending anything TO your post
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json'
// I would expect a data call here, something like:
data: $(form).serialize(), // OR { points: 3, execute: 1 }
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
I assume that you want to spit back some results with the format of result->key;
So Keeleon's answer above is good:
$ret = array($advert, $another);
echo json_encode($ret);
But you can also do:
//Adding everything to array, and asking json_encode to encode the array is the key. Json_encode encodes whatever is in the first argument passed to it.
$ret = array('advert'=>$advert, 'another'=>$another,'test'=>$test);
echo json_encode($ret);
Hopefully, this answers your questions.

Related

AJAX POSTing to PHP isn't working

I am trying to POST a JSON to PHP where it should be decoded and pushed to MySQL database.
This is my JavaScript code.
var dictstring = "{sensorid: \""+ name +"\", x: " +pos.x +" ,y: "+pos.y+"}";
console.log(dictstring);
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
url: "myfile.php",
data: JSON.stringify(dictstring),
success: function(data){
alert('Success');
},
error: function(e){
console.log(e.message);
}
});
And this is my PHP code
<?php
$jsonData = file_get_contents('php://input');
$data_back = json_decode($jsonData);
$unit = $data_back->{"sensorid"};
$x_axis = $data_back->{"x"};
$y_axis = $data_back->{"y"};
// Create connection
$con=mysqli_connect("xxxxxxx:xxxx","xxxxx","xxxx","xxxxxxxx");
// Check
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert Values
$sql_hm = "INSERT INTO xxxx(unit, x_axis, y_axis)
VALUES ('$unit', $x_axis, $y_axis)";
if ($con->query($sql_hm) === TRUE) {
echo "values inserted successfully";
} else {
echo "No data ";
}
?>
I know the PHP part works - I tried POSTing JSON data with contentType: application/json from a REST client app and it works. But when I am trying it with my Javascript code, it isnt POSTing. I can see the "dictstring" string value in console. I cannot see the "Success" alert too. Interestingly, "Success" alert is shown if I remove the dataType: "json" line. But, POSTing is still not happening as I cannot see the values in database.
What am I missing here?
var dictstring = "{sensorid: \""+ name +"\", x: " +pos.x +" ,y: "+pos.y+"}";
You have a string.
data: JSON.stringify(dictstring),
Which you then convert to a JSON representation of that string.
$data_back = json_decode($jsonData);
Which you decode to a string.
$unit = $data_back->{"sensorid"};
Which you try to treat like an object.
Start with an object, not a string:
var dictstring = { sensorid: name, x: pos.x, y: pos.y };
… you probably want a different variable name too.
dictstring is already in JSON format, you don't need JSON.stringify in your JS
dataType: "json" is to be used if the data returned from server is JSON
You can create an array of messages and then use echo json_encode($array); to return JSON data to your js.
Coming to your problem, from the question and the information you've supplied, I couldn't find an obvious problem, but I could suggest to use console.log(data) in your success function and see what is returned. You'll at least know if it hit your php page or returned with some error like 404 or 500.
Try $data_back['sensorid']
or
Just print_r($data_back); and see the data structure of $data_back and then try access the data accordingly.
Okay it might sound silly but have you made sure to state that you're using JQuery in the java script because the amount of times I've been doing ajax and i cant figure out why it wont work and its because I haven't declared the JQuery.
like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">

How to iterate with javascript a json response from symfony2

i want to itarate a json response from symfony and put it in a table td>
my action :
$search = $this->getDoctrine->...;
$serializer = $this->get('serializer');
foreach ($search as $key => $value) {
$search[$key] = $serializer->serialize($value, "json");
}
$reponse = new JsonResponse($search);
return $reponse;
this is what i have in my twig ( i examine it with Firebug ):
i have a to display at least something but sometimes i have undefined or nothing ... this my javascript function
$(document).ready(function () {
var dataString = $("form").serialize();
var typerequest = $("form").find('input[name="typerequest"]').val();
$('#filtreperseance').ajaxForm({
type: "POST",
url: Routing.generate('myroute'),
data: dataString,
success: function (response) {
$.each(response, function (cle, valeur) {
$("#test").html(valeur);
});
}
});
});
EDIT 1 : Console.log
EDIT 2 :
I'd try to cut down the problem. First make sure, the JSON is valid and looks the way you expect. Don't use jQuery at this point. Call the symfony controller in your browser directly. Then check the json. http://jsonviewer.stack.hu might be of use.
Once you verfified that the JSON itself is valid and contains what you need, we can look at the jQuery part. Then we'd need the code and the errors you get.
i have done a mistake when i returned the JSOn from Controller . its Ok now

AJAX/JS/PHP: How to replace text in file sent to PHP file, and pass successful attribute?

I have this button by ID of genPDF, which if clicked has this function:
$('#genPDF').click(function () {
var str = "headingText=" + jQuery("#headingText").val();
$.ajax({
url: 'indexpdf.php',
data: str,
dataType: "json",
type: 'post',
success: function () {
console.log("Success!");
}
});
})
It's supposed to take the text from input "headingText" and send to the php file indexpdf.php.
Then here's my indexpdf.php:
<?
$headingText = trim(isset($_POST['headingText']) ? $_POST['headingText'] : '');
$initialpdf = file_get_contents('file_html.php');
$initialpdf = str_replace(array(
'%headingText%'
), array (
$headingText,
), $initialpdf);
file_put_contents($fp, $initialpdf);
?>
This file is supposed to decalre the headingtext variable from the previous page, and replace each "%headingText%" in file_html.php, then save this html/php file as "file_html2.php"
The problems are, I don't think I'm saving the finalized php file right, and for some reason, while passing the "str" into the ajax php call, it doesn't succeed. If I get rid of the line, "data: str,", it succeeds.
How can I pass in these string variables, replace them in the php file, and save that file as a different file succesfully? What's wrong here?
An Alternative Way
<script>
$('#genPDF').click(function () {
var str = $("#headingText").val();
$.ajax({url:"indexpdf.php?headingText="+str,cache:false,success:function(result){
console.log("Success!");
}});
})
</script>
Use _GET
<?
$headingText = trim(isset($_GET['headingText']) ? $_GET['headingText'] : '');
$initialpdf = file_get_contents('file_html.php');
$initialpdf = str_replace(array(
'%headingText%'
), array (
$headingText,
), $initialpdf);
$initialpdf->saveHTMLFile("file_html2.php");
?>
You want to pass an object to data. For this, replace:
data: str
with:
data: { headingText: jQuery("#headingText").val() },
This should pass the value correctly
First Part
You are forcing ajax request to json type and trying to post data as string thats why its not working, try posting your headingText in JSON format i.e.
data: {headingText: jQuery("#headingText").val()}
this will make sure you receive data in PHP
Second Part
After making all the changes you can use alternate function to file_get_contents to store file once manipulation is done i.e. file_put_contents
Use it like
$initialpdf = file_get_contents('file_html.php');
$initialpdf = str_replace(array(
'%headingText%'
), array (
$headingText,
), $initialpdf);
file_put_contents("file_html2.php", $initialpdf);
this should address your both issues.
Try sending it as a json object instead of a string.
str = {headingText:'blabla'}

response from php to javascript via json

I have this function in php
public function get_updated_session_value()
{
$sql = "SELECT IF(Session = 12345678 , 1,0) AS login FROM `psf_users` WHERE id = 236";
$var = $this->addDb($sql)->execute();
$Session = $var['login'];
return json_encode('2');
}
and the javascript code to fetch this value,
function check() {
$.ajax({
url : 'auctions.php',
type : 'get',
// dataType: 'json',
data : {page:'__request', module:'PSF_auctions', action:'get_updated_session_value'},
success: function(data) {
console.log(data);
}
});
}
also, this function runs every 5 seconds via
setInterval(check, 5000);
the problem is, console.log(data); prints nothing, i believe that means it is not getting any data (or json response) from the php function. am i missing something?
It can't work as you're returning the value. The difference between returning a value and emitting a response is that the latter writes a response on the HTTP stream whilst the first one merely returns the control to the parent with a specific value.
Sanjay has spotted it very well, and I'd recommend that you use a very simple function to wrap up your responses:
function emit_response( $status_code, $data ) {
http_response_code( $status_code ); // 200 is it's success. find more http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
die( json_encode( array(
"status_code" => $status_code,
"data" => $data )));
}
Then modify that echo (though it's fine as well) with
emit_response( 2 );
and since the response is valid JSON, JavaScript will love it; in your callback, you can simple do this:
success: function(res) {
var response = JSON.parse( res );
// response.data will be 2. :)
// ... rest of the code ...
Replace return with echo like this:
public function get_updated_session_value()
{
$sql="SELECT IF(Session = 12345678 , 1,0) as login FROM `psf_users` WHERE id=236";
$var= $this->addDb($sql)->execute();
$Session= $var['login'];
echo json_encode('2');
}

PHP + Javascript parse both responses

I have two problems. One is totally in PHP the other in Javascript. But both are equal in what I'm trying to get.
index.php
$.ajax({
type: "post",
url: "insert_info.php?type=info",
data: { array : all },
success: function(data) {
alert(data);
// Returns: {'status':1}
// I want to get "1"
// data[0] -> doesn't work
}
});
insert_info.php
// Connects to another file
include_once('verify_info.php');
$verify = new verify_info();
$arr = array("status:" => 1);
$extension = $verify->verify_file($_REQUEST['array'][9]);
if($extension[0] == 0){
$arr = array("status:" => 0);
}
echo json_encode($arr);
verify_info.php
public function verify_file($file){
$extensions = array('jpg', 'png', 'jpeg', 'bmp');
$info = pathinfo($file);
$arr = array();
if(!in_array($info['extension'], $extensions)){
$arr = array("status:" => 0);
}else{
$arr = array("status:" => 1);
}
return $arr;
}
In insert_info.php, I would like to get by $extension[0] the status retrieved from the function verify_file();
After that I output as json_encode the value to Javascript and I would like, again, to parse the info.
What am I doing wrong? Thanks.
Edit 1: alert(data.status); doesn't work either.
Edit 2: alert(data.status); would never work since I echo {'status:', 1} (problem with that two points in the middle)
Correct way for solving the issue of javascript:
var obj = jQuery.parseJSON(data);
alert(data.status);
I'm still trying to get fixed the php.
Edit 3: All solved. Thank you guys.
public function verify_file($file){
$extensions = array('jpg', 'png', 'jpeg', 'bmp');
$info = pathinfo($file);
if(!in_array($info['extension'], $extensions)){
return false;
}
return true;
}
As I said in my comment, your setting your key in PHP to "status:" is the trailing colon necessary on the end of your key? I don't think it's necessary, PHP arrays already offer mechanisms for fetching them and your JSON will contain the string without processing it so your key once you hit your JS code will still be "status:" where most likely you intended for "status".
Regardless of whether you will make this change or not that doesn't break anything. In your Javascript code, as #charlietfl pointed out, you should be setting the dataType of the return to "json" so you're JS Ajax call would look like:
$.ajax({
type: "post",
url: "insert_info.php?type=info",
data: { array : all },
dataType: "json",
success: function(data) {
// Assuming no change on the backend
alert(data["status:"]);
}
});
If, however, you altered the string to remove the colon then accessing the status element of data would be data.status as #A.Wolff pointed out in his comment. This doesn't work because of the trailing colon in the key - but accessing the data with a string key will still work.

Categories

Resources