I'm trying to send data from the browser's local storage to php using AJAX, when I test the API using postman by inserting this data(POST)
[
{
"product-id": "32",
"product-name": "Reese Stevenson",
"product-description": "Ea tempore temporib",
"product-image": "Screenshot_3.png",
"product-price": "778 "
}
]
which is the same data in local storage I get back this object as a response(POST & GET METHODS) which is the thing I want for the moment (starting small before scaling the API and integrating it with the whole application )
so when I tried to make the request using AJAX:
const storedProduct = localStorage.getItem("product-id");
const products = JSON.parse(storedProduct);
(function products_to_backend() {
let xhr = new XMLHttpRequest();
xhr.open("POST", "localhost:9000/frontEndProductsHandler.php",true);
xhr.setRequestHeader("Content-type" , "application/json");
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.addEventListener("load",function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(`server status : 200 OK : ${xhr.responseText}`);
}else if(xhr.status === 404){
console.log("NOT FOUND");
}
});
xhr.addEventListener("error", function(){
console.log(`request faild : ${xhr.statusText}`);
});
console.log(typeof(JSON.parse(storedProduct)))
xhr.send(JSON.parse(storedProduct));
})();
the PHP script :
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_CONTENT_TYPE']) && $_SERVER['HTTP_CONTENT_TYPE'] === "application/json"){
$requestBody = file_get_contents("php://input");
$data = json_decode($requestBody);
if($data){
http_response_code(201);
echo json_encode($data);
}else{
http_response_code(400);
}
}else{
http_response_code(404);
die();
};
Thanks in advance, and I hope that I described the issue well.
So the first problem was that i forgot about HTTP protocol in the end point , thanks to Markus Zeller to notice it.
And the second this was that i'm actually encoding the data into json even tho its already a json.
So that the new version of the script :
js :
(function products_to_backend() {
let xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:9000/controller/handlers/frontEndProductsHandler.php",true);
xhr.setRequestHeader("Content-type" , "application/json");
xhr.addEventListener("load",function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(`server status : 200 OK : ${xhr.responseText}`);
}else if(xhr.status === 404){
console.log("NOT FOUND");
}
});
xhr.addEventListener("error", function(){
console.log(`request faild : ${xhr.statusText}`);
});
xhr.send(JSON.stringify(storedProduct));
})();
php :
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_CONTENT_TYPE']) && $_SERVER['HTTP_CONTENT_TYPE'] === "application/json"){
$requestBody = file_get_contents("php://input");
$data = $requestBody;
if($data){
http_response_code(200);
echo json_decode($data);
}else{
http_response_code(400);
}
}else{
http_response_code(404);
die();
};
Related
I have attached the two files, I am trying to verify recaptcha from server side and trying to pass grecaptcha.repsonse() to php using XMLHttpRequest but it sends blank data using POST.I am able to get the solution for the same.
Following code has the XMLHttpRequest
<script type="text/javascript">
function sendAjaxRequest() {
if (grecaptcha === undefined) {
alert('Recaptcha not defined');
return;
}
var response = grecaptcha.getResponse();
if (!response) {
alert('Coud not get recaptcha response');
return;
}
var http = new XMLHttpRequest();
var url = 'validate-recaptcha.php';
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
temp = JSON.stringify(response);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.open('POST', url, true);
http.send(response);
}
</script>
Following is the php code:
<?php
if (empty($_POST['response'])) {
exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(array (
'response' => $response,
'secret' => 'mysecretkey',
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$opts = array('http' => array (
'method' => 'POST',
'header' => 'application/x-www-form-urlencoded',
'content' => $post
)
);
$context = stream_context_create($opts);
$serverResponse =
#file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if (!$serverResponse) {
exit('Failed to validate Recaptcha');
}
$result = json_decode($serverResponse);
if (!$result -> success) {
exit('Invalid Recaptcha');
}
exit('Recaptcha Validated');
?>
I am creating a login form and I need to redirect the user to his/her profile page! I am using AJAX Requests so header redirect is not working at all. It just stays on the homepage. So how can I redirect the user to another page in pure javascript PHP ajax call? Please give the answer in pure javascript. I don't like to use jQuery at all!
Javascript:
function ajaxCall(){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
document.getElementById('error').innerHTML = this.responseText;
}
};
var parameters = 'email='+document.getElementById('email')+'&password='+document.getElementById('password');
xhttp.open('POST', 'login.php', true);
xhttp.setRequestHeader('Content-type', 'application/x-www/form/urlencoded');
xhttp.send(parameters);
}
Login.php(PHP)
<?php
if(isset($_POST['email']) && isset($_POST['password'])){
$ema = $_POST['email'];
$pass = $_POST['password'];
if(!empty($ema) && !empty($pass)){
if($ema === 'Bill' && $pass === 'Cool'){
header('Location: https://www.google.com');
}
}
}
Make an ajax call.
<?php
header('Content-Type: application/json');
echo json_encode(['location'=>'/user/profile/']);
exit;
?>
The ajax response will return something like
{'location':'/user/profile/'}
In your ajax success javascript function
xhr.onreadystatechange = function () {
if (xhr.status >= 200 && xhr.status <= 299)
{
var response = JSON.parse(xhr.responseText);
if(response.location){
window.location.href = response.location;
}
}
}
I landed here looking for an Ajax solution, nevertheless MontrealDevOne's answer provided useful. If anyone else is curious about the ajax method too, here you go:
$('body').on('submit', '#form_register', function (e) {
var form = $(this);
$.ajax({
type: 'POST',
url: 'form_submissions.php',
data: form.serialize() + "&submit",
dataType:"json",
success: function (data) {
if(data.location){
window.location.href = data.location;
}
},
error: function(data) {
alert("Error!");
}
});
e.preventDefault();
});
Just my 2 cents, hope it helps :)
try this bill if its works.
window.location.replace("http://www.google.com");
I don't have much experience with PHP, but what I'm trying to do is to write content to a file. For some reason the content is written to the file, but still returns 'failed to write to file!' with the 400 status code. But the contents are successfully written to the file. How?
php code (update.php):
<?php
//get root and page of request
$content_root = $_SERVER['DOCUMENT_ROOT'] . '/Animagie/content';
$page = $_POST['page'];
//open the correct contentfile
$content_file = fopen($content_root . '/' . $page, 'w');
if (isset($_POST[$page . '-content'])) {
if (fwrite($content_file, $_POST[$page . '-content']) === FALSE ) {
echo 'failed to write to file!';
fclose($content_file);
http_response_code(400);
} else {
fclose($content_file);
http_response_code(200);
}
} else {
echo 'something went wrong!';
fclose($content_file);
http_response_code(400);
}
?>
I call update.php with following code:
editor.addEventListener('saved', function(e) {
var name, payload, regions, xhr;
//check if something changed
regions = e.detail().regions;
if (Object.keys(regions).length === 0) {
return;
}
//set editor busy while saving
this.busy(true);
// Collect the contents of each region into a FormData instance
payload = new FormData();
payload.append('page', getCurrentPage());
for (name in regions) {
if (regions.hasOwnProperty(name)) {
payload.append(name, regions[name]);
}
}
// Send the updated content to the server to be saved
function onStateChange(e) {
//check if request is finished
if (e.target.readyState === 4) {
editor.busy(false);
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
}
}
xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '../api/update.php');
xhr.send(payload);
});
As you probably can tell it's quiet important to get the correct statuscode since I check for it and return if it's succesfull or not to the user. Anyone able to help me?
Thanks in advance!
Apperently the problem lays in the javascript check:
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
should be
if (e.target.status == 200) {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
Also after I switched the if-statement (like told by #Jon Stirling), postman wasn't refreshed yet. So it was partially a wrong if-statement on the server side & wrong if-statement on the client side.
I writing a registration/login form, I am sending user info via POST to a PHP that is looking in a DB. I would like that the PHP returns an ok or wrong value to the js and I don't now how to do it.
Here my js:
ui.onClick_regsubmit=function()
{
var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var affiliation=document.getElementById('affiliation').value;
var data = new FormData();
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
data.append("fname",fname);
data.append("lname",lname);
data.append("password",password);
data.append("mail",mail);
data.append("affiliation",affiliation);
xhr.open( 'post', 'PHP/registration.php', false );
xhr.send(data);
window.alert(affiliation);
}
And the php:
<?php
mysql_connect('localhost','root','') or die('Cannot connect mysql server');
mysql_select_db('ChemAlive_login') or die('cannot connect database');
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$password=$_POST['password'];
$mail=$_POST['mail'];
$affiliation=$_POST['affiliation'];
$q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
$n=mysql_fetch_row($q);
if($n>0)
{
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password) echo "ok";
else echo "wrong";
}
else
{ $insert=mysql_query("insert into login values('".$fname."','".$lname."','".$mail."','".$password."','".$affiliation."')") or die(mysql_error());}
?>
I would like to return to js this ok or wrong value. How to do it?
xhr.onload=function()
{
if (xhr.status==200)
{
alert(xhr.response);
}else
{
alert("unknown server error");
}
}
it will be better if the server sends a response code, and javascript will transfer this code to the text. For example:
onload=function()
{
switch(xhr.response)
{
case "0":{alert("unknown error")};break;
case "1":{alert("email is already used")};break;
...
}
}
I think thought it is clear
I do not have the rep to comment or I'd ask for details, but if you can consider using ajax, it could look something like this:
php:
$doit = //your query;
if($doit){
$youdid = 'ok';
}
else{
exit('1');
}
js:
$(document).ready(function () {
var foo = $("#formfield")val();
$.ajax({
"foo":foo;
type: 'POST',
url: 'some.php',
success: function(responseText) {
if(responseText == "1") {
alert("Leave instantly");
};
}
else {
alert("One of us");
}
If you want to return either ok or wrong to the JavaScript to handle you could do something like this in your registration.php page:
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password){
header('Content-Type: application/json');
echo json_encode(array('password' => 'ok'));
}else{
header('Content-Type: application/json');
echo json_encode(array('password' => 'wrong'));
}
I have not fully testing this, but the idea is to set the header to return json and then send it a JSON string.
Does that make sense?
Like I said in my comment below I have only used jQuery for AJAX. But here is a little something of what I know about XMLHttpRequest and my undertsanding of how you would test what you get back.
You can set up a listener for when you get a response back onreadystatechange and then put the response in a variable var pass = xhr.response and then just output the text to an alert box like alert(pass.password).
if (xhr.onreadystatechange === 4 && xhr.status === 200){
var pass = xhr.response;
//should output either ok or wrong
alert(pass.password);
}
Read more about XMLHttpRequest here
Let me know if that works.
Here is my javascript:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
hanapin.send(reqdata);
hanapin.onreadystatechange = function() {
if (hanapin.readyState == 4 && hanapin.Status == 200) {
document.getElementById('province').innerHTML=hanapin.ResponseText
}
}
window.alert(targeturl);
window.alert(reqdata);
}
I know the function is receiving the data because I used the alert.
but on php:
<?php
$findwat = $_POST['condo'];
echo $findwat;
?>
even when I open the php file using a separate link it won't echo the variable
An example using jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
$.post("testajax.php", {condo:proptype}, function(data){
// data is the result received from php
alert(data);
});
}
A mandatory header field for http post request is Content-length. change your code to:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hanapin.setRequestHeader("Content-length", reqdata.length);
hanapin.setRequestHeader("Connection", "close");
hanapin.send(reqdata);
hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} }
window.alert(targeturl);
window.alert(reqdata);
}
also a better solution is to use jquery to handle ajax