I'm trying the Fetch API for the first time and I'm trying to POST a variable to a PHP script. I did this same this with jQuery.ajax() which did work.
var myRequest = new Request('invoeren.php', {method: 'POST', body: JSON.stringify({name: name})});
fetch(myRequest).then(function(response) {
console.log(response);
});
This returns to me Undefined index 'name'.
What am I doing wrong?
The working jQuery code:
$.ajax({
url: "invoeren.php",
method: "POST",
data: { name : name}
}).done(function( msg ) {
console.log(msg);
}).fail(function( jqXHR, textStatus ) {
alert( "Naam is niet ingevoerd door een probleem: " + jqXHR );
});
The PHP Script:
try {
$dbh = new PDO('mysql:host=localhost;dbname=ajaxoef', $user, $pass);
$stmt = $dbh->prepare('INSERT INTO names(name) VALUES (:name)');
$stmt->bindParam(':name', $name);
$name = json_decode($_POST['name']);
$stmt->execute();
echo "Naam is ingevoerd.";
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
The working jQuery code
data: { name : name}
… so when you used jQuery you send WWW URL Form Encoded data (the default jQuery encoding).
body: JSON.stringify({name: name})
… but when you switched to fetch, you also converting the object to JSON.
JSON is not WWW URL Form Encoded!
You, presumably, haven't rewritten the PHP to expect JSON, and are probably trying to read from $_POST (which is empty, because PHP doesn't support JSON encoded requests by default).
You can construct a FormData object which will be encoded in a way that PHP will parse by default.
var body = new FormData;
body.append("name", name);
//...
body: body
Related
So I have a js file that posts a JSON object using $.ajax, and then my php script takes that JSON object and does stuff to it, however, i can't get a json response back from the php script (the success callback function never runs).
register_script.js:
$.ajax({
method: "post",
dataType: "json",
url: "http://localhost/login/webservices/register2.php",
data: {
reg_username: username,
email: email,
reg_password: password,
confirm_password: confirm_pass
},
success: function (data) {
alert("hello?");
//alert(data.status);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
});
register2.php:
if (isset($_POST['reg_username'], $_POST['email'], $_POST['reg_password'], $_POST['confirm_password'])) {
$username = $_POST['reg_username']; //$_POST['from html']
$email = $_POST['email'];
$password = hash('md5', ($_POST['reg_password']));
$confirm_password2 = hash('md5', ($_POST['confirm_password']));
$sql = "INSERT INTO users (username, email, password) VALUES ('$username','$email','$password')";
if ($password == $confirm_password2) {
$response = sqlsrv_query($conn, $sql);
if ($response) {
$data = array(
"username" => $username,
"email" => $email,
"password" => $password,
"confirmPass" => $confirm_password2,
"status" => "Registered",
);
echo "Registered \n";
}
}
}
//...
//some other validations
//...
echo json_encode($data);
I have a feeling the way i am handling the json object is incorrect. any help would be really appreciated.
you should not
echo
anything other than json_encode when working with ajax dataType : json you have
echo "Registered \n";
before
echo json_encode
remove that and it should work
EDIT:
when you set the dataType : "json" in your ajax call then the response is expected to be in json when the call is finished, and any text other than json encoded string in response will result in an error. if you still need to debug and see what route the script is taking, you can add another index in $data (i assume that $data is an array), so it would be like
if($registered){
$data['debug_logs'] .='Registration successfull----';
}
if($emailSent){
$data['debug_logs'].='Email sent for registration-----';
}
echo json_encode($data);
and then in your ajax success function you can use it like
success:function(data){
console.log(data.debug_logs);
}
hope it clears your confusion.
Please remove echo "Registered \n"; the line from your code when you echo "Register"; the Ajax request return this back to the browser, and your actual data echo json_encode($data); never return back to the browser.
Afternoon guys/gals,
I'm relatively new to using AJAX to POST information to a JSON file and I am not sure what the .php file should look like to process it. I have very little experience with .php. Am I on the right track? I've looked a lot of examples but most of them only have pieces of the .php file to process it. I am trying to inject the "task" into the JSON file which I then use handlebars to read on another page.
function fnCreateTask() {
var url = "save.php";
var title = $("#TaskTitle").val();
var date = $("#TaskDate").val();
var desc = $("#TaskDescription").val();
var info = {
Title: title,
Date: date,
Description: desc
};
var body = JSON.stringify(info);
$.ajax({
type: "POST",
url: url,
contentType: 'application/json',
data: body,
dataType: 'json',
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
}
<?php
$fp = fopen('careers.json', 'w');
fwrite($fp, $_POST = json_decode(file_get_contents('php://input'), true););
fclose($fp);
?>
$.ajax POST (or GET for that matter) data will be x-form encoded by default when sent to the server. You can do
on the client
//object for the data
var data = {
title: $("#TaskTitle").val(),
date: $("#TaskDate").val()
};
$.ajax({
type: "POST",
url: "save.php",
data: data,
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
and on the server
// as a separate object to be safe
$dataobj['title'] = $_POST['title'];
$dataobj['date'] = $_POST['date'];
// write json_encode object to file
file_put_contents ( 'filename.json' , json_encode($dataobj));
To create a JSON in PHP :
<?php
$array = array(
"name" => "toto",
"lastname" => "lafraise",
"age" => 33
);
$fp = fopen('careers.json', 'w');
fwrite($fp, json_encode($array));
fclose($fp);
Right so I have a angular function that is sending data to a php file using the http method.The php code I want to process the data and echo it back onto the page to confirm that the php file has processed it. I'm currently getting undefined alerted back to me, surely I should be getting the vaule of email back to me?. Thanks all
I'm following this tutorial https://codeforgeek.com/2014/07/angular-post-request-php/
var request = $http({
method: "post",
url: "functions.php",
data: {
email: $scope.email,
pass: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
//.then occurs once post request has happened
//success callback
request.success(function (response) {
alert(response.data);
},
//error callback
function errorCallback(response) {
// $scope.message = "Sorry, something went wrong";
alert('error');
});
My php code...
//receive data from AJAX request and decode
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$email = $request->email;
#$pass = $request->pass;
echo $email; //this will go back under "data" of angular call.
From the documentation:
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
Your code should look like this:
request.then(
function( response ) {
var data = response.data;
console.log( data );
},
function( response ) {
alert('error');
}
);
Now, you need to encode the response from the server in a JSON format, so replace echo $email; with:
echo json_encode( array(
'email' => $email
) );
And you can access the email property from the angularjs $http.success promise callback function (it's the first function inside the then closure) by response.data.email
I have the following jquery function which is supposed to post data to a php function which in the process it passes it to the external script for processing.
Below is my jquery function :
function order_confirmation(json) {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>home/confirm_order_received/",
data: json,
contentType: 'application/json',
dataType: 'json',
success: function (data) {
console.log(data);
},
failure: function (errMsg) {
console.log(errMsg);
}
});
}
This function is supposed to pass the json data to my php function which is below here :
function confirm_order_received() {
$json = $this->input->post('json');
// Initialize curl
$curl = curl_init();
$externalscriptaddress = "http://197.237.132.178/api/order/order_upsert";
// Configure curl options
$opts = array(
CURLOPT_URL => $externalscriptaddress,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $json
);
// Set curl options
curl_setopt_array($curl, $opts);
// Get the results
$result = curl_exec($curl);
// Close resource
curl_close($curl);
echo $result;
}
I have a problem of how I am supposed to access the data from the php side, I have tried accessing it through the post : $json = $this->input->post('json'); and passed it to the CURLOPT_POSTFIELDS => $json but I get an error since nothing has been passed. Please advise how can i pass the json data to an external script?
For getting raw post data (in your case) use file_get_contents("php://input")
Instead of data: json, you should use data: "json:json",
Using just data: json, will post the data, but it will not be assigned to a key. To access the data ou need to assign it to a key. By using data: "json:json",, you can access it with $json = $this->input->post('json');
I am new to Ajax & JavaScript. But i am stuck with this error. I am making post request using Ajax.
var sentdata = {"name":"gourav", "email":"email"};
var sentd = JSON.stringify(sentdata);
this.url = "http://localhost/Working/board.php";
$.ajax({
type: "POST",
url: $(this).url,
data: sentd,
contentType: "application/json",
//dataType : "json",
success: function (response) {
alert(response.message);
console.log( "Done with success: ");
},
error: function (xhr, thrownError) {
alert(thrownError);
}
});
I am calling this request to simple code where i am not even checking the $_POST variable and just trying to write some data in mysql table.
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, true);
// selecting database
mysql_select_db(DB_DATABASE, $con);
if(1)
{
$tb_name = "tb_appuser";
$name = "name1";
$email="email1";
$deviceId="0";
$platform="1";
$query = sprintf("INSERT INTO %s (user_name, email, device_regid, platform_type) VALUES ('%s', '%s', '%s', '%d')" , $tb_name, $name, $email, $deviceId, $platform);
echo "$query\n";
$res = mysql_query($query);
}
I already tested this board.php code and verified it is inserting the data in table.
But when i am doing this via $ajax i am getting "The page at localhost says: undefined" and nothing got written in my database also.
url: this.url, not $(this).url.
$(this) does not have a property called "url" in your context I think.