I am having an issue with my form. The issue is that when submit is clicked the jQuery does not work within the response.length > 0 statement but however the form is working and importing data but I need it to update the div and load the thank you page instead of acting like its doing nothing :)
It should be response.length > 0 - then load the errors and update div else go to the thank you page
jQuery:
$('#mountianForm').submit(function(e) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
if (response.length > 0) {
$('#mountianFormResponse').html(response); // update the DIV
} else {
window.location.href = 'https://example.com/thank-you/';
}
}
});
e.preventDefault();
});
Process Code:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$url = 'https://id.infusionsoft.com/app/form/iframe/formID';
$userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36';
if (!empty($_GET))
{
$url .= '?'.http_build_query($_GET);
}
$isPOST = !empty($_POST);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_POST, $isPOST);
if ($isPOST)
{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
}
$response = curl_exec($ch);
curl_close($ch);
if(preg_match('/(<ul>.*<\/ul>)/is', $response, $match)){
$match[1];
}else{
$error = "Error";
$file = fopen("mountianProxyerror.php", 'w+'); // Create a new file, or overwrite the existing one.
fwrite($file, $error);
fclose($file);
}
?>
I think you didn't return the response from your process code.
if(preg_match('/(<ul>.*<\/ul>)/is', $response, $match))
{
$match[1];
$resp = array('status' => TRUE,'msg' => 'success','resp' => $response);
}
else
{
$error = "Error";
$file = fopen("mountianProxyerror.php", 'w+'); // Create a new file, or overwrite the existing one.
fwrite($file, $error);
fclose($file);
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
And in your ajax
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
dataType : 'json',
success: function(response) { // on success..
alert(response.msg);
if (response.status == true) {
$('#mountianFormResponse').html(response.resp);
// Do whatever with the success code
}
else
{
window.location.href = 'https://example.com/thank-you/';
}
}
});
Related
If there is an error in the js/send_to_telegram.php file, then the error script will work. How to do it?
jQuery("form").submit(function () {
var form_data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "js/send_to_telegram.php",
data: form_data,
success: function (result) {
donemodal.style.display = "block";
},
error: function (jqXHR, exception) {
errormodal.style.display = "block";
}
});
});
in js/send_to_telegram.php the following code:
$token = "5306003979:AAEPK2NhlxW";
$chat_id = "497358";
$txt = htmlspecialchars($_POST["text"]);
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");
Now, even if you enter the wrong token in $sendToTelegram, it returns success. How to get error if token is wrong?
Short answer: It doesn't use API response status code unless you tell him does that. What if we sent multiple HTTP requests and got different status codes? Which of them should be used?
Solution: This is what you need:
<?php
function post($url, $fields = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
if (is_array($fields) && count($fields)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
$response = post("https://api.telegram.org/bot{$token}/sendMessage", [
'chat_id' => $chat_id,
'text' => $txt,
]);
if ($response->ok) {
echo '{"message": "ok"}';
} else {
http_response_code(500);
echo '{"message": "Something went wrong"}';
}
Goal:
Log into processor's site using their API and store the success response into COOKIEs and SESSIONs on my site.
What almost works:
jQuery(document).ready(function($){
$.ajax({
type: 'POST',
url: '{url-to-api-call}',
xhrFields: {
withCredentials: true
},
dataType: 'text',
data: 'Email={email}&GuestSessionToken={token}&Password={pass}&Format=JSON&RememberMe=true',
processData: false,
crossDomain: true,
success: function (res) { console.log('success'); },
error: function (jqXHR, textStatus, ex) {
console.log('error');
}
});
});
Why it doesn't work:
I'm unable to store the response to COOKIEs and SESSIONs.
What I would like to work:
$url = {url-to-api};
$curl = curl_init();
$curl_post_data = array(
'Email' => $fields['user_email'],
'GuestSessionToken' => $_COOKIE['SessionToken'],
'Password' => $fields['user_pass'],
'Format' => "JSON",
'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);
if ($content_array['StatusCode'] == 'OK') {
$fields['UserId'] = $content_array['Data']['UserId'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionToken'] = $content_array['Data']['Token'];
return true;
} else {
$errors->add( 'error', 'Unable to sign in.' );
return false;
}
Why it doesn't work:
This will return a success response that I can use to set the COOKIEs and SESSIONs, but it will not log the user into the processor's site.
Why I think it doesn't work:
The ajax call wouldn't sign the user in until I added the xhrFields part. I think if I could find a cURL equivalent for the xhrFields part, I would be all set.
Thanks in advance!
My duct tape fix.
<?php
// If signin form is submitted and signin cURL was successful.
echo (isset($fields['signin_script'])) ? $fields['signin_script'] : "";
function processor_signin(&$fields, &$errors) {
$url = '{url-to-api-call}';
$curl = curl_init();
$curl_post_data = array(
'Email' => $fields['user_email'],
'GuestSessionToken' => $_COOKIE['SessionToken'],
'Password' => $fields['user_pass'],
'Format' => "JSON",
'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);
if ($content_array['StatusCode'] == 'OK') {
$fields['UserId'] = $content_array['Data']['UserId'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionToken'] = $content_array['Data']['Token'];
// Duct tape fix
$fields['signin_script'] = "
<script>
jQuery(document).ready(function($){
$.ajax({
type: 'POST',
url: '{url-to-api-call}',
xhrFields: {
withCredentials: true
},
dataType: 'text',
data: '
Email=".$fields['user_email']."
&GuestSessionToken=".$_COOKIE['SessionToken']."
&Password=".$fields['user_pass']."
&Format=JSON
&RememberMe=true',
processData: false,
crossDomain: true,
success: function (res) { console.log('signin success'); },
error: function (jqXHR, textStatus, ex) {
console.log('signin error');
}
});
});
</script>
";
return true;
} else {
$errors->add( 'error', 'Unable to sign in.' );
return false;
}
}
?>
Maybe you are logged in but you are not storing the cookies.
So you need to parse the headers and in the end store all cookies. In proceeding requests you need to send back all cookies that you retrieved before.
Here is an example how to retrieve the cookies and other headers from the server:
public function sendRequest(HttpRequest $request)
{
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getHeaders());
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, [$this, 'fetchHeader']);
...
$content = curl_exec($ch);
...
}
/**
* #param resource $ch - curl handle
* #param string $header
*
* #return int
*/
private function fetchHeader($ch, $header)
{
$headerParts = explode(': ', $header, 2);
if (2 === count($headerParts)) {
$headerName = strtolower($headerParts[0]);
if ('set-cookie' === $headerName) {
$this->responseHeaders[$headerName][] = trim($headerParts[1]);
return strlen($header);
}
$this->responseHeaders[$headerName] = trim($headerParts[1]);
}
return strlen($header);
}
I am using facebook login using oauth. Sometime I am getting proper accessToken or sometime this kind of garbage values in accessToken
{"source":"uni","s":"s","p":{"z":"0","c":"0","i":"287"},"r": {"z":"1","c":"15239"},"node_id":"23.57.77.12"}.
Because of that my next requests to graph API fails. What is that thing and How do I handle this??
I have multiple domains ex. www.example.com, www.example12.com, www.example22.com etc.
I have created app for www.example.com on facebook and using it for all domains using the window.postmessage:
homepage.php (When user click on facebook login button):
if(!window.addEventListener){
window.attachEvent("onclick", processFacebookLogin);
}
else{
window.addEventListener("message", processFacebookLogin, false);
}
var width = 500;
var height = 500;
var left = ((window.innerWidth / 2) - (width / 2)) + window.screenLeft;
var top = ((window.innerHeight / 2) - (height / 2)) + window.screenTop;
winObj = window.open("http://www.example.com/fb-login?currentDomain=www.example12.com", "fbwindow", "height="+width+",width="+height+",top="+top+",left="+left);
function processFacebookLogin(e) {
winObj.close();
if(e.data != "error" && e.data != "missing_param"){
accessToken = e.data;
$.ajax({
async: false,
url: "UrlToProcessFacebookLogin",
type: "POST",
dataType: "json",
data:
{
"medium" :"facebook",
"accessToken" : accessToken
},
success: function(data)
{
//redirect to some another url
}
});
}
}
child window url page contains the following code fbLoginController.php:
The above window.open contains the indexAction url of fbLoginController (I am using Zend Framework):
public function indexAction()
{
$communityDomain = preg_replace('#^https?://#', '', $_GET['community']);
$fbLoginUrl = "https://www.facebook.com/v1.0/dialog/oauth?client_id=FbAppClientId&scope=AllRequiredScopes&auth_type=rerequest&return_scopes=true&display=popup&redirect_uri=http://www.example.com/fb-login/fb-response?community=".$communityDomain;
$this->_redirect($fbLoginUrl);
exit;
}
public function fbResponseAction()
{
$arrParams = $this->_getAllParams();
$code = $arrParams['code'];
$communityDomain = $arrParams['community'];
$grantedScopes = $arrParams['granted_scopes'];
$error = $arrParams['error'];
if(!empty($error))
{
echo "<script>window.opener.postMessage('error', 'http://".$communityDomain."');</script>";
exit;
}
if(empty($communityDomain) || empty($grantedScopes))
{
echo "<script>window.opener.postMessage('missing_param', 'http://".$communityDomain."');</script>";
exit;
}
$curlUrl = "https://graph.facebook.com/v1.0/oauth/access_token?client_id=FbAppClientId&client_secret=FbAppClientSecret&code=" . $code . "&redirect_uri=http://www.example.com/fb-login/fb-response?community=" . $communityDomain;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, 0);
curl_setopt($ch, CURLOPT_POST, 0);
$curlResponse = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);
parse_str($curlResponse,$parsedStr);
echo "<script>window.opener.postMessage('".$parsedStr['access_token']."', 'http://".$communityDomain."');</script>";
exit;
}
for proper understanding I have put each and every line of code in this question.
i have a html page that submits 2 forms(formone & formtwo) via ajax on one button click.
formone is submitted to formone.php and if it was succesfully sent formtwo is submitted to formtwo.php.
Everything works fine. Except i need to send data via POST to another php script (on another server, but for now i'm testing it on the same server).
I tried it with the following code but it wont work (i don't get any errors though).
Curl code i used!
function transferData()
{
//Set up some vars
$url = 'test.php';
$user = 'sampletext';
$pw = 'sampletext';
$fields = array(
'user'=>urlencode($user),
'pw'=>urlencode($pw)
);
// Init. string
$fields_string = '';
// URL-ify stuff
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
}
This is the code for my ajax form submission:
function submitforms()
{
FormSubmissionOne();
function FormSubmissionOne()
{
//Form 1
var $form = $('#formone');
$.ajax(
{
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function (msg)
{
FormSubmissionTwo();
},
error: function(msg)
{
alert(msg);
}
});
}
function FormSubmissionTwo()
{
//Form 2
var $form2 = $('#formtwo');
$.ajax(
{
type: 'POST',
url: $form2.attr('action'),
data: $form2.serialize(),
success: function (msg)
{
alert(msg);
//redirection link
window.location = "test.php";
}
});
}
}
This is test.php (receiving script from curl function)
$one = $_POST['user'];
$two = $_POST['pw'];
echo "results:";
echo $one;
echo "\r\n";
echo $two;
echo "\r\n";
There are a few issues, firstly, CURLOPT_POST is for a boolean not a count.
So change this:
curl_setopt($ch,CURLOPT_POST,count($fields));
to
curl_setopt($ch,CURLOPT_POST, 1); // or true
Secondly, you need to tell CURL that you want the returned data. You do that using CURLOPT_RETURNTRANSFER
So your curl related code should look like this:
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
print_r($result); // just see if result
//close connection
curl_close($ch);
Hi every one,
I have a login form which has mail id and password, on submit it should call an api which inturn generates a auth token. I have used POST method in Php curl but getting the following error.
Apache Tomcat/6.0.36 - Error report
.. some html styles..
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method
and this is my ajax call..
function callapi()
{
data = new Object();
var email= document.getElementById("input01").value;
var pwd=document.getElementById("input02").value;
if(email != ""&& pwd != "")
{
data.Email = email;
data.Pwd = pwd;
}
jQuery.ajax({
url: "http://localhost/stackato/nlogin.php",
type: "POST",
dataType:"json",
data:data,
error: function (data) {
alert('error--'+data);
},
success: function (data) {
if(data=="invalid")
{
}
else
{
window.location.href="finalstackatolists1.html";
}
}
});
}
and this is my curl php page
<?php
header('Content-type: application/json');
$url = $_SERVER['REQUEST_URI'];
$scriptname = $_SERVER['SCRIPT_NAME'];
$queryString = $_SERVER['QUERY_STRING'];
$mail=$_POST["Email"];
$pwd=$_POST["Pwd"];
$action = $_POST["action"];
$nurl = str_replace($scriptname,"...the api...",$url);
//open connection
$ch = curl_init();
$data = array("username" => $mail, "password" => $pwd);
$req_data = json_encode($data);
curl_setopt($ch, CURLOPT_URL, $nurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req_data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//execute post
if( ! $result = curl_exec($ch)) {
die(curl_error($ch));
curl_close($ch);
}
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == '500')
{
header("Status: 500 Server Error");
}
curl_close($ch);
echo $result;
?>
(I tried it in REST-Client and the token has been generating)
Please help me to solve this.. thanks in advance..
You have to specify that the posted data is of type JSON
add this line to your curl code
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/json"));