Given below is the ajax call from the javascript
let dataX = {"VERSION": "iVersion_100", "ITOKEN": "iToken", "METHOD":"GSB"};
$.ajax({
type: "POST",
url: "target.php",
data: dataX,
dataType: "json"
})
.done(function(data) {
console.log(data);
});
Now, here is the simple target.php
<?php ob_start();
$iVersion = $_REQUEST['VERSION'];
$iToken = $_REQUEST['ITOKEN'];
$iMethod = $_REQUEST['METHOD'];
echo $iVersion;
?>
I was expecting to see "iVersion_100" in the console log. Instead, it is returning NULL. I have almost broken the wall with my head banging. Request your help desperately. Thanks in advance.
You're setting dataType: "json"
but the PHP responds with iVersion_100
this is not valid JSON
as you have no .error handler, it seems jQuery "silently ignores" this error condition and the end result is that .done is never called
change your code to
let dataX = {"VERSION": "iVersion_100", "ITOKEN": "iToken", "METHOD":"GSB"};
$.ajax({
type: "POST",
url: "target.php",
data: dataX,
dataType: "json"
})
.error(function() {
console.log(arguments);
})
.done(function(data) {
console.log('hello');
console.log(data);
});
You'll see there is an error, "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
Since you are using dataType: "json" in this code your are telling ajax to get return data in json format.
In place of sending data in json your are just echo $iVersion; echo the data. If you want to use json as dataType please parse data before output it like this echo json_encode($iVersion); and you will get the data.
Or
If you want to use simple out put in none json format please Remove dataType: "json" from ajax attribute. You will get the output echo $iVersion;.
Related
I'm stumped why my Flask called JSON data is not being read by ajax success wait statement that works very well elsewhere. I realize the Success: statement is supposed to wait for data to returned and it does, but then the data returned isn't accessible as any JSON. There are no console nor browser console errors to indicate why data is considered 'invalid'
Flask Function
#blueprint.route('/target_liner')
def target_liner():
ind_id = int(request.args.get('ind_id'))
label = "1508 Loss Correction"
data = '[{"Program_Name":"' + label + '"}]'
return data
JSON Data
[{"Program_Name":"1508 Loss Correction"}] // This is confirmed legal JSON
Javascript
function updates() {
$.ajax({
url: "/target_line",
method: "GET",
data: {
ind_id: 1508
},
success: function (data) {
console.log(data);
alert(data); // This shows the JSON string correctly in Chrome Inspect console
alert(data.Program_Name);
alert(data[0]['Program_Name']);
alert(data[0].Program_Name );
}
});
};
updates();
The data retuned is a String. You can either do a JSON.parse(data) after the success or you can use dataType: 'json' in your ajax request. you might get a parse error if your JSON String is not formed properly when you use dataType: 'json' .
You have three possibilities:
in your flask change return data to return jsonify(data);
add dataType: "json", to your ajax call as per comment by #Rocket Hazmat;
add to the succes response a conversion from string to json: data = JSON.parse(data);
$.ajax({
url: "/target_line",
method: "GET",
data: {
ind_id: 1508
},
success: function (data) {
data = JSON.parse(data);
console.log(data);
console.log(Object.keys(data[0])[0]); // print: Program_Name
console.log(data[0].Program_Name ); // print: 1508 Loss Correction
}
});
I am creating simple application which will insert log data into database table.
Going with jQuery Ajax POST method and JSON format for data.
My index.php has HTML and this code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.ajax({
type: "POST",
url: "http://www.example.com/ajax_model.php",
data: {
"log_session": "27738d7552b75ae395ae1138adf4fa60",
"log_ip": "1.2.3.4",
"log_vrijeme": "2018-11-23 01:22:47",
"log_model": "12345"
},
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(response) {
console.log(response);
alert(response);
},
error: function(error) {
console.log(error);
}
});
});
</script>
My ajax_model.php - which gives me response Array[] instad the data which is sent:
<?php
if(isset($_POST)){
header('Content-Type: application/json');
echo json_encode($_POST);
exit;
}
?>
I am getting result in my console.log() and alert() - Array[].
How can I output my sent response to check if the data was correctly sent over Ajax?
Am I missing some brackets like [] or {}?
Or do I need to add something to my ajax_model.php file?
Thank you for suggestion and provided information.
You aren't sending JSON so get rid of:
contentType: 'application/json; charset=utf-8',
That will cause $_POST to be empty as the default contentType is:
application/x-www-form-urlencoded; charset=UTF-8
I want to know how I can pass data from my script javascript to my php code to use the data into a query
I tried many things but it didn't work for me
So this is my script to upload files from input type: file then i get the url in downloadURL variable
var downloadURL;
...
uploadTask.on('state_changed',function(snapshot){
},function(error){
},function(){
downloadURL=uploadTask.snapshot.downloadURL;
alert(downloadURL);
});
Now I want to pass downloadURL to my php so I can use it .
I also tried Ajax to do this task but it didn't work or the code that I used is false
Ajax code :
$.ajax({
type: "POST",
url: '', //same page
data: downloadURL ,
success: function(data)
{
//alert(data);
}
});
EDIT
Php code :
<?php
$user=$_POST['downloadURL'];
echo $user;
?>
Just a normal echo to test if data is Posted or not
Structure the data of your $.ajax request in a name-value pair manner.
Change this:
$.ajax({
type: "POST",
url: '', //same page
data: downloadURL ,
success: function(data)
{
//alert(data);
}
});
To this:
$.ajax({
type: "POST",
data: {"downloadURL":downloadURL} ,
success: function(data)
{
//alert(data);
}
});
I also removed url from your $.ajax request because by default url is set to the current page.
With the above modifications, your PHP code will remain unchanged (e.g., $user=$_POST['downloadURL'];).
Okay change your php with that code:
if(isset($_POST['downloadURL']) {
$response = array(
'user' => $_POST['downloadURL']
);
echo json_decode($response);
exit;
}
Because you are making ajax request you must return json that why we parse our Array to json(object) and then in your javascript ajax request inside success function write
console.log(data);
And after data
...
data: downloadUrl,
Add this
dataType: 'json'
This mean we are telling on our ajax request that we are expecting json response
Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);
Okay so here is my problem. I have a simple jQuery Ajax request and I can't get is work when I set the DataType to "JSON".
var form_data = { "id": msg, "token": token };
$.ajax({
type: 'POST',
url: "ajax.php",
data: form_data,
dataType: 'json',
beforeSend:function(){
// this is where we append a loading image
},
success: function(data) {
var thing = JSON.parse(data);
$('.body-item').html(thing.b);
},
error: function() {
alert('error');
}
});
This is my ajax file actually. The ajax.php looks like this:
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$foo = json_encode($arr);
echo $foo;
When I run the jQuery script, I got a 200:OK response with Firebug, and when I take a look at the response I got the following: {"a":1,"b":2,"c":3,"d":4,"e":5}
However I do NOT get anything showed in the .body-item div, nor if I try with alert().
Also if I run the same code WITHOUT the: dataType: 'json' part, I get everything outputted correctly.
What could be the issue here?
When you use dataType: 'json', jQuery calls JSON.parse() and puts the result in data. You shouldn't call it yourself, since data is not a JSON string, it's the parsed object. So just do:
$('body-item').html(data.b);
From the documentation:
"json": Evaluates the response as JSON and returns a JavaScript object.