How to console the PHP echo in my javascript? - php

I can not get the PHP echo in my Ajax.
This is my test01.html code:
In my HTML code, I quote the jQuery, and I bind the event in my "sub01" button, I use Ajax provide the POST request:
$(".sub01").bind("click", function() {
$.ajax({
type: "POST",
url: "cms/test01.php?action=test01",
dataType: "json",
data: {
"var_01": "var_01_value",
"var_02": "var_02_value",
},
success: function(response) {
console.log(response) // there I want to console the response from PHP.
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<form>
<input type="text" value="var_01">
<input type="text" value="var_02">
<input id="sub01" type="submit" value="click me!">
</form>
</div>
And this is my PHP test01.php code:
in my PHP code I want to echo the $_POST, then I want the AJAX code get the response.
<?php
echo $_POST;
I want the code
success: function(response) {
console.log(response) // there I want to console the response from PHP.
}
shows the PHP echo, but there console nothing.

Problem 1
You never call your JS function
$(".sub01").bind
You are binding to the click event of elements with the class sub01.
<input id="sub01" type="submit" value="click me!">
Your button doesn't have that class!
Aside: bind is deprecated in favour of on.
$("#sub01).on("click" ....
Problem 2
You aren't letting the JS run
Since you are (trying) to run the JS when a submit button is clicked, the form is submitting.
The browser is leaving the page before the Ajax response comes back and triggers the success function.
You need to prevent the default behavior of the submit button.
$("#sub01").on("click", function (event) {
event.preventDefault();
// etc
});
Problem 3
You aren't parsing the response correctly
You said dataType: "json", which means "Tell the server I only Accept JSON and ignore the Content-Type and parse the response as JSON regardless".
Since the server is not responding with JSON, the attempt to parse the response fails and it errors.
Option 1
Remove dataType: "json".
This will process the response as invalid HTML (because PHP sends Content-Type: text/html by default).
Then you will echo the response (which is Array … probably not the response you want PHP to send though).
Option 2
Change the PHP so it responds with JSON
<?php
header("Content-Type: application/json");
echo json_encode($_POST, JSON_PRETTY_PRINT);

You need to output a json.
header('Content-Type: application/json');
echo json_encode($_POST);

Related

How do you save a file to a directory given by an input type="text" with php?

I have a html page with jQuery and I used ajax to send data to the a php file to save the data.
I have seen other questions like this but none of them seemed to match my purpose.
The data is an iframe's srcdoc.
My html looks like this:
<iframe srcdoc="<h1>hello</h1>" id="iframe"></iframe>
<br />
<input type="text" placeholder="Filename to save as..." id="fn">
<input type="button" value="Save" onclick="saveDoc(document.querySelector('#fn').value)">
My jQuery and JS looks like this:
function saveDoc(e) {
let iframe = document.querySelector("#iframe");
let data = {"srcdoc": iframe.srcdoc, "lnk": e};
$.ajax({
type: "POST",
url: "saver.php",
dataType : "text",
contentType: "application/json",
data: data,
cache: false,
timeout: 3000,
success: function (data) {
alert("SUCCESS");
console.log(data);
},
error: function (e) {
alert(e);
}
});
}
And my php code looks like this:
<!doctype html>
<html>
<body>
<?php
if (isset($_POST["lnk"]) && isset($_POST["srcdoc"])) {
$myfile = fopen($_POST["link"], "w");
fwrite($myfile, $_POST["srcdoc"]);
fclose($myfile);
echo $_POST["lnk"];
echo "\n <br/>";
echo $_POST["srcdoc"];
} else {
echo "Error";
}
?>
</body>
</html>
When I run it, I get an alert message saying "SUCCESS". And the console.log gives me:
<!doctype html>
<html>
<body>
Error</body>
</html>
What is happening here, and what am I doing wrong?
contentType: "application/json"
You are explicitly sending this to the server as JSON - so you can not access it via $_POST. (PHP only populates $_POST for Content-Types application/x-www-form-urlencoded or multipart/form-data.)
Either remove contentType, so that it can fall back to the normal way of sending form data, or go read up on how to actually read POSTed JSON data in PHP. (That would involve reading the data from php://input first, see Receive JSON POST with PHP)

PHP capture data and join together

Okay so I need to parse two parts. Here is the code im trying to parse.
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
I would like it to parse and output like this once done.
10528935=12-1-D33D19A3F048E845A9AA885220729B98
Here is the site I'm trying to do this for
https://www.payqwiq.com/login?uid=582063bd-1973-42e4-8235-b28f5addf8bf
All I need is that data to be parsed and joined like above so I can continue with my program :)
Would appreciate some help if possible :)
I'm completely new in PHP.
Php is a back-end language. Since you are attempting to get data stored in a document object on the front-end, you should use a front-end language to parse the document object, then send the data to a php handler to do what you want with it on the back-end.
Using jQuery you can achieve the desired output with one line of code, then build an ajax call to send the output data to the desired php handler.
// when document is loaded
$(document).ready(function() {
// get data from document object to send to php handler
var combinedData = $('input').attr('name') + '=' + $('input').val();
// execute ajax method to send data to php handler
sendData(combinedData);
});
function sendData(data) {
// ajax method to send data to php handler
$.ajax({
url: 'pageToSendTo.php',
type: 'POST',
data: {
"data": JSON.stringify(data)
},
dataType: 'JSON',
success: function(data) {
console.log(data);
},
error: function(xhr) {
console.log('error: ' + xhr.responseText);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
<!-- this is the "pageToSendTo.php" php handler. -->
<?php
if ($_POST['data']) {
//echo 'received data!';
$data = json_decode($_POST['data']);
// do stuff with data
print_r(json_encode($data));
}
?>

jsonp, jQuery & PHP to make cross-domain ajax call

http://serverA.com/list.php:
html:
<form id="myform">
<input id="inputfield" name="view">
</form>
js:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: inputdata,
dataType: 'jsonp'
});
});
http://serverB.com/detail.php
php:
<?php
$view = $_GET['callback'].'('.json_encode(name) .')';
?>
html:
<h4><?php echo $view; ?></h4>
what the code does is:
from serverA, assign a value "ocean-view" to an input field, submit this form to serverB, and display this value in a h4 tag.
I couldn't quite figure out how to write the server-side code to output the value, even though I have found the following posts.
this and this.
Any kind of help is appreciated.
UPDATE:
I used YQL to help to see the jsonp callback response, here is the json structure:
callback({
"query": {
"count": 1,
"created": "2013-07-29T13:01:12Z",
"lang": "en-US",
"results": {
"h3": {
"class": "mytitle",
"content": "Example"
}
}
}
});
Actually You are very close to success... just read these points.
Whenever you are making an ajax request the browser sends a hit on ajax URL with respected parameters and details. On respected URL PHP code executes. It can return data in some format. It can not return data in directly PHP variable.
Formats are:
text/html
json
xml
......
Mainly for cross domain requests we use JSONP.
And it means PHP script will return data in JSON.
So you will just echo your json_encode in directly script. That will be the response of your ajax request.
Now when you have got the data in ajax function, then jQuery uses success: function(response){ } where you response will come.
So variable response will contain JSON.
You can access JSON and put data in any tag by using jQuery selector.
$().html(response.);
These thing can be analyzed in any browser in debug console. That what is requested and what is returned.
even you can use Firebug in Mozilla to inspect ajax request.
So you will do three changes.
In Ajax function write a success function:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: "inputdata="+inputdata,
dataType: 'jsonp',
success:function(response){
// response will be json type so access it
// print ur json in html tag like resposne is {"data":23}
$(<jquery selector>).html(reponse.data);
}
});
});
<?php
// echo this
$inputdata = $_GET['inputdata'];
// perform you logic ,
// make an array to encode it in json
echo $_GET['callback'].'('.json_encode($responseArr) .')';
?>
and remove PHP code from h4 tag.

JQuery .load() or .ajax() or .post() for form data to php function

Trying to implement AJAX using one of JQuery’s functions. I’ve been trying .load(), .ajax() or .post() in various ways, by using some of the examples on Stack Overflow without success.
I have a form, which queries the oracle DB, and returns another form and a results table. I have it working in the traditional way with separate PHP files (reload an entire new page). Now I want to just load the content without the page refresh.
Start Form PHP (checkin_start.php): Enter a barcode and submit…
<div class="content" id="bodyContent">
<form id="usualValidate" class="mainForm" method="post" action="">
<label>Barcode:<span>*</span></label>
<input type="text" class="required" name="startBarcode" id="startBarcode"/>
<input type="submit" value="submit" class="blueBtn" id="startBtn" />
</form>
</div>
Process PHP (checkin_process.php): a new form and the query results from the php function are loaded into id="bodyContent"…
<form id="checkinProcess" class="mainForm" method="post" action="">
<label>Barcode:<span>*</span></label>
<input type="text" class="required" name="processBarocdes" id="processBarcodes"/>
<input type="submit" value="submit" class="blueBtn" id="submitBtn" />
</form>
<!-- Shipment List Table -->
<?php
// Accept a parameter from #usualValidate form and run query.
$barcode = $_POST['startbarcode'];
search_shipped_barcode($barcode);
?>
Functions PHP (functions.php): returns results table…
<?php
function search_shipped_barcode($barcode){
<--! DB connection & query -->
echo "<table>";
<--! echo table results -->
echo "</table>";
}
?>
I think I probably have the same problem no matter which one I choose, so here's my .post() attempt. I don't quite understand how to pass the form data to my php function and return the data back...
$(document).ready(function() {
$("#usualValidate").submit(function(sevt) {
sevt.preventDefault();
var startBC = $("#startBarcode").val();
$.post("checkin_process.php",
{"startBarcode" : "startBC"},
function(data) {$("#bodyContent").html(data)},
"html");
});
});
Thanks for any insight....
When you use $.post, the values should not be quoted unless they are literals.
Try this:
$(document).ready(function() {
$("#usualValidate").submit(function(sevt) {
sevt.preventDefault();
var startBC = $("#startBarcode").val();
$.post("checkin_process.php",
{startBarcode : startBC},
function(data) {
$("#bodyContent").html(data);
// log the returned data to console for debug
console.log(data);
});
});
});
In your javascript file you can use the post method or you can use ajax like in the example below to send your data:
$.ajax({
type : 'post',
url : 'currentphpfile.php',
//Here is where the data is put
data : {
"ajax" : "1",
"otherData" : "abc"
},
success : function(data, textStatus, jqXHR) {
//Do something with the data here like insert it into the document
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//Do something to fix the error
},
dataType : 'text' //Or automatically parse a json response with 'json'
});
For this to work, you would need something in your php file that could handle the request like this:
if (!empty($_POST['ajax']) && $_POST['ajax']==1){
//Do stuff with the other post data
//Here's how to return the data to your script:
//If you chose a text response above:
echo $importantData;
exit;
//If you chose json
echo json_encode(array("title" => $title, "text" => $text /*, etc... */));
}
I haven't tested this code for bugs, but you probably get the idea.

Jquery Ajax no response

When I try to get the response from a php file using Jquery ajax, I just get (an empty string) (Accdg. to Firebug console using console.log(data))
Here's the Html code:
<form action="test.php" method="POST" id="ajax">
<input type="text" name="field" />
<input type="submit" value="submit" name="submit" />
</form>
Here's the Jquery code:
$('#ajax').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
url: 'test.php',
cache: false,
success: function(data) {
alert(data);
}
});
return false;
});
And the PHP code:
if ($_POST['submit'] == "submit")
{
echo 'Got your request';
}
Just basic. What frustrates me is that it's straightforward, I've done some research and still it doesn't work. I also want it to be as simple as possible.
Please enlighten me.
Don't check to see if you're in a POST situation by checking for fieldnames. That's incorrect - you might change your client-side form names and forget to update the PHP check.
The 100% reliable method is to use:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Got your request";
}
However, since you just want to see if the server got pinged at all by your ajax call, why not do:
<?php
echo "Got your ", $_SERVER['REQUEST_METHOD'], " request";
Which'd just return Got your POST request or Got your GET request, etc...
As well, check your server log (or use HTTPFOX/Firebug Net tab, etc...) to see if that ajax request is actually going out and being received by the server.
The problem with the serialize() method is that it doesn't include the name of the button parameter which you use in your php script (submit=submit parameter). It doesn't do it because it doesn't know which button was clicked. This parameter is only included by the browser when you submit the form normally.
So one possibility is to manually attach this parameter as query string parameter:
url: 'test.php?submit=submit',
and in your PHP script:
if ($_GET['submit'] == "submit")
{
echo 'Got your request';
}

Categories