formating return json in html - javascript

I need help formatting json return in html from my jquery json result.
this my html code :
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "testerer"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "test.php",
data: data,
success: function(data) {
$(".the-return").html(data["json"]);
}
});
return false;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="test.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="testerer" value="" placeholder="Favorite restaurant" />
<input type="submit" name="submit" value="Submit form" />
</form>
<div class="the-return"></div>
and this my test.php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "testerer": testerer(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function udemy(){
$courseid = $_POST['testerer'];
$client_id = 'xxx';
$client_secret = 'xxxxx';
// set HTTP header
$headers = array(
"Authorization: Basic " . base64_encode($client_id . ":" . $client_secret),
"Content-Type: application/vnd.api+json"
);
$url = 'https://xxx/' . $courseid . '/';
// Open connection
$ch = curl_init();
// Set the url, number of GET vars, GET data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute request
$result = curl_exec($ch);
// Close connection
$data["json"] = json_encode($result);
echo json_encode($data, JSON_PRETTY_PRINT);
}
always got return like this :
"{\"_class\": \"course\", \"id\": 5816, \"title\": \"XXx xxx xxx\", \"url\": \"\/xxx-xxx\/\",
I need result readable.

It's not clear what your $data should contain, but it looks like the problem is that you're calling json_encode() twice on the same data:
$data["json"] = json_encode($result);
echo json_encode($data, JSON_PRETTY_PRINT);

Convert JSON data into string
JSON.stringify(data["json"])
add as below
$(".the-return").html(JSON.stringify(data["json"]));

Related

Allow form to send POST request but prevent page from reloading - Javascript

I am working on a signup form with an integrated v2 reCAPTCHA and I ran into the issue that when submitting the form which includes the reCAPTCHA, it is reloading the page. I have a php function to validate the reCAPTCHA:
if (isset($_POST['g-recaptcha-response'])) {
function CheckCaptcha($userResponse) {
$fields_string = '';
$fields = array(
'secret' =>'secret_key',
'response' => $userResponse
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}
$result = CheckCaptcha($_POST['g-recaptcha-response']);
if ($result['success']) {
echo 'Success!';
} else {
echo 'Error';
}
}
When the form submits it gives a POST variable g-recaptcha-response to the page it's on as there is no action attribute to the form
So, I need to get the POST request but I can't let the page reload because that would get rid of other data on the page.
I tried using event.preventDefault(); when the form is submitted, but that also prevented the form from submitting the POST variable.
I have no idea how I would get the POST variable through javascript because the reCAPTCHA is not actually an input.
But if there was a way to get the value of the reCAPTCHA through javascript, then I could use ajax to send the POST request to the function.
If you include the query strings in the script url:
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
then you can use grecaptcha.getResponse as it says in the google reCAPTCHA documentation:
https://developers.google.com/recaptcha/docs/display
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
<script type="text/javascript">
var verifyCallBack = function(response) {
alert(response);
};
var widgetId;
var onloadCallback = function() {
widgetId = grecaptcha.render('recaptcha', {
'sitekey' : 's',
'theme' : 'light'
});
}
</script>
<form>
<div id="recaptcha"></div>
<input type="submit" name="submit" value="submit">
</form>
$('form').submit(function(e) {
e.preventDefault();
var response = grecaptcha.getResponse(widgetId);
$.ajax({
url: 'validate_captcha.php',
type: 'POST',
data: {'g-recaptcha-response': response},
success: function(data) {
alert(data);
},
error: function(error) {
alert(error);
}
});
});
And then in validate_captcha.php:
<?php
if (isset($_POST['g-recaptcha-response'])) {
function CheckCaptcha($userResponse) {
$fields_string = '';
$fields = array(
'secret' => 'secret_key',
'response' => $userResponse
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}
$result = CheckCaptcha($_POST['g-recaptcha-response']);
if ($result['success']) {
echo 'success';
} else {
echo 'error';
}
}
?>
So now in your javascript, you can use the data variable inside success:function(data) in an if statement:
if(data == 'success') {
registerUser(name, email, password); // not a real function, just an example
}

How do I send a single html form to OneSignal server and another Server

I have a form that requires to be sent to OneSignal and then to a mySql db on another server
<form action="AppPushUserOne.php" method="post">
<textarea class="form-control" id="Message" name="Message" rows="5" placeholder ="Please insert your Incident and Deployment location here..."></textarea>
<br>
<button type="submit" class="btn btn-success btn-lg btn-block">Send Push Notification Message</button>
<button onclick="postTimeEvent();" class="btn btn-success btn-lg btn-block">Send DB</button>
</form>
The Submit button goes to OneSignal and the second button goes to a mySql db on another server. How would I combine those two buttons? I do not think it is wise to add type="submit" and onclick="postTimeEvent(); to the same button.
php I am using
<?php
function sendMessage($message){
$content = array(
"en" => $message
);
$headings = array(
"en" => 'Pembina User here'
);
$fields = array(
'app_id' => "be8a65fa-xxxx-xxxx-xxxx-xxxxxxxxxxx",
'ios_badgeType' => 'SetTo',
'ios_badgeCount' => '1',
'included_segments' => array('All'),
'headings' => $headings,
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage($_POST['Message']);
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
js form I am using
<script>
function postTimeEvent() {
var event_log = document.getElementById("Message").value;
var dataString = 'event_log1=' + event_log;
if (event_log == '')
{
alert("Please Fill All Fields");
}
else
{
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
</script>
Ideally, your PHP code in AppPushUserOne.php should be taking care of sending the same message to your MySQL DB. You can do this by simply appending the code from your ajax.php file to AppPushUserOne.php, or you may use curl to POST the data to ajax.php once you are done sending it to OneSignal.
However, if you wish to do it via JavaScript, you will have to call the postTimeEvent() function before the form is submitted, otherwise the AJAX call to ajax.php might not get triggered. To do this, give an id to your form (e.g. myForm), set type="button" for your button, and once the AJAX call is successful, submit your form.
<form id="myForm" action="AppPushUserOne.php" method="post">
<textarea class="form-control" id="Message" name="Message" rows="5" placeholder ="Please insert your Incident and Deployment location here..."></textarea>
<br>
<button type="button" onclick="postTimeEvent();" class="btn btn-success btn-lg btn-block">Send Push Notification Message and Send to DB</button>
</form>
<script>
function postTimeEvent() {
var event_log = document.getElementById("Message").value;
var dataString = 'event_log1=' + event_log;
if (event_log == '')
{
alert("Please Fill All Fields");
}
else
{
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
$('#myForm').submit();
}
});
}
//return false;
}
</script>

Possibly sending data incorrectly? Posting a form submission to PHP and then to an external API and response says included field is missing

I have a form that I want to submit to an external API. To do this without getting a cross-origin error I found a way to pass data from the form to a PHP file and then from there I can make the POST to the outside API and return the response to my client file and read the contents of the response.
However I'm getting 400 errors with a message saying "password is missing" when password is definitely not missing. Is there something wrong with my php or javascript that's causing the data not to be sent correctly? Please let me know if you see something wrong. I'm new to php.
Another thing worth noting is that when I run this code it still hits the success case in the JavaScript instead of hitting the error case. Which makes it extra strange. The response definitely doesn't give an object with properties that are expected.
the error looks like this: ""jsonCode":402,"message":"402 Missing password","requestID":"arhwerhwarawtr"}
html form
<form action="hello.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="hidden" id="name" name="name" value="johndoe">
<input type="hidden" id="password" name="password" value="sfhsrtjsgargjk">
<input type="text" id="id" name="id" value="" placeholder="username" />
<input type="text" id="secret" name="secret" value="" placeholder="password" />
<input type="submit" name="submit" value="Submit form" />
</form>
php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": callAPI('POST','www.sample.com', $action); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function callAPI($method, $url, $data){
$curl = curl_init();
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
$result["json"] = json_encode($result);
echo json_encode($result);
return $result;
}
?>
JavaScript:
$(document).ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "hello.php",
data: data,
success: function(data) {
// manipulate response data
// $(".the-return").html(
// "First Value: " + data["username"] + "<br />Second Value: " + data["password"] + "<br />JSON: " + data["json"]
// );
console.log(data);
// alert("Form submitted successfully.\nReturned json: " + data);
}, error: function(data){
alert("Form submitted unsuccessfully.\nReturned json: " + data.jsonCode + data.message);
}
});
return false;
});
});

Return information result to multiple input fields

I am attempting to create a simple web element that on request, retrieves the page title / meta description of a webpage by using: php / ajax / jquery.
I have it working to a point, though I am not sure how to prepare the returned information in the PHP and on success, so that the $title appears in an input field and the $description appears in a separate input field.
At the moment it just returns to one echo'ed block.
HTML
<a href="javascript:retrievepageinformation()" >Action request</a>
<div>The URL</div>
<input name="theaddress" type="text" id="theaddress" value="http://">
<div>The result</div>
<input name="title" id="title" value="" />
<input name="description" id="description" value="" />
Javascript
function retrievepageinformation () {
$("#title").val('Retrieving..');
$("#description").val('Retrieving..');
var dataqueryurl = $("#theaddress").val();
$.ajax({
type: "POST",
url: "request-information.php",
data: "dataqueryurl="+ dataqueryurl,
success: function(dataresult){
$("#title").ajaxComplete(function(){
$(this).val(dataresult);
});
}
});
}
PHP (request-information.php)
if(isSet($_POST['dataqueryurl'])) {
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$dataqueryurl = $_POST['dataqueryurl'];
$html = file_get_contents_curl($dataqueryurl);
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
// Get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description')
$description = $meta->getAttribute('content');
}
// Data to pass back to input field 'Title'
echo $title;
// Data to pass back to input field 'Description'
echo $description;
}
To pass back information from request-information.php you can use concept of array and json_encode.
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$dataqueryurl = $_POST['dataqueryurl'];
$html = file_get_contents_curl($dataqueryurl);
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
// Get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description'){
$description = $meta->getAttribute('content');
}
}
$result = array('title'=>$title, 'desc'=>$description);
echo json_encode($result);
}
And to get this information in your javascript you can use $.parseJSON() in the success callback of ajax.
function retrievepageinformation () {
$("#title").val('Retrieving..');
$("#description").val('Retrieving..');
var dataqueryurl = $("#theaddress").val();
$.ajax({
type: "POST",
url: "request-information.php",
data: "dataqueryurl="+ dataqueryurl,
success: function(dataresult){
dataresult = $.parseJSON(dataresult);
$("#title").val(dataresult.title);
$("#description").val(dataresult.desc);
}
});
}
In the php side
echo json_encode(array("title"=>"My title","description"=>"Test description"));
In the ajax success
success: function(dataresult){
$("#title").val(dataresult.title);
$("#description").val(dataresult.description);
}
FYI
json_encode

how to create a POST with request in php or javascript

how to create a post with request in php or javascript for steam web API
Example post:
https://api.steampowered.com/IEconService/CancelTradeOffer/v1/?key=STEAM_API_KEY&tradeofferid=TRADE_OFFER_ID
when i use it in a browser i get:
Method Not Allowed
This API must be called with a HTTP POST request
In C# this was written as:
private bool CancelTradeOffer(ulong tradeofferid)
{
string options = string.Format("?key={0}&tradeofferid={1}", ApiKey, tradeofferid);
string url = String.Format(BaseUrl, "CancelTradeOffer", "v1", options);
Debug.WriteLine(url);
string response = SteamWeb.Fetch(url, "POST", null, null, false);
dynamic json = JsonConvert.DeserializeObject(response);
if (json == null || json.success != "1")
{
return false;
}
return true;
}
If you are using jQuery then there is a very handy function to do this.
$.post( "http://api.example.com/get-some-value", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
But be careful about cross domain ajax when calling it from JS.
EDIT
For the comment.
You have to include jQuery into your page and then you can call anything within the very useful and handy $( document ).ready() that jQuery supplies.
$(document).ready(function(){
$.post( "http://api.example.com/get-some-value", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
})
UPDATE:
Try this:
$url = 'https://api.steampowered.com/IEconService/CancelTradeOffer/v1/';
$postData = array();
$postData['key'] = $STEAM_API_KEY;
$postData['tradeofferid'] = $TRADE_OFFER_ID;
$parameters=json_encode($postData);
$headers = array( "Accept-Encoding: gzip",
"Content-Type: application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
$resultt = curl_exec($ch);
var_dump($resultt);
curl_close($ch);
Or use this as a function to POST values
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $k => $v)
{
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
Final Answer:
PHP Curl Post, works OK :)
Please give credits to WD :)
$url = 'http://api.steampowered.com/IEconService/CancelTradeOffer/v1/';
$postData = array();
$postData['key'] = ""; // insert variable
$postData['tradeofferid'] = ""; // insert variable
$fields = '';
foreach($postData as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($postData));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
var_dump($result);
curl_close($post);
jQuery Post, works OK :)
Please give credits to SRC :)
<script src="jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
$.post( "http://api.steampowered.com/IEconService/CancelTradeOffer/v1/", { key: "SteamApiKey", tradeofferid: "TradeOfferID" })
//This part does not work -- but is not needed to post data
//.done(function( data ) {
// alert( "Data Loaded: " + data );
//});
})
</script>
To Check Trade Offer status in PHP use:
//Check if trade offer was canceled
//Get File and avoid error if the server is down
$CheckTradeOfferID = ""; // add variable
$BotSteamApiKey = ""; // add variable
if (!$data = #file_get_contents("https://api.steampowered.com/IEconService/GetTradeOffer/v1/?key=".$BotSteamApiKey."&tradeofferid=".$CheckTradeOfferID."&format=json")) {
print 'Steam Api is Down';
} else {
$json=json_decode($data,true);
$TradeOffersResponse = $json['response'];
if (empty($TradeOffersResponse)) {
print "Trade Offer ID not found!!!";
}else{
$trade_offer_state = $json['response']['offer']['trade_offer_state'];
$TRANSLATE_Trade_Offer_State = "Unknown";
if($trade_offer_state == "1"){ $TRANSLATE_Trade_Offer_State = "Invalid"; }
if($trade_offer_state == "2"){ $TRANSLATE_Trade_Offer_State = "Trade Offer Sent"; }
if($trade_offer_state == "3"){ $TRANSLATE_Trade_Offer_State = "Trade Offer Accepted"; }
if($trade_offer_state == "4"){ $TRANSLATE_Trade_Offer_State = "The User Sent A Counter Offer"; }
if($trade_offer_state == "5"){ $TRANSLATE_Trade_Offer_State = "Trade Offer not accepted before the expiration date"; }
if($trade_offer_state == "6"){ $TRANSLATE_Trade_Offer_State = "The sender cancelled the offer"; }
if($trade_offer_state == "7"){ $TRANSLATE_Trade_Offer_State = "User Declined the Trade Offer"; }
if($trade_offer_state == "8"){ $TRANSLATE_Trade_Offer_State = "Some of the items in the offer are no longer available"; }
print $TRANSLATE_Trade_Offer_State;
}
}

Categories