Wording might be a bit off. I'm trying to use the Battle.NET API to retrieve some information regarding characters. I have a 'server' field, and a 'char name' field.
I've reviewed a few of the similar questions, like this one, and maybe it's just my PHP new-ness but I'm getting confused on how to properly do it. I'm still not sure at all how to troubleshoot PHP errors.
What I did was design the HTML + PHP embedded into one 'php' file. It Worked. I then separated them into index.html + test.php it worked
The main issue with that was a few things - I wasn't rendering the response, I JUST had it 'echo' the response. Which appears to have been in JSON
{"lastModified":1477156067000,"name":"Thischaracter","realm":"Thisrealm","battlegroup":"Thisbattlegroup","class":1,"race":6,"gender":0,"level":110,"achievementPoints":20805,"thumbnail":"thrall/50/129432626-avatar.jpg","calcClass":"Z","faction":1,"totalHonorableKills":8657}
So the flow needs to be HTML Form - Submit -> AJAX -> PHP form (This is far as my "experience" goes, because I've never done anything with the response) -> MAYBE a getJSON from the PHP data? -> HTML output. I mention AJAX because I don't want the page to update. Just a 'div' or LI to be updated.
index.html -- I modified this form a bit before posting here to remove extra non-sense.
<form action="testingApiForBnet.php" method="post" id="myForm">
<p class="inp-wrap search-wrap">
<label for="search-field" class="search-label grid-25">Find</label>
<input type="search" name="search-term" id="charSearch" class="grid-75"/></p>
<p class="inp-wrap cat-wrap">
<label for="categories" class="grid-20">on</label>
<select name="search categories" id="servers" class="grid-80">
</select>
</p>
<submit name="SubmitButton">
</form>
testAPI.php
<?php
if(isset($_POST['SubmitButton']))
{
$charName = $_POST['charName'];
##$_POST['charName'];
$server = $_POST['servers'];
##$_POST['server'];
$bnetAPI = "https://us.api.battle.net/wow/character/";
$apiKey = "apiKeyWouldGoHere";
// Example https://us.api.battle.net/wow/character/$Server/$CharName?locale=en_US&apikey=$apiKey//
$request = $bnetAPI . urlencode($server) .'/'.$charName .'?locale=en_US&apikey=' . $apiKey ;
$response = file_get_contents($request);
$jsonobj = json_decode($response);
}
?>
The 'json_decode' and 'file_get_contents' I got from another thread, because I was getting non object responses. With those $jsonobj is putting out the object I linked above.
test.js
$(document).ready(function () {
$('#myForm').on('submit', function(e) {
e.preventDefault();
$.post('testAPI.php', $(this).serialize(), function (data) {
alert(data);
console.log(data)
return false;
})
});
});
Up until the "function (data)" this script is actually taken from another form I have that works successfully. Currently nothing is happening when I hit submit - No redirect, no response, no console.log - I feel like it's because I'm POSTing, and it needs to GET but then I'd still get 'something' from data?
Would appreciate any input. Also still unable to troubleshoot PHP, unless I run the PHP script directly. I feel this much just be functionality within the language.
Thanks!
UPDATE Placeholder.php
<?php
if (!empty($_POST)) {
$charName = $_POST['charName'];
##$_POST['charName'];
$server = $_POST['servers'];
##$_POST['server'];
$bnetAPI = "https://us.api.battle.net/wow/character/";
$apiKey = "key";
// Example https://us.api.battle.net/wow/character/Thrall/Teodoro?locale=en_US&apikey=$apiKey//
$request = $bnetAPI . $server .'/'.$charName .'?locale=en_US&apikey=' . $apiKey ;
$response = file_get_contents($request);
$jsonobj = json_decode($response);
header('Content-Type: application/json');
echo $response;
exit();
}
?>
UPDATE index.html (just JS portion)
$(document).ready(function () {
$('#myForm').submit(function (e) {
e.preventDefault();
$.post('test2.php', $(this).serialize(), function (data) {
console.log(typeof(data));
if (typeof data === 'string')
data = JSON.parse(data);
if (typeof data !== 'object') {
console.log("failed to parse data");
return;
}
data = JSON.parse(data);
console.log(data);
});
/*
*/
console.log('Data is not returning.');
return false;
});
});
Your jQuery code refers to a form with myForm ID, but you haven't assigned the ID to the form. So you should add the id attribute as follows
<form id="myForm">
Next, you have to fix the URL you post to. It should be testAPI.php, but not text.php:
$('#myForm').submit(function (e) {
e.preventDefault();
$.post('testAPI.php', function (data) {
// ...
});
})
Since you are binding the onsubmit, and handling the post request yourself, you probably don't need the action and method attributes in your form. Since the testAPI.php returns JSON content, you need to decode it in the request handler. Also, with the $.post() call you don't send any data to the server. It is just an empty POST request. You have to pass the serialized form as the second argument:
test.js
$('#myForm').submit(function (e) {
// note, `this` variable refers to the form node.
e.preventDefault();
$.post('testAPI.php', $(this).serialize(), function (data) {
if (typeof data === 'string')
data = JSON.parse(data);
console.log(data);
});
return false;
})
The code parses data, if it is a string. The jQuery handler may pass data as Object in case if the response returned Content-Type: application/json (in fact, is the right MIME type for JSON data). So you I'd recommend fixing the MIME type in testAPI.php, and, yes, you should print the response instead of decoding (unless you need to modify it):
header('Content-Type: application/json');
echo $response; // supposed to be a JSON string
exit();
If, however, you need a modified response, then decode it, modify, and encode, again:
header('Content-Type: application/json');
$response = json_decode($response, true);
$response['something'] = 'somevalue';
// unset($response['redundant_field']);
header('Content-Type: application/json');
echo json_encode($response); // supposed to be a JSON string
exit();
Example
test.php
<?php
if (!empty($_POST)) {
$search_term = $_POST['search-term'];
$category = $_POST['category'];
$fake_response = [
'term' => $search_term,
'cat' => $category,
'somethingelse' => date('r'),
];
header('Content-Type: application/json');
echo json_encode($fake_response);
exit();
}
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Test</title>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
<input type="search" name="search-term" id="charSearch"/>
<select name="category" id="servers">
<option value="optA" selected>optA<option>
<option value="optB">optB</option>
</select>
<input type="submit" name="SubmitButton"/>
</form>
<script>
$(document).ready(function () {
$('#myForm').submit(function (e) {
e.preventDefault();
$.post('test.php', $(this).serialize(), function (data) {
if (typeof data === 'string')
data = JSON.parse(data);
if (typeof data !== 'object') {
console.log("failed to parse data");
return;
}
console.log(data);
});
return false;
});
});
</script>
</body>
</html>
Sample output (in the browser's console)
Object { term: "rr", cat: "optA", somethingelse: "Sun, 23 Oct 2016 05:10:50 +0000" }
Related
I would like to build a newsletter subscription function to my website. and I want to get all the input save into a txt file in the host folder. However, I don't want to switch page after people submit it. Just show a popup message saying "Thank You for Subscribing" will be perfect. I know how to do it with PHP to show a message in a separate page, but not sure how to do it in a popup box. Here is my html and PHP code. Please help, thanks a lot.
<html>
<head>
<title></title>
</head>
<body>
<form>
<form action="myprocessingscript.php" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Text file</a>
</body>
PHP function is
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
Once you have included jQuery to your page, something like following should work:
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'field1' : $('input[name=field1]').val(),
'field2' : $('input[name=field2]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myprocessingscript.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// data is the output from your php, check it and display alert appropriately
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Take a look at source article
Ive been trying to connect my PHP file to my HTML file using Javascript/jQuery and json. When the user inputs a number into the input box in the form and submits it, the PHP file should multiply the number by two and send it back to the user.
However when I press the submit button it takes me to the php page instead of displaying the information (processed in the php file) in HTML.
This is my HTML form:
<div id="formdiv">
<form action="phpfile.php" method="get" name="form1" id="form1" class="js-php">
Mata in ett nummer: <input id="fill1" name="fill1" type="text" />
<input type="submit" id="submit1" name="submit1" value="submit">
</form>
This is my Javascript file
$(".js-php").submit(function(e){
var data = {
"fill1"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
$("#formdiv").append("Your input: "+data)
alert (data);
}
})
e.preventDefault();
});
PHP file:
$kvantitet = $_GET['fill1'];
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
echo json_encode($work) ."<br>";
echo json_encode($bork);
There are a few things you could do a bit differently here to make this work:
Currently, using both .serialize and $.param your data variable contains something like this:
someurl.php?fill1=1&0=f&1=i&2=l&3=l&4=1&5=%3D&6=1
If you use only .serialize you will get something easier to work with:
?fill1=5
On the PHP side, currently your code outputs something like this:
4<br>8
By adding your values to an array you can get a response back that you can work with:
$result = array();
$kvantitet = $_GET['fill1']; // Lets say this is 5
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
//add the values to the $result array
$result = array(
"work" => $work,
"bork" => $bork
);
echo json_encode($result);
Which will output:
{"work":4,"bork":8}
Back on the JS side you can then handle the data in your success callback:
$(".js-php").submit(function(e){
data = $(this).serialize();
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
// *data* is an object - {"work":4,"bork":8}
$("#formdiv").append("Your input: "+data)
console(data);
}
});
// Use return false to prevent default form submission
return false;
});
One way to access the properties in your object is by using dot notation:
data.work //Outputs 4
data.bork //Outputs 8
But here is a really great answer on processing / accessing objects and arrays using JavaScript.
Here is a Fiddle containing your (working) jQuery
You are expecting JSON Data but what you send back is not JSON
Try output the following in your PHP File:
$data['work'] = $work;
$data['bork'] = $bork;
echo json_encode( (object)$data );
Use console.log to inspect incoming data on the AJAX call then handle it according to how you want.
I think you need &
data = $(this).serialize()+'&'+$.param(data);
and as #leonardo_palma mentioned in comments maybe you need to use e.preventDefault(); in the beginning of submit function
and I prefer to use
$(document).on('submit','.js-php',function(){/*code here*/});
How do I validate my code in PHP without getting error messages defined in the ajax definition in main.js?
Note: Chrome console returning:
XMLHttpRequest cannot load file:///C:/Documents/Mini%20Revision%20Projects/Project%20Website%203/ajax.php. Received an invalid response. Origin 'null' is therefore not allowed access.
Below is my code:
main.html
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="C:\Documents\jQuery\jquery2.js"></script>
</head>
<body>
<ul id="info1">
<li>Put anything in the field below.</li>
</ul>
<form id="form1">
<input type="text" name="field1" id="field1">
<input type="submit" name="submit" id="submit" value="Submit Form">
</form>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
main.js
$(document).ready(function() {
$("#form1").submit(function( event ) {
event.preventDefault();
//alert("happy");
$.ajax({
type: 'POST',
url: 'ajax.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$("#info1").html(data.msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
});
});
ajax.php
<?php
class ajaxValidate {
function formValidate() {
//Put form elements into post variables (this is where you would sanitize your data)
$field1 = #$_POST['field1'];
//Establish values that will be returned via ajax
$return = array();
$return['msg'] = '';
$return['error'] = false;
//Begin form validation functionality
if (!isset($field1) || empty($field1)){
$return['error'] = true;
$return['msg'] .= '<li>Error: Field1 is empty.</li>';
}
//Begin form success functionality
if ($return['error'] === false){
$return['msg'] = '<li>Success Message</li>';
}
//Return json encoded results
return json_encode($return);
}
}
$ajaxValidate = new ajaxValidate;
echo $ajaxValidate->formValidate();
?>
First of all, verify if PHP is not returning a warning or critical error. Insert this code in top of your code. If PHP returns a hidden error, the success data value will be null.
ini_set("display_errors", "On");
error_reporting(E_ALL);
PHP Error reporting manual
PHP run-time display_error
I think that if you are returning a JSON array in php, you need to call an array.
$("#info1").html(data['msg']);
Try to return the post values to verify if $_POST is not empty:
return json_encode($_POST);
You don't need to define an empty array if you define directly a first row.
//$return = array();
$return['msg'] = '';
you need to have PHP server in order to PHP scripts to work. install something like XAMPP (windows) or MAMP (linux)
I have thoroughly researched this topic, but cannot seem to find an answer due to the fragmented nature of the discussions and the very different use cases everyone seems to have.
I am using JQuery mobile to send data to a PHP login/registration script via $.ajax() call. It appears that the data I am trying to send never makes it to the server to be evaluated, and I am at a loss as to why.
I am trying to send the data from this form:
<div data-role="content">
<form id="reg_form" data-ajax="false">
<div data-role="fieldcontain">
<label for="reg_email">Email:</label>
<input type="email" name="reg_email" id="reg_email" value="" />
<label for="reg_pass">Password:</label>
<input type="password" name="reg_pass" id="reg_pass" value="" />
<label for="reg_pass_conf">Password:</label>
<input type="password" name="reg_pass_conf" id="reg_pass_conf" value="" />
<h4 id="reg_notification"><?php echo 'Notifications will appear here...'; ?></h4>
<button data-theme="b" id="reg_submit" type="button">Register!</button>
</div>
</form>
</div>
Which is triggered by this javascript:
$(document).on('pageshow', '#reg_page', function() {
$("#reg_notification").text("page loaded");
$(document).on('click', '#reg_submit', function(){
$("#reg_notification").text("button clicked");
var formDataReg = $("#reg_form").serialize();
$.ajax({
type: "POST", // Method of sending data to server
url: "php_scripts/reg_handle.php", // php script being sent to
cache: false, // requested pages won't be cached by server
data: formDataReg, // data to be sent to server
dataType: "json", // data type to be received back from server
success: onRegSuccess, // function to call on success
error: onError // function to call on error
});
return false;
});
});
function onRegSuccess(data, status)
{
alert(data);
$("#reg_notification").text(data.email + ' ' + data.pass + ' ' + data.pass_conf);
}
Which is sent to this php script:
<?php
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
?>
However, as stated earlier, the if/else block detects that $_POST['formDataReg'] is not even set. When I try to use it to assign values to variables, it obviously has no data to assign and I get null values.
I used alert to verify that indeed formDataReg did hold the proper form values before being passed to the server in the ajax call. It somehow gets lost in the ajax call, or I am not accessing it correctly.
If someone can point me in the right direction, I would very much appreciate it.
By this:
var formDataReg = $("#reg_form").serialize();
You serialized your form into the form. Now in formDataReg has such contents:
reg_email=xxx#gmail.com®_pass=yyy®_pass_conf=yyy
You have to parse this query in your php file:
$email = $_POST['reg_email'];
$pass = $_POST['reg_pass'];
$pass_conf = $_POST['reg_pass_conf'];
But you tried to work with $_POST['formDataReg'] which wasn't sent. So it is wrong. Yes, you had variable formDataReg in your JS, but it means nothing. You had sent serialized string (query) with your ajax-request and have to handle it.
So this code:
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
wouldn't work because you hadn't sent formDataReg and there are no value with this key in $_POST array.
This:
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
should work properly.
Let me know is something is unclear.
How can I save the form data in a file or a local db (maybe using AJAX) which send the data via form action to an external db?
The source code for my form is here: http://jsbin.com/ojUjEKa/1/edit
What changes (if any) should I make to the code?
EDIT:
Right. So I'm able to store the data into localStorage using AJAX and want to send the data stored across to a file called backend.php. Here's my html file: http://jsbin.com/iSorEYu/1/edit
and here's my backend.php file: http://jsbin.com/OGIbEDuX/1/edit
The AJAX is working absolutely fine to store the fields in localStorage but things go wrong when it tries to send the data across to backend.php. I receive the following errors:
[24-Jan-2014 08:40:34 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:34 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
[24-Jan-2014 08:40:58 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:58 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
What's the issue here?
LocalStorage would be your best bet. I would suggest using storejs as their API is straight forward, easy to use, and x-browser.
You could then trigger the form values to be stored on the "blur" event of each field.
$('input').on('blur', function (e) {
var el = e.target;
store.set(el.attr('name'), el.val());
});
When you are ready to submit to the server, you could use something like the following:
$('#formID').on('submit', function (e) {
e.preventDefault();
$.post('/my/save/route', store.getAll(), function () { ... });
});
You of course could do all of this without storejs and use vanilla JS to interact with the native LocalStorage API.
PHP:
<h1>Below is the data retrieved from SERVER</h1>
<?php
date_default_timezone_set('America/Chicago'); // CDT
echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
$current_date = date('d/m/Y == H:i:s ');
print "<h2>Server Time : " . $current_date . "</h2>";
$dataObject = $_POST; //Fetching all posts
echo "<pre>"; //making the dump look nice in html.
var_dump($dataObject);
echo "</pre>";
//Writes it as json to the file, you can transform it any way you want
$json = json_encode($dataObject);
file_put_contents('your_data.txt', $json);
?>
JS:
<script type="text/javascript">
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input[type=text]").val("");
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: fields,
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
</script>