Accept POST from other application - php

I have a CodeIgniter User Panel and a login form out of CodeIgniter Environment and I need to know how can I accept the post coming from this.
Basically, is:
My app send a POST with (login an password) to CodeIgniter application to login in successfully.
Obs: I read about CrossDomain POST with AJAX but doesn't work.
I tried this:
$("form").submit(function() {
$.ajax({
url: 'http://localhost/cp/login/auth',
type: 'POST',
crossDomain: true,
data: {login: $('#login').val(), passwd: $('#passwd').val()},
})
});
But when I click in submit button, I redirect to login page (CI) but don't log in.
I appreciate your patience. Thank you!

Add this header to your page. (http://localhost/cp/login/auth page)
header('Access-Control-Allow-Origin: *');

Say No for crossdomain ajax. Send data with post. And in your application check data and login user or redirect back if has errors.

I feel that you are trying to send data from ajax to a codeigniter function via post. Then you should do this:
function makeAjaxCall(){
$.ajax({
type: "post",
url: '<?php echo base_url(); ?>" + "MyController/Myfunction',
cache: false,
data: $('#MyForm').serialize()}); }
The form should be as
<form name="MyForm" id="MyForm" action="">
Submit Button as
<input type="button" onclick="makeAjaxCall();" value="Submit"/>
Then on the controller
class MyController extends CI_Controller{
public function Myfunction(){
$username = $this->input->post('username_field');
$password = $this->input->post('password_field');
//Do my stuff then redirect
}}
Hope that is helpful.

Hi to get info from other login app, you need to make a webservices or using curl
assuming that you app that make login and return data is working fine
in the other app, you need to make a call using curl like
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "username:password#example.com/controller/method/parm1/param2");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
//print result
var_dump($output);

Related

Send PHP's JSON response from an API call as part of AJAX success function

I have setup a page that takes the data from a form, serializes into JSON and then uses AJAX to call a PHP file to process the form data and send it to an API via cURL.
How can I get the response from the API to come back as part of the AJAX's success function?
At the start of my project, I was able to accomplish this because I was using the php as an include. But cannot use that method because the file is being executed from the AJAX call not from an include.
I tried to follow this tutorial, but just kept catching errors.
I've also scoured, reviewed and attempted more suggestions from various posts on this site than I can even count. Now, I'm asking for some help.
Here is the pertinent ajax on my index.php file.
$.ajax
({
type: "POST",
dataType : 'json',
async: false,
url: 'save_application.php',
data: { filename: fileName, applicationData: jsonFormString, job: adid },
success: function () { console.log("done");},
failure: function() {console.log('error');}
});
And here is the relevant part of the save_application.php file.
$curl = curl_init();
curl_setopt_array($curl, array(
//stuff here
));
$applicantresponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
And lastly, the $applicantresponse that comes back is formatted like this:
{
"applicationId": 123456789,
"links": {
"link1": "https://thisisalinkforLINK1.html", //THIS IS THE VALUE I WANT
"link2": "https://thisisalink.html",
"link3": "https://thisisalink.html"
}
}
Ultimately, I want to set a variable to the value for links->resume (ex: var resumeLink = (something goes here); \\returns https://thisisalinkforLINK1.html) back on my index.php within the success function so I can use that response for some other to-dos.
You need to output $applicantresponse from your save_application.php file so that it's returned to your calling code, and you need to change the success function in your ajax code to then use that data. It'll look something like this:
$applicantresponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
echo json_encode($applicantresponse);
and then...
$.ajax
({
...
success: function (data) {
console.log(data.links.link1);
// do something with the data that was returned
},
...
});
One thing that is important is that your php code not output any other text to the client. All other echo, print, debugging calls, all of that stuff, has to be removed, because otherwise you're not sending back valid json encoded data that jQuery knows how to interpret.
It looks like save_application.php uses the data submitted by $.ajax for the curl request, and you need to send part of the curl response back to the client to be used in the success function.
The curl response is already JSON, so the simplest thing to do is just
echo $applicantresponse;
which will send the entire curl response back to the client.
If you only want to send one of the links of it, you'll need to decode it and extract the specific piece you want, then re-encode that piece.
$applicantresponse = json_decode($applicantresponse);
$link = $applicantresponse->links->link1;
echo json_encode($link);

WordPress using AJAX connections to third-party server

I'm okay with WordPress and editing files but I've had to take over a website from the designers and I'm a bit stuck.
What they've done is create an AJAX file that is used for all website submitted forms, and all of those forms are redirected to their own servers, before being sent on to the customer.
Obviously this is not ideal for a variety of reasons, but I'm unsure how to fix it. There is a rule for each form/contact method, then a final rule at the bottom of the file that I presume applies to all the previous rules.
This is:
function postThis($data_to_post) {
$form_url = "https://abcdef.co.uk/__mailer/__send123456.php";
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL, $form_url);
curl_setopt($curl,CURLOPT_POST, sizeof($data_to_post));
curl_setopt($curl,CURLOPT_POSTFIELDS, $data_to_post);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
I'm not sure how to replace the https (which I've changed the URL of) bit with something that will simply send the forms from the website to the website owners email address, without the intercept.
You could set up individual jquery functions that are returned on form submit to point to a php email function.
Form:
<form onsubmit="return someFunction();">
</form>
Javascript:
function someFunction(){
var data = $('form').serialize();
$.ajax({
url: phpMailClass.php,
data: data,
method: 'post',
success: function(resp){
// Handle the response upon success
}
});
}
Receive the user inputs in a php file then use PHP's mail() function to send the form(s) to the desired recipients.

PHP: How to send cookies with REST API call by clicking on a link?

I'm new to the REST APIs style of web development. I have to send 2 cookies along with 1 REST API. How do I send them together by clicking on a link?
For example, if an user clicks on the link, it is supposed to make the REST API call and send the cookie along with it. I know how to do it in the cURL but I am confused as to how I can trigger that via a link. Ideally, the user should be able to download a zip file by clicking the link. The link should call the REST API and send 2 cookies over to get the zip file. I am able to get the raw code of the zip file using the following code but is not able to achieve that by clicking on the link.
$getResultsDetails = curl_init();
$getResults_service_url = '<URL of the REST API call>';
curl_setopt($getResultsDetails,CURLOPT_URL,$getResults_service_url);
curl_setopt($getResultsDetails,CURLOPT_COOKIE,"LWSSO_COOKIE_KEY=".$LWSSO_COOKIE_KEY.";QCSession=".$QCSession);
curl_setopt($getResultsDetails, CURLOPT_RETURNTRANSFER, true); //get response
$getResults_service_url_response = curl_exec($getResultsDetails);
curl_setopt($getResultsDetails, CURLOPT_RETURNTRANSFER, true);
if ($getResults_service_url_response === false) {
$info = curl_getinfo($getResultsDetails);
curl_close($getResultsDetails);
die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($getResultsDetails);
Any ideas how I can achieve that?
This is mostly a duplicate of this but with the added 'how do I?' part. So, heres the bit to add to the answer of that question.
just use a link to direct your user to the php script making the call.
you can do this in 2 ways:
1.
click me
read this answer for details on how to do the cookie part.
or
2. use an ajax call using jquery:
from jquery docs
$.ajax({
type: "POST",
url: "path/to/yourCurlScript.php",
data: data,
success: success,
dataType: dataType
});
same script is called, so process cookies in the same way.
for the best user experience I would probably opt for number 2. I dont know what it is that youre planning on retrieving from the API, but you can pipe it into a file using either.

Upload image from client web application to RESTful API

I've been working on building an API as a learning purpose. It is essentially a twitter-like micro post API. Alongside the API I've been building a client web application powered off of the API. I am able to successfully post statuses without any problems. But now I am trying to allow users to upload an image along with the post. The client application is built using the mvc pattern. I post the submitted post to my post controller via jQuery ajax like so:
$.ajax({
url: '../../posts/newPost',
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data);
$('#post-form-area').removeClass('loading');
$('#post-body').val('');
$('#files').val('');
$('#attached').find('img').remove();
$('#attached').hide();
},
cache: false,
contentType: false,
processData: false
});
I am able to successfully get the file data using the $_FILES array within my controller. However, I am having a lot of difficulty figuring out how to send this to my RESTful API. I created a class to handle my API calls and here is the code for my POST method:
$ds = json_encode($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $ds);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request
$result = curl_exec($ch);
Here is the data that I pass to post a text only status:
$data = array('user_id' => $_SESSION['user_id'], 'body' => $body, 'time' => $timestamp);
I have tried passing $_FILES['file']['tmp_name'] as part of the array, but on API side the $_FILES array is null. I tried following this example, but I ran in to the same problem.
The way my API is set up, if the $_SERVER['request_method'] is POST I get the contents from cURL from php://input and then pass these parameters to the necessary controller. Do I need to add anything here that will give me access to the $_FILES array? I've been digging for about 3 hours now and haven't been able to find anything that has helped me, so I appreciate any help.
Thanks!
Edit:
I don't see how this is a duplicate as the link you posted that it is a duplicate of has nothing to do with uploading an image through a RESTful service...
Edit 2:
I've narrowed it down to how I am sending the data from my client application because I am successfully able to use the following command line code to upload a file:
curl -X POST -F "image=#test.JPG" http://rest.mattaltepeter.com/posts/upload
And then the code to receive it:
public function uploadAction() {
$result['success'] = move_uploaded_file($_FILES['image']['tmp_name'], SITE_ROOT . '/uploads/' . $_FILES['image']['name']);
$result['data'] = UPLOAD_DIR . $_FILES['image']['name'];
return $result;
}
I came across this tutorial and have been able to implement it fine with a static URL to an image, but that isn't very helpful as I want a user to be able to select their own image to upload with their post. So it looks like my issue is revolved around getting the full path as that tutorial mentions on line 4 of the first code block and sending it to the api. So how do I get that same information from the $_FILES array instead of a static file URL?
Finally figured it out. It had to do with using json_encode() to send my POST data. As soon as I tried it with out json_encode(), I had access to the $_FILES array. I think I'll have to add a parameter to my ApiCall->post() method to tell it if I want to json_encode() the data I wish to pass.

Submit external form without leaving the page/site

I looked through the site for answers to this, but nothing's spot on to what I need (this is close, except it doesn't actually submit the form: Prevent form redirect OR refresh on submit?).
I'm trying to incorporate a mailing list sign-up (code borrowed from a sign-up page hosted on ReverbNation) to a website.
The form submits properly, but the signee is redirected to a hideously rendered page on ReverbNation's site. I cannot modify their script and don't think there's an API I can use to keep things tidy.
Is there a way I can submit the form in the background, without the user being redirected?
Here's an example in PHP for tunneling a POST.
//set POST variables
$url = 'http://domain.com/url-to-post-to';
$fields = array(
// Add the fields you want to pass through
// Remove stripslashes if get_magic_quotes_gpc() returns 0.
'last_name'=>urlencode(stripslashes($_POST['last_name'])),
'first_name'=>urlencode(stripslashes($_POST['first_name'])),
'email'=>urlencode(stripslashes($_POST['email']))
);
//url-ify the data for the POST
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));
// returns the response as a string instead of printing it
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result;
If you're posting to the same domain, you can use an AJAX post. However, it seems you're trying to POST to different domain, so the browser's same origin policy will prevent you from doing so (http://en.wikipedia.org/wiki/Same_origin_policy). (JSONP can get around this but it doesn't work for POST)
Another way to get around this is to have your server do the POST and tunnel the response back to your page.
<form id='yourForm' action="" onsubmit="javascript: doPostToTunnelPage(); return false;">
<!-- inputs...-->
</form>
Make sure to return false, or your page will be redirected.
in my understand, you need send a form without redirect?
consider my example
$(function() {
$('#myForm').submit(function (e) {
e.preventDefault();
$.ajax({ /* params to send the form */ });
return false;
});
});
IIT it will work just because of the e.preventDefault.
If this method is called, the default action of the event will not be triggered.
See jQuery documentation here for more information.
Hope it help you

Categories