I have a button to call a php file with jQuery in my html file,
<script>
$('#mysubmit').bind('click', function(e){e.preventDefault();
var jqueryXHR = $.ajax({
'type': 'POST',
'url': 'http://localhost/lt/resources/lists/update.php',
'dataType': 'json'
});
</script>
<input type="submit" id="mysubmit" value="Submit" />
It works but I don't know how to get the result of the php file, i.e. the php file works, make an API POST and get the result as success or error, but I don't know how to get through jQuery if the php file response is success or error.
Please help me I am a noob in Ajax and Jquery.
your php file must respond with an echo:
<?php echo "success"; ?>
in your request do something like this:
$.ajax({
'type': 'POST',
'url': 'http://localhost/lt/resources/lists/update.php',
'dataType': 'json'
}).done(function(response){ /*DO SOMETHING WITH response*/ });
use jquery ajax success property.
<script>
$('#mysubmit').bind('click', function(e){e.preventDefault();
var jqueryXHR = $.ajax({
'type': 'POST',
'url': 'http://localhost/lt/resources/lists/update.php',
'dataType': 'json',
'success' : function(returnData){
alert(returnData); // or
console.log(returnData);
}
});
</script>
<input type="submit" id="mysubmit" value="Submit" />
what every you print at PHP side it will return in "success" function
Try adding a success \ error handler to see the response:
var jqueryXHR = $.ajax({
type: 'POST',
url: 'http://localhost/lt/resources/lists/update.php',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
You should however follow #skobaljic's suggestion, and use a recognized response format such as JSON or XML - to make it easier to parse and more professional.
Using PHP it would look something like this:
<?php
$result = ..... whatever you like to return here ...
header('Content-Type: application/json');
echo json_encode($result);
?>
Related
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
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;.
I'm sending JSON to backend server, but I'm confuse about how I can process it correctly,
i'm reading around that echo (json_decode($_POST)); is not going to work but
echo (json_decode(file_get_contents("php://input")));, but actually I tried to output the response on the client side alert(respon); but nothing show
0_12_e2_contentType_JSON.html
<html>
<head>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<script >
$(function(){
$.ajax({
url: "fragment/0_12_e2_contentType_JSON.php",
type: "POST",
contentType:"application/json; charset=utf-8",
data: {
"name":"hans" ,
"id":10
},
success: function (respon)
{
alert(respon);
},
error:function(e){
alert('Ajaxnya error');
}
});
});
</script>
</body>
</html>
0_12_e2_contentType_JSON.php
<?php
echo (json_decode(file_get_contents("php://input")));
?>
My question is that is it already correct? but why does it output nothing? Thanks
If you want to send contentType:'application/json' you need to stringify the data yourself
$.ajax({
url: "fragment/0_12_e2_contentType_JSON.php",
type: "POST",
contentType:"application/json; charset=utf-8",
data: JSON.stringify({ "name":"hans" ,"id":10}),
success: function (respon)
{
alert(respon);
},
error:function(e){
alert('Ajaxnya error');
}
});
Most people would not override the default contentType and receive in php using $_POST
not clear to me Your question anyway it seems like in the end You want to answer from the server what You sended via ajax... if it is the case I would recommend to use json_encode ... not json_decode
<?php
header('Content-Type: application/json');
echo (json_encode($_POST));
?>
I want to pass two input data to PHP with JQuery ajax I read about json, serialize and similar but I couldn't quite get a grip around it. I got:
<p><input type="text" id="domain"></p>
<p><input type="text" id="domain1"></p>
<button id="order">Search</button>
<script type="text/javascript">
function callAjax() {
$.ajax({
type: "GET",
cache: false,
url: 'getip.php',
data: ???
});
</script>
And also what do I need on PHP file because I only got this.
$name=($_GET['']);
$surname =
echo($name) ;
endif;
function callAjax() {
// Get values to send to server
var domain = $('#domain').val();
var domain1 = $('#domain1').val();
$.ajax({
type: "GET",
cache: false,
url: 'getip.php',
data: {
domain: domain,
domain1: domain1
}
And in php you'll get it as
$domain = $_GET['domain'];
$domain1 = $_GET['domain1'];
Docs: http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
cache: false,
url: 'getip.php',
data = {
'domain': $('#domain').val(),
'domain1': $('#domain1').val()
};
)};
And in you php file php you can get data with :
$domain = $_GET['domain'];
$domain1 = $_GET['domain1'];
Try this:-
<p><input type="text" id="domain" name = "domain"></p>
<p><input type="text" id="domain1" name ="domain1"></p>
<button id="order">Search</button>
function callAjax() {
$.ajax({
type: "GET",
cache: false,
url: 'getip.php',
data:{domain: $('#domain').val(),domain1: $('#domain1').val()}
});
In your php file get it like this:-
$domain = $_GET['domain'];
$domain1 = $_GET['domain1'];
Note:- Please try to read jquery a bit. It will help you.
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);