AJAX POSTing to PHP isn't working - javascript

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">

Related

Cant get PHP variables using AJAX

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.

Save value in Javascript variable from $.get and use it in PHP variable

I am getting some basic info of the visitor on my site using javascript.
var userinfo = "";
//printing user info
$.get("http://ipinfo.io", function (response) {
alert("IP: " + response.ip);
alert("Location: " + response.city + ", " + response.region);
alert(JSON.stringify(response, null, 4));
userinfo = (JSON.stringify(response,null,4)); //saving json in js variable (not working, it says undefined)
}, "jsonp");
Then I want to access this value in my PHP variable:
<?php
echo $getuserinfo ; // How to store JS var here in this php var?
?>
The JS variable value is not being saved, what I am doing wrong?
And how can I store JS variable value in PHP variable?
You could make a stat page/api that you make a ajax call to from javascript.
$.ajax({
type: "POST",
url: '/setstats.php',
data: {userdata: userinfo},
success: function(){
console.log("Userdata send");
},
dataType: "json"
});
This will first be avalible at a later time then when the page initally loads, but you could now have it saved in the session for the next requests.
You are using jQuery.get method.
This method support a parameter called Data
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
After it is sent to the server to http://ipinfo.io it is available in the called script (index.php or what you have as default) in the $_GET array.
If you send data: {var1: value1, var2: value2} you will have $_GET["var1"] and $_GET["var2"]
Simply send data: userinfo and in php do a var_dump($_GET) and check what you got
I solved it by using the PHP version of the API:
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
//echo $ip;
return $details;
}
$details = ip_details($userIp);

Echo'ing php as "return value" to ajax call

My jquery code:
var value = $.ajax({
type: "POST",
url: "to_submit.php",
data: $('#submit').serialize(),
cache: false,
async: true
}).success(function(response){
console.log(response);
console.log("data received");
console.log(response.data);
$("#appended").append(response);});
}).error(function() {});
});
and PHP
include("../header.php");
$to_return = "test";
echo "\ndata: " . json_encode($to_return);
flush();
How the console.logs in the javascript part behaves:
first console.log: (a lot of code information (head, body, etc) related to my website header!)
still first console.log: data: "test"
console.log("data received");
second console.log: undefined
So, data is being recognized as undefined and a lot of code is being flushed, and I can't figure out why...
Two things: first, you shouldn't need to use flush() - simply echo your data and end your script.
Second, the results of your echo statement: data: ["insert your data here"] is not valid JSON and you're not going to be able to decode it on the client.
Change
echo "\ndata: " . json_encode($to_return);
To
echo json_encode($to_return);
Cause this string can't be parsed properly by js decoding function (it is not a valid json string).

Post JSON to PHP in AJAX for MongoDB Querying

I am constructing a Javascript object. I am using the id of user who is logged in (from a session variable) and storing it as an attribute with AJAX.
I wanted to post the resulting object as JSON via AJAX to a PHP file which then inserts the document into a MongoDB database:
var numpages=$('.page').length;
var book=new Object();
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(data){
var user=JSON.parse(data);
book.user=data.username;
}
});
book.title=title;
book.pages=new Array();
var page;
var link;
for (var i=0;i<numpages;i++){
var numlinks=$('#p'+i+' .link').length;
page=new Object();
page.text=$('#p'+i+' .textarea').text();
page.links=new Array();
for (var j=0;j<numlinks;j++){
link=new Object();
link.text=$('#p'+i+'l'+j+' .linktext').text();
link.locale=$('#p'+i+'l'+j+' .locale').text();
page.links.push(link);
}
book.pages.push(page);
}
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
success: function(msg) {
//var story=JSON.parse(msg);
console.log(msg);
//alert(msg);
}
});
}
Here is the PHP:
<?php
$dbhost = 'localhost';
$dbname = 'story';
$m = new MongoClient("mongodb://$dbhost");
$db = $m->$dbname;
$collection = $db->stories;
$story=$_POST['json'];
if (isset($story)){
$collection->save($story);
}
?>
The document is being inserted into the database but I get this:
Notice: Undefined index: json
You have two problem, first being that ajax is async unless you specify the async flag to false which you probably don't want to do so:
book.owner=data.username;
Is likely to actually be empty when you come to JSON encode in the second ajax call.
To solve this you can use JQuery promises like so:
$.get().done(function(data){
/// extra processing
}).then(function(){ $.get() // etc });
This will ensure that one Ajax calls runs after the other.
As for the missing index you don't actually need to stringify your data at all instead you can just do:
$.get('some_url', {book: book})
And JQuery will actually serialize it for you ready for PHP.
This
JSON.stringify(book),
creates an object something like:
{"title":"East of Eden","author":"John Steinbeck"}
better completely remove the JSON.stringify() bit and just pass the book variable
And it in the ajax call it should be type: "POST", not method: "POST"
So in your php script you can do
$_POST['title'];
$_POST['author'];
Hope that helps
If you want to work exclusively with JSON, you should set your content-type header to application/json and then read that content from PHP raw input:
The javascript:
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
contentType: 'application/json',
success: function(msg) {
alert(msg);
}
});
The PHP:
$story = file_get_contents('php://input');
So really you just need to add one line of code and change another.
The reason $_POST['json'] was not being populated is that nowhere did you define a query string (or let jQuery define for you) that has a key json.
You could have, for example done something like this:
data: {'json': JSON.stringify(book)}
And that would have populated $POST['json'], but again if all you are looking to do is pass around a JSON string and directly insert it into Mongo, there is no reason to use form-encoding for this at all, just work with raw POST data.
Note also the problem mentioned by #Sammaye about needing to properly work with event delegation.

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