How can I read fetch() form data in php? - php

I have this code which works for me but when I try to actually use the form data in PHP I cant get it working. I've tried a number of snippets from stack overflow and the web but nothing seems to work. I did a reduced test case and discovered that I wasn't able to use var_dump($_POST) because I must have some misunderstanding of how fetch works because when I replace the php file with nothing but var_dump($_POST) or even echo("test") I'm not seeing anything.
Can anyone help me get at the data sent to the php file?
checkout.html ( this works fine )
<!DOCTYPE html>
<html>
<head>
<title>Buy cool new product</title>
<link rel="stylesheet" href="style.css">
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<section>
<form id = "myForm">
<input type="text" name="">
<input type="submit" name="">
</form>
</section>
</body>
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe("pk_9999999999999999999");
const myForm = document.getElementById('myForm');
myForm.addEventListener("submit", function (e) {
e.preventDefault();
const formData = new FormData(this);
fetch("/create-checkout-session-dump.php", {
method: "POST",
body: formData
})
.then(function (response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
});
</script>
</html>
creatch-checkout-session-dump.php ( this is just in place of the regular file as a reduced test case - the original file works for what i want it for but i need to be able to see the form contents here somehow but as it is I cant even get it so print "hello world")
<?php
echo('test');

I'm going to answer you again here.
In your PHP file you should ideally use the $_POST super global.
<?php
$data = $_POST['test'];
?>
This 'test' key tag is directly related to whatever you named your input/value in the form. Try this:
<input type="text" name="test" />
<script>
fetch("/create-checkout-session-dump.php",{
type: "POST",
body: formData
})
.then( response => response.ok ? response.json() : "ERROR LOADING" )
.then( data => console.log(data) )
.catch( err => console.error(err) );
</script>

Related

Trying to call a PHP script in separate JS file, how do i display the output onto my HTML page

First time trying this can anyone help me, i get an output on the console but have no idea how to display it in a tag. This is the problem for both the sections of my code. Any help would be appreciated.
const URL_GETOFFERS = 'getOffers.php';
const URL_GETOFFERS_XML = 'getOffers.php?useXML';
fetch(URL_GETOFFERS)
.then(
function (response) {
return response.text();
})
.then(
function (data) {
console.log(data);
document.getElementById("getHTMLOffer").innerHTML = "<p>" + this.responseText + "</p>";
})
.catch(
function (err) {
console.log("Something went wrong!", err);
});
fetch(URL_GETOFFERS_XML)
.then(
function (response) {
return response.text();
})
.then(
function (data) {
console.log(data);
parser = new DOMParser();
xmlDoc = parser.parseFromString(data,"text/xml");
xmlDoc.getElementsById("getXMLOffer").innerHTML = this.responseText;
})
.catch(
function (err) {
console.log("Something went wrong!", err);
});
});
If you want to put some content inside HTML elements you have to:
create the desired HTML elements
<div id="getHTMLOffer">initial content</div>
<div id="getXMLOffer">initial content</div>
get the elements in Javascript, after DOM has loaded
change the contents of the elements
// the contents of this function is executed after the HTML structure (DOM) is loaded
// aka `on ready`
(function() {
document.getElementById("getHTMLOffer").innerHTML = "new content here";
document.getElementById("getXMLOffer").innerHTML = "new content here";
})();
Know that there are multiple ways to accomplish this. Above is shown just one of those ways.
Also be aware the function getElementById gets only one element. In your code there is a typo getElementsById (extra s character).
A rudimentary example that sends a basic GET request with a querystring to the same page, processes th servers response and displays on the page
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['task'] ) ){
ob_clean();
echo 'Some text as respons to the FETCH request task = "'.$_GET['task'].'"';
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>FETCH</title>
</head>
<body>
<aside id='getHTMLOffer'></aside>
<script>
fetch( '?task=fetch&source=text' )
.then( r=>{ return r.text() } )
.then( data=>{
document.getElementById('getHTMLOffer').innerHTML=data
})
.catch(err=>{ alert( err ) } )
</script>
</body>
</html>

Can't get this AJAX call working in PhoneGap

Using PhoneGap, I'm trying to build a basic android app that makes an AJAX call to a PHP API and return some JSON data. The code, in its entirety works on the desktop, but it doesn't seem to work for my Android when I make a build. When I build the app, install it on my device, and load it up, I get blank screen.
Here's the client that I wrote... Is there anything wrong with this code?
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.css" />
</head>
<body>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// Now safe to use the PhoneGap API
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.ajax({
url: 'http://api.example.com/test.php',
dataType: 'json',
timeout: 5000,
success: function(data, status) {
//data loaded
$('#results').append(data[0].about);
},
error: function() {
//error loading data
$('#results').append('No data received.');
}
});
$(document).ajaxError(function(event, request, settings) {
$("#msg").append("<li>Error requesting page " + settings.url + "</li>");
});
$(document).ajaxComplete(function(event, request, settings) {
$("#msg").append("<li>Request Complete.</li>");
});
}
</script>
<p id="results"></p>
<p id="msg"></p>
</body>
</html>
I also set the access origins in the config.xml to:
<access origin="http://example.com" subdomains="true" />
<access origin="*"/>
It seems that the AJAX code (and the global AJAX event handlers) is not getting called.
Be sure to have cordova.js included in the right location and available (e.g. by alert(<some cordova property>);). Then try if the onDeviceReady is called at all:
document.addEventListener("deviceready", function(){
alert("deviceready");
},false);

Passing results from PHP class to AJAX and back to the calling script

I have a class which returns a set of data from the database. The class is called by ajax and the results need to be returned back to the index.php so that I can format and display the results in a table format.
Problem: I'm unable to return the results throug ajax and back to a php variable.
Any help you can provide would be greatly appreciated.
<php
class Questions
{ public function displayQuestions()
{
return $this->questionArray;
} // contains set of data from db
}
?>
Return the dataset from the class and pass it to the $var so that I can format the data for display
index.php:
<html>
<body>
<div id="questiondev" ><?php $var[] = returned by ajax ?> </div>
<div id="questionButton">
<form method="POST" name="form_questions" action="">
<TEXTAREA NAME="saveqa" id="saveqa"></TEXTAREA>
<BUTTON class="btn_save" id ="btn_save" NAME="btn_save">Ask</BUTTON>
</form>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$('#btn_save').on('click', function() {
$.ajax({
type: "POST",
cache: false,
url: "testData.php",
dataType: "json",
success:function(info){
$('#questiondev').html(info[0]);
console.log(" reponse :"+ info);
}
});
});
$('#btn_save').trigger("click");
});
</script>
</body>
</html>
add
data:$("form").serialize(), U need to serialize the form
<div id="questionButton">
<form method="POST" name="form_questions" action="">
<TEXTAREA NAME="saveqa" id="saveqa"></TEXTAREA>
<BUTTON class="btn_save" id ="btn_save" NAME="btn_save">Ask</BUTTON>
</form>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$('#btn_save').on('click', function() {
$.ajax({
type: "POST",
cache: false,
url: "testData.php",
data:$("form").serialize(),
dataType: "json",
success:function(info){
$('#questiondev').html(info[0]);
console.log(" reponse :"+ info);
}
});
});
$('#btn_save').trigger("click");
});
</script>
</body>
</html>
It doesn't look like you're echoing your results in json format. It appears that if your query is successful, $questionArray gets set, but is not echoed. Plus you can't just echo $questionArray - it must be output in json format for the Ajax code to accept it.
Try this - after $questionArray is set:
$encodedJSON = json_encode($questionArray);
echo $encodedJSON;
you can't insert result of AJAX request into PHP variable like this. When you run php page web server willl render it, and then javascript is run by browser, which means, that you can't edit PHP variables from javascript, because PHP runs on server and JS runs on client.
Why do you want to do this? Maybe it is flaw in app design, give more information and maybe we can help you more so you won't need to do this. If you want to format data, then format them before you send them back to AJAX :)

Backbone.js: Save Method Always Return Error Callback

I know people probably will get real confused why I am not using rails but I feel better using php thus I've picked it. I'm basically trying to create a really simplebackbone.js. I've predefined the urlRoot and url functions. I've coded php to just simply return me a message (using echo).
But no matter what I do, whenever I try receive the response it always falls to the error callback. I do get the responseText in response, however I still cannot understand why the error callback is triggered. Here is my full html and back-end php code. Why is it always going to the error callback? I would also like to state I receive header HTTP/1.1 200 OK
HTML (also with Backbone.js inside);
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
</head>
<body>
<div id='place'>
<input id='clicker' type='button' value='Click Me'/>
</div>
<script type='text/javascript'>
(function($){
Backbone.emulateHTTP=true;
Backbone.emulateJSON=true;
var URL=Backbone.Model.extend({
initialize:function(){
console.log("URL object has been created");
},
defaults:{
url:'not actually defined'
},
urlRoot:'/StupidExample/server.php',
url:function(){
var base=this.urlRoot || (this.collection && this.collection.url) || "/";
if(this.isNew()) return base;
return base+"?id="+encodeURIComponent(this.id);
}
});
var URLView=Backbone.View.extend({
initialize:function(){
console.log('URL View has been created');
},
el:('#place'),
events:{
"click #clicker":"alerter"
},
alerter:function(){
console.log("I've been clicked");
var obj=new URL();
obj.save(obj.toJSON,{
success:function(){
console.log("Success")
},
error:function(model,response,xhr){
console.log(model);
console.log(response);
console.log(xhr);
console.log("Error");
}
});
}
});
var urlView=new URLView();
})(jQuery);
</script>
</body>
</html>
PHP;
<?php
echo "I've received something";
?>
You must return a valid JSON object with your HTTP 200 response. Backbone throws an error on your echo return value because it tries to parse the response as JSON, which fails.
As Derick said you need to return JSON, which you can do by changing your php file to:
<?php print json_encode(array( 'response' => 'success' ));
But you will also need to not use absolute paths as your URL because AJAX is not allowed across domains so it's required to be relative.

jquery ajax request firebug error

I am using php/ajax to submit a form without page refresh. Here are my files-
coupon.js
jQuery(document).ready(function(){
jQuery(".appnitro").submit( function(e) {
$.ajax({
url : "http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php",
type : "post",
dataType: "json",
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false or
e.preventDefault();
});
});
sms.php
<?php
//process form
$res = "Message successfully delivered";
$arr = array( 'mess' => $res );
echo json_encode( $arr );//end sms processing
unset ($_POST);
?>
and here is code for my html page -
<form id="smsform" class="appnitro" action="http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php" method="post">
...
</form>
<div id="mess" style="background:green;"></div>
Now when i click on submit button nothing happens and firebug shows following under console panel -
POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
404 Not Found 1.29s `jquery.min.js (line 130)`
Response
Firebug needs to POST to the server to get this information for url:
http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
This second POST can interfere with some sites. If you want to send the POST again, open a new tab in Firefox, use URL 'about:config', set boolean value 'extensions.firebug.allowDoublePost' to true
This value is reset every time you restart Firefox This problem will disappear when https://bugzilla.mozilla.org/show_bug.cgi?id=430155 is shipped
When i set 'extensions.firebug.allowDoublePost' to true then following results show up -
POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
404 Not Found 1.29s `jquery.min.js (line 130)`
Response -
{"mess":"Message successfully delivered"}
CaN anyone help me in fixing this firebug error of 404 not found. And why is it showing jquery.min.js (line 130) along side?
P.S -do not worry about http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street this is my base url
You may want to try putting the e.preventDefault() statement before the $.ajax call.
EDIT:
My x.html, corresponds to your HTML page
<!DOCTYPE html>
<html>
<head>
<title>x</title>
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript" src="/so/x.js"></script>
</head>
<body>
<form id="smsform" class="appnitro" action="/so/x.php">
<input type="text" name="zz">
<input type="submit">
</form>
<div id="mess" style="background:green;"></div>
</body>
</html>
My x.js, corresponds to your coupon.js
jQuery(document).ready(function(){
jQuery(".appnitro").submit( function(e) {
e.preventDefault();
$.ajax({
url : "/so/x.php",
type : "post",
dataType: "json",
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false or
//e.preventDefault();
});
});
My x.php, corresponds to your sms.php
<?php
$res = "Message successfully delivered.";
$arr = array('mess'=>$res);
echo json_encode($arr);
unset($_POST);
?>
This actually works in my environment, although I do not have the rest of the HTML markup or the additional PHP form processing code. The "Message successfully delivered." shows up in green directly below the input field.
When inside the Ajax call this refers to the Ajax object you need to do this
var __this = this;
Before going into the Ajax call, then it would be
data : __this.serialize()
Or look up the use of context within an Ajax call in Google. Or serialise your data into a variable before going into the Ajax call.

Categories