I'm building part of a Firefox OS app and I'm having to use the OpenBadges API, meaning I can't use more PHP, which would make this much simpler.
The problem I'm having now is that my data sent from an AJAX POST request:
$(function(){
$("#submitBtn").click(function(){
var mail = $('#mail').val();
$.ajax({
type: 'POST',
contentType: 'text',
dataType: 'JSON',
url: 'scripts/test.php',
data: {
mail: mail
},
success: function(data){
var jdata = jQuery.parseJSON(data);
alert("success! X: " + data);
}
});
});
});
...isn't being received by my PHP script:
<?php
if(isset($_POST['mail']))
{
$id_url = 'http://backpack.openbadges.org/displayer/convert/email';
$mail = $_POST['mail'];
$email = 'email='.$mail;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $id_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $email);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
curl_close ($curl);
$user_id = json_decode($result)->userId;
$test_var = json_decode($result);
echo $result;
//echo $test_var;
//echo $user_id;
}
//echo $mail;
?>
I keep getting a "cancelled" status on my PHP script in the Chrome dev tools Network tab, and I can see that it's sending the input in the form of "example%40gmail.com" instead of "#", but I'm not sure if that's part of the problem or not.
I've been looking and tweaking my code for about two days trying to figure out the problem, but none of the fixes that have worked for other people have worked for me.
Thanks in advance.
You're getting "cancelled" because the link you're clicking is being executed at the same time as your ajax call, in turn canceling it. What you need to do is use preventDefault() to prevent the click from canceling your request.
$(function(){
$("#submitBtn").click(function(e){
e.preventDefault(); // don't cancel the request
var mail = $('#mail').val();
$.ajax({
type: 'POST',
contentType: 'text',
dataType: 'JSON',
url: 'scripts/test.php',
data: {
mail: mail
},
success: function(data){
var jdata = jQuery.parseJSON(data);
alert("success! X: " + data);
}
});
});
});
Related
I want to confirm transaction from other third-party, e.g I pay goods of $50 to juma Joe after click pay button and pay page is still loading and tell me to wait almost 5 seconds to check if the transaction is processing succeed, and if the transaction succeeds, it redirects to a success page.
So i need javascript and html confirmation code call from php to check if transaction is success then to show redirect seconds.
Thank you
Bellow is code for for validate transaction
$result = array();
$url = 'https://api.xxxx.co/transaction/verify/reference';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer xxxxxxx']
);
$request = curl_exec($ch);
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
}
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
echo "Transaction was successful";
//Compete transaction
}else{
// Not complete
echo "Transaction not complete";
}
So. You can using ajax to request and response in you code.
Example:
PHP Code: validate.php
//....above you code here
// my code config response
$res = [
'mess' => null,
'status' => 404
];
//...you code validation result
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
//Compete transaction
$res['mess'] = "Transaction was successful";
$res['status'] = 200;
}else{
// Not complete
$res['mess'] = "Transaction not complete";
$res['status'] = 404;
}
// my code response mess
echo json_encode($res);
So, below my front-end code, using jQuery Ajax to send POST request.
Document you can check here
$(document).ready(function() {
function validate(){
$.ajax({
url: 'validate.php',
type: 'POST',
dataType: 'json',
success: function(res) {
if (res.status === 200) {
console.log("you code here for success");
} else {
console.log("you code here for fail");
}
},
error: function(err) {
console.log("Request is error with: " + err);
}
});
}
});
HTML for submit button. Call to javascript
<button id="submit" type="submit" onclick="validate();">Send Request</button>
function checking(){
$.ajax({
dataType: "json",
url: status.php,
success: function(data){
if (data.done=='y') window.location = 'done.html';
}
});
}
setInterval(checking,5000);
With this script, you can call for every 5 seconds. But the best practice is to use a webhook. For more information, search it up on your payment gateway API documentation.
status.php
$result = array();
$respond=array();
$url = 'https://api.xxxx.co/transaction/verify/reference';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer xxxxxxx']
);
$request = curl_exec($ch);
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
}
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
$respond[done]='y';
//Compete transaction
}else{
// Not complete
$respond[done]='n';
}
echo json_encode($respond);
I have been stuck for a while on this mistake and I just can't seem to find it. I get this error:
ERROR: SyntaxError: Unexpected string in JSON at position 1
I am trying to do an AJAX-request to dashboard.php using this dashboard.js file:
$(".next").click(function(){
console.log("next uitgevoerd");
i++;
huidige_pagina += 1;
document.getElementById("pagina").innerHTML = huidige_pagina;
$.ajax({
type: 'POST',
url: 'http://goad-as-05/ramon/logic/dashboard.php',
contentType: 'application/x-www-form-urlencoded',
dataType: 'JSON',
data: { "pagina": i },
success: function (resultaat) {
alert(resultaat);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + errorThrown);
}
});
});
Here is the php-code:
<?php
header("Content-Type: application/json; charset=utf-8", true);
if(isset($_POST["pagina"])){
$pageno = $_POST["pagina"];
echo $pageno;
} else {
echo "foutje";
}
// $url will contain the API endpoint
$url = "https://app.teamleader.eu/api/getContacts.php";
// $fields contains all the fields that will be POSTed
$fields = array(
"api_group"=>(GROUP_KEY),
"api_secret"=>(SECRET_KEY),
"amount"=>2,
"pageno"=>$pageno
);
// Make the POST request using Curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
// Decode and display the output
$api_output = curl_exec($ch);
echo curl_error($ch);
//$json_output = json_decode($api_output);
echo json_encode($api_output);
header('application/json');
// Clean up
curl_close($ch);
?>
Here is my html:
<div class="pagina">
<p id="pagina">1</p>
</div>
I am sure it is not my URL, as both files are in the same folder.
Do I have to use JSON.stringify("pagina":i) first and use that?
Any help is appreciated, it probably is the smallest mistake I just can't seem to find.
SOLUTION FOUND:
Refresh my javascript with ctrl+F5 when loading it, completely forgot about cache.... thanks everyone for trying to help!
Ramon
In PHP, you can not use the HEADER function after an output.
echo json_encode($api_output);
header('application/json'); // delete this line
the server ends up producing an error that makes the JSON string unusable.
EDIT:
header("Content-Type: application/json; charset=utf-8", true);
if(isset($_POST["pagina"])){
$pageno = $_POST["pagina"];
echo $pageno; // ERROR
} else {
echo "foutje";
}
with the echo $pageno; line write the result sent by POST generating an error.
EDIT 2:
echo curl_error($ch);
This line also produces an unencoded output in JSON
EDIT 3:
I'm happy that you've been able to find the solution to your problem and to prevent it from happening again I suggest you edit the JS file address so:
echo 'dashboard.js?'.time(); // disable browser cache
The problem was with the the browser cache, i forgot to use ctrl + f5 to reload the cache and reload my javascript that way, thanks for the help everyone!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to send trigger an email when a user completes a webform.
However I am getting the following error
Appreciate any advise on how to resolve this error.
JS file that will call the php function
$(function() {
$('.error').hide();
$(".request_demo").click(function() {
// validate and process form here
$('.error').hide();
var email = $("#email").val();
if (email == "") {
$("#email_error").show();
$("#email").focus();
return false;
}
var email = $("#email").val();
var dataString = '<p><strong>Email: </strong> ' + email + '</p>';
$.ajax({
type: "POST",
url: "/script/send.php",
data: { data: dataString, senderAddress: email },
success: function() {
// show a success message to your visitors
// clear input field values
$("#email").val('');
}
});
return false;
});
});
PHP file
<?php
if( isset($_POST) ){
$postData = $_POST;
$mailgun = sendMailgun($postData);
if($mailgun) {
echo "Great success.";
} else {
echo "Mailgun did not connect properly.";
}
}
function sendMailgun($data) {
$api_key = 'xxxxxxx1234';
$api_domain = 'our_domain';
$send_to = 'some#email.com';
// sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
// form data
$postcontent = $data['data'];
$reply = $data['senderAddress'];
$messageBody = "<p>You have received a new message from the contact form on your website.</p>
{$postcontent}
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
$config = array();
$config['api_key'] = $api_key;
$config['api_url'] = 'https://api.mailgun.net/v2/'.$api_domain.'/messages';
$message = array();
$message['from'] = $reply;
$message['to'] = $send_to;
$message['h:Reply-To'] = $reply;
$message['subject'] = "New Message from your Mailgun Contact Form";
$message['html'] = $messageBody;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $config['api_url']);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:{$config['api_key']}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,$message);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
?>
I am not sure this will solve your problem or not, but this may help you.
Please check what DATA TYPE is your server expecting. In your ajax request you haven't mentioned any Content-Type. As this is a POST request, jQuery will consider form data as default Content-Type. As I can see you are providing a JS Object as data, by default it will be converted to a query string before sending the request to the server.
If your server is expecting a json payload in the request, then you need to do JSON.stringify() you payload to convert the JS object into a JSON object.
ie. data : JSON.stringify({ data: dataString, senderAddress: email })
I'm query data from another sever by using curl_setopt PHP and Ajax
I've already to test my below function it is work but it seem not smooth enough because sometime when I try to refresh and internet got a little big slow I will never got data.How ever when i check on firebug in Firefox I found as below json respond.
"<html><head>
<meta http-equiv="refresh" content="0;url=http:MyPartnerWebsite!queryLuckNumberRecordByPeriods.action?gwqqnhmpepceiqqn">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
</head><body></body></html>
"
*I'm got stuck right now because I don't know how to do with this respond *
private function http_code() {
$ch = curl_init();
if (!$ch) {
die("Couldn't initialize a cURL handle");
}
$ret = curl_setopt($ch, CURLOPT_URL, "http://Mypartnerwebsite!queryLuckNumberRecordByPeriods.action");
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ret = curl_setopt($ch, CURLINFO_PRETRANSFER_TIME, 0.1);
$ret = curl_setopt($ch, CURLINFO_HTTP_CODE, true);
$ret = curl_setopt($ch, CURLOPT_PRIVATE, false);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$ret = curl_exec($ch);
$data;
$res;
if (empty($ret)) {
$res = 0;
$data = 0; // Partner server slow.
curl_close($ch);
} else {
$info = curl_getinfo($ch);
curl_close($ch);
if (empty($info['http_code'])) {
$res = 01;
$data = 01; // Got empty date from partner server
} else {
if ($this->errorType($info['http_code']) == TRUE) { // errors type
$data = $ret;
$res = $this->errorType($info['http_code']);
} else {
$data = $ret;
$res = 'unknowError';
}
}
}
echo json_encode(array('res' => $res, 'data' => $ret));
}
This is a function to check to know what type of server errors respond
Purpose I want to checking when my partner server errors and I will send this kind of errors to my website for make sure what kind of errors.
private function errorType($haystack) {
$errors = array(404, 200, 201, 204, 500, 501, 502, 503, 504, 505, 100, 203);
if (in_array($haystack, $errors)) {
return $haystack;
} else {
return FALSE;
}
}
Here is Jquery Ajax to fetch data from my own server
$.ajax({
method: "GET",
url: "<?PHP echo base_url('getcurrentday'); ?>",
dataType: "JSON",
beforeSend: function (xhr) {
},
success: function (data, textStatus, jqXHR) {
$(".loading").html("");
if (data.res !== 200) {
$("<p>Errors type:"+data.res+"</p>").appendTo(".errors");
} else {
if (data.data == false) {
getdata();// I want to reload Ajax if I got respond false and my data = '';
}
$.each(eval(ldata), function (i, val) {
$(val.anydata").appendTo(".result");
})
}
}
});
Please help.
It seems that your ajax call gets a timeout and therefor it is not always working. You can increase the timeout setting of ajax.
Furthermore you can add an error function to see when errors like timeouts occur.
$.ajax({
//your ajax code here...
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
},
timeout: 10000 // sets timeout to 10 seconds
});
The reason you still see the response in firebug is that the browser will anyways receive the server response, even on timeout, but it will not reach your jquery code.
I am trying to send a delete request to instagram api using ajax but my current javascript code display the response in alert box as:
<pre></pre><pre></pre>
so i cant find the problem why delete request is not successful! if i call the same php script(doit.php) from the browser and pass it media id then the delete will be successful!
could any one tell me what is wrong with my current delete ajax request that fails to make delete request to instagram api?
Instagram API Docs for Deleting Like
sample api response:
{
"meta": {
"code": 200
},
"data": null
}
javascript:
<script>
function deleteLike(a,b)
{
alert("MediaID:"+a+"\nId:"+b);
var url = "./doit.php";
$.post(url, {
"method": "post",
//"method": "delete",
"MediaID": a,
}, function(data)
{
var ajaxResponse = data;
alert("Response:"+ajaxResponse);
if (data.meta.code == 200) {
alert("sucessDelete");
}
})
}
</script>
PHP CODE:
$MediaIDvar= $_POST["MediaID"];
//$MediaIDvar= $_GET["MediaID"];
$url2 = "https://api.instagram.com/v1/media/".$MediaIDvar."/likes?xxxxx";
$api_response2 = get_data2(''.$url2);
$record2 = json_decode($api_response2); // JSON decode
echo '<pre>' . print_r($api_response2, true) . '</pre>';
echo '<pre>' . print_r($record2, true) . '</pre>';
// to see what is in the $api_response and $record object
/* gets the data from a URL */
function get_data2($url2) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$MediaIDvar= $_POST["MediaID"];
$MediaIDvar= $_GET["MediaID"]; // => this will overwrite the previous $MediaIDvar
it will work if you call the php script with a GET variable, not through ajax using POST ;-)