Redirect in Slim - ajax

I have an ajax request, but I need my response to redirect to a certain twig template. This is what I have:
$response = ['success'=>false];
return $this->view->render($resp, 'spotlight-results.twig',['data' => $response] );
The problem with this is I am receiving the page in the console, this is not replacing the page that makes the request. I don't know if I explained myself correctly...

I have found the answer:
$loader = new Twig_Loader_Filesystem('../templates/');
$twig = new Twig_Environment($loader);
$template = $twig->loadTemplate('spotlight-results.twig');
$message = ['success' => false];
$view = $template->render(['data' => $message]);
$response = ['success' => false, 'view' => $view];
This way I return my template, with my desired content, $message

Related

How to post request with query params in laravel 9

I am trying to send post request with query params. just like this screenshot
I used Http::post but it supports only json as far as I know. I just want to send request just like the screenshot. cause API data only supports parameter wise. Here What I tried but failed to achieve that.
FormController.php:
public function post_parameter_wise(Request $request,$lp_campaign_id, $lp_campaign_key, $first_name, $last_name, $email, $phone, $zip_code){
$form = new Form();
$fName = $form->first_name = $request->get($first_name);
$lName = $form->last_name = $request->get($last_name);
$cCmail = $form->email = $request->get($email);
$cPhone = $form->phone = $request->get($phone);
$zCode = $form->zip_code = $request->get($zip_code);
$response = Http::post("https://t.vivint.com/post.do", [
"lp_campaign_id" => $lp_campaign_id,
"lp_campaign_key" => $lp_campaign_key,
// "lp_supplier_id" => "",
"first_name" => $fName,
"last_name" => $lName,
"email" => $cCmail,
"phone" => $cPhone,
"zip_code" => $zCode
]);
dd($response);
Can't leave a comment so disregard this as the answer
Preferably, you just need to change it from a Post request to a Get request and it will work
$response = Http::get("https://t.vivint.com/post.do", [...
But a post request will contain the data as a post request should.
If you have to use post and define the query params then you should do it as follows
public function post_parameter_wise(Request $request,$lp_campaign_id, $lp_campaign_key, $first_name, $last_name, $email, $phone, $zip_code){
$form = new Form();
$fName = $form->first_name = $request->get($first_name);
$lName = $form->last_name = $request->get($last_name);
$cCmail = $form->email = $request->get($email);
$cPhone = $form->phone = $request->get($phone);
$zCode = $form->zip_code = $request->get($zip_code);
$response = Http::post("https://t.vivint.com/post.do?lp_campaign_id=".$lp_campaign_id."&lp_campaign_key=".$lp_campaign_key."&first_name=".$fName."&last_name=".$lName."&email=".$cCmail."&phone=".$cPhone."&zip_code=".$zCode, []);
dd($response);
Although this is really just forcing it to

file_get_contents() returning false for Google reCAPTCHA v3

I have been trying to implement Google reCAPTCHA v3 by using the following PHP source code:
<script src="https://www.google.com/recaptcha/api.js?render=6Ldl-98fAAAAAKRPodblUlTcVgvrfWZ_8lODjmZA"></script>
<?php
if(isset($_POST) && isset($_POST["btnSubmit"]))
{
$secretKey = '6Ldl-98fAAAAAD3ekajHHVBi2X4fZTW37bI5IGUN';
$token = $_POST["g-token"];
$ip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = array('secret' => $secretKey, 'response' => $token, 'remoteip'=> $ip);
// use key 'http' even if you send the request to https://...
$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data)
));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);
if($response->success)
{
echo '<center><h1>Validation Success!</h1></center>';
}
else
{
echo '<center><h1>Captcha Validation Failed..!</h1></center>';
}
}
?>
The problem is that every time I run this and step through the code line by line, I notice that the file_get_contents() function is always returning false and is assigning false to the '$result' variable. Why is this?
$result = file_get_contents($url, false, $context);
I would appreciate any advice that I can get.
From docs: 'null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.'
Show us $response, so var_dump($response). In recaptcha v2 i had empty string or token lately. That's why I ask for response, json decode will decode if there is proper json value.
I'd bet you get empty result and json_decode fails.

How can I redirect current page to post response with guzzle (laravel)

For example, I have a form:
<form method='post' action='https://test.com'>
<input name='name' value='test'>
<button name='test' type='submit'> </button>
</form>
And after submit this redirects me to another page.
My question is 'how can I do the same thing with guzzle from a controller?' I tried to make:
$client = $client = new GuzzleHttpClient();
$response = $client->post('https://test.com',
form_params => [
'name' => 'test'
]);
return $response->getBody()->read(1024);
And here I am getting a response that I wanted. but I want to redirect my current page to page with the response.
Use return redirect()->back() in method controller
You have to try something like this
$client = $client = new GuzzleHttpClient();
$response = $client->post('https://test.com',
form_params => [
'name' => 'test'
]);
$response_to_return = $response->getBody()->read(1024);
return redirect()->back()->withInput()->with('response_to_return', $response_to_return);

Add a new value to insert it

hello i have this function insertion works very well
function add_post(){
$this->form_validation->set_rules('user_id','User Id','trim|required');
//set msg if form validation false
if($this->form_validation->run() == FALSE){
$response = array('status' => FAIL, 'message' => strip_tags(validation_errors()));
$this->response($response);
}
$is_exist = $this->common_model->getsingle(USERS,array('userId'=>$this->post('user_id')));
if($is_exist){
$is_active = $this->common_model->getsingle(USER_COUPON,array('user_id'=>$is_exist->userId,'status'=>1));
$data['user_id'] = $is_exist->userId;
$data['user_coupon_id'] = $is_active->userCouponId;
$data['email'] = $is_exist->email;
$result = $this->common_model->insertData(USER_COUPON_SCAN,$data);
$response = array('status' => SUCCESS, 'message' => "success");
$this->response($response);
}
$response = array('status' => FAIL,'message' =>"No record found please try again");
$this->response($response);
}
the function recovers a single value user_id,I want to get a new value send by post (name admin_id) and isert in user_coupan_scan table
If you are sure that your code is working well, You can receive posted admin_id in following way.
function add_post(){
$this->form_validation->set_rules('user_id','User Id','trim|required');
//set msg if form validation false
if($this->form_validation->run() == FALSE){
$response = array('status' => FAIL, 'message' => strip_tags(validation_errors()));
$this->response($response);
}
$is_exist = $this->common_model->getsingle(USERS,array('userId'=>$this->post('user_id'))); // You may need to change $this->post('user_id') to $this->input->post('user_id')
if($is_exist){
$is_active = $this->common_model->getsingle(USER_COUPON,array('user_id'=>$is_exist->userId,'status'=>1));
$data['admin_id'] = $this->input->post('admin_id'); // make sure that the column name in your table is admin_id
$data['user_id'] = $is_exist->userId;
$data['user_coupon_id'] = $is_active->userCouponId;
$data['email'] = $is_exist->email;
$result = $this->common_model->insertData(USER_COUPON_SCAN,$data);
$response = array('status' => SUCCESS, 'message' => "success");
$this->response($response);
}
$response = array('status' => FAIL,'message' =>"No record found please try again");
$this->response($response);
}
In above answer, I have added one line i.e. receiving admin_id in post data.
$data['column_name_in_your_table'] = $this->input->post('name_in_post_data');
To receive data from post method you can do it like this
$some_name = $this->input-post('name');
Hope it helps.

HybridAuth send tweet with image

I'm using the HybridAuth library.
I'd like to be able to post message to my authenticated users twitter profile with images.
The setUserStatus method works well to automatically send a tweet.
I wrote the following method :
function setUserStatus( $status, $image )
{
//$parameters = array( 'status' => $status, 'media[]' => "#{$image}" );
$parameters = array( 'status' => $status, 'media[]' => file_get_contents($image) );
$response = $this->api->post( 'statuses/update_with_media.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
The message I get from twitter is :
Ooophs, we got an error: Update user status failed! Twitter returned an error. 403 Forbidden: The request is understood, but it has been refused.
How Can I get more precise info about error ?
Does anybody allready success in sending a picture attached to a tweet ?
Thanks !
Hugo
Thanks #Heena for making myself wake up on this question, I MADE IT ;)
function setUserStatus( $status )
{
if(is_array($status))
{
$message = $status["message"];
$image_path = $status["image_path"];
}
else
{
$message = $status;
$image_path = null;
}
$media_id = null;
# https://dev.twitter.com/rest/reference/get/help/configuration
$twitter_photo_size_limit = 3145728;
if($image_path!==null)
{
if(file_exists($image_path))
{
if(filesize($image_path) < $twitter_photo_size_limit)
{
# Backup base_url
$original_base_url = $this->api->api_base_url;
# Need to change base_url for uploading media
$this->api->api_base_url = "https://upload.twitter.com/1.1/";
# Call Twitter API media/upload.json
$parameters = array('media' => base64_encode(file_get_contents($image_path)) );
$response = $this->api->post( 'media/upload.json', $parameters );
error_log("Twitter upload response : ".print_r($response, true));
# Restore base_url
$this->api->api_base_url = $original_base_url;
# Retrieve media_id from response
if(isset($response->media_id))
{
$media_id = $response->media_id;
error_log("Twitter media_id : ".$media_id);
}
}
else
{
error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
}
}
else
{
error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
}
}
if($media_id!==null)
{
$parameters = array( 'status' => $message, 'media_ids' => $media_id );
}
else
{
$parameters = array( 'status' => $message);
}
$response = $this->api->post( 'statuses/update.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
To make it work you have to do like this :
$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );
$twitter_status = array(
"message" => "Hi there! this is just a random update to test some stuff",
"image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );
Enjoy !
I did not understand it for hybridauth then I used this library
https://github.com/J7mbo/twitter-api-php/archive/master.zip
Then I was successful using code below: (appears elsewhere in stack)
<?php
require_once('TwitterAPIExchange.php');
$settings= array(
'oauth_access_token' => '';
'oauth_access_secret' => '';
'consumer_key' => '';
'consumer_secret' => '';
// paste your keys above properly
)
$url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json";
$requestMethod = "POST";
$tweetmsg = $_POST['post_description']; //POST data from upload form
$twimg = $_FILES['pictureFile']['tmp_name']; // POST data of file upload
$postfields = array(
'status' => $tweetmsg,
'media[]' => '#' . $twimg
);
try {
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url_media, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "You just tweeted with an image";
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>

Resources