how to call curl cmd in Ajax - javascript

Here is my curl command is there anyway to execute this command using ajax
curl -X POST -u "CONVERSATION_USERNAME":"CONVERSATION_PASSWORD" -H "Content-Type:application/json" -d "{\"input\": {\"text\":\" \"}}" "https://gateway.watsonplatform.net/conversation/api/v1/workspaces/CONVERSATION_ID/message?version=2016-07-11"

This should work.
$.ajax({
url: "https://conversation_username:conversation_password#gateway.watsonplatform.net/conversation/api/v1/workspaces/CONVERSATION_ID/message?version=2016-07-11",
method: "POST",
headers: {
"Content-Type": "application/json"
},
data: {
input: {
text: " "
}
}
})
done(function(data) {
// handle success response
})
.fail(function(err) {
// handle error response
});
http://api.jquery.com/jquery.ajax/
edit - updated to handle success and error responses using promises.

Create a php file, put that command inside that file, return from it whatever you need from the curl response and call this php file via ajax.
file ajax_curl.php
<?php
//do your curl call here
//curl -X POST -u "CONVERSATION_USERNAME":"CONVERSATION_PASSWORD" -H "Content-Type:application/json" -d "{\"input\": {\"text\":\" \"}}" "https://gateway.watsonplatform.net/conversation/api/v1/workspaces/CONVERSATION_ID/message?version=2016-07-11"
//see http://php.net/manual/en/curl.examples-basic.php
//do a return like so if $url is you url
$defaults = array(
CURLOPT_URL => $url,
your_other_params => go_here,
CURLOPT_RETURNTRANSFER => 1
);
$ch = curl_init();
curl_setopt_array($ch, $defaults);
$result= curl_exec($ch);
if( ! $result = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
curl_close($ch);
echo json_encode($result);
?>
your calling js looks like
$.post( "ajax_curl.php", { passed_data: "pass_whatever_you_need" }, function( data ) {
console.log( data );
}, "json");
'data' now contains a json with the response from your curl call

Create a PHP file.here file name is chat.php
<?php
if(isset($_POST['conversation'])) {
$data = array("input"=>array("text"=>$_POST["conversation"]));
$url = "https://gateway.watsonplatform.net/conversation/api/v1/workspaces/a9379972-d820-4cdf-b1cb-ad0af898a534/message?version=2016-07-11";
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_USERPWD => "username:password",
CURLOPT_HTTPHEADER => array("Content-Type:application/json"),
CURLOPT_POSTFIELDS => json_encode($data),
));
$response = curl_exec($ch);
curl_close($ch);
print_r(json_decode($response));
}
?>
and call this by using Ajax
var xhr = new XMLHttpRequest();
//xhr.open('get', 'chat.php');
xhr.open("GET", "chat.php?data=" + data to be pass, false);
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
//alert(xhr.responseText);
talking = true;
botMessage=xhr.responseText;// 'This is the returned text.'
} else {
// console.log('Error: ' + xhr.status); // An error occurred during the request.
alert ('Error: ' + xhr.status);
}
}
};
// Send the request to send-ajax-data.php
xhr.send();

Related

Adding http response code in php breaks axios

After adding http response code in the login file axios is returning these errors even if the login email and password are correct and the catch block isn't executed I get these errors. If I remove the http_response_code(400) it will work and return the user or the message with 200 ok but I don't want that.
How do i fix it? thanks in advance.
Access to XMLHttpRequest at 'http://localhost/classroom-api/api/user/login.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
POST http://localhost/classroom-api/api/user/login.php net::ERR_FAILED
login.php
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');
require_once '../../vendor/autoload.php';
use Firebase\JWT\JWT;
require_once '../../config/Database.php';
require_once '../../models/User.php';
// Connect db
$database = new Database();
$db = $database->connect();
$user = new User($db);
try {
// Get posted data
$data = json_decode(file_get_contents("php://input"));
if(empty($data->email) || empty($data->password)) {
throw new Exception("Please enter all fields");
}
$user->email = $data->email;
$user->password = $data->password;
if ($user->login()) {
// Create token
$key = 'ajdZiWodDaAs1123';
$iat = time();
$payload = [
'iss' => 'localhost',
'aud' => 'localhost',
'iat' => $iat,
'nbf' => $iat,
'exp' => $iat + 259200000, // 3 days
'data' => [
"id" => $user->id
]
];
$token = JWT::encode($payload, $key, 'HS256');
echo json_encode(
array(
"id" => $user->id,
"full_name" => $user->fname ." ".$user->lname,
"email" => $user->email,
"token" => $token
)
);
} else {
throw new Exception("Invalid credentials");
}
} catch (Exception $e) {
http_response_code(400);
echo json_encode(
array('message' => $e->getMessage())
);
}
?>
axios
import axios from 'axios';
const base_url = 'http://localhost/classroom-api';
const route = '/api/user';
export const login = async (userData) => {
const res = await axios.post(base_url + route + '/login.php', userData);
console.log(res);
};
although it does work in postman
Browsers will first send an OPTIONS request to check for CORS headers.
Add this right after the headers:
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS')
exit('ok');

How to send a response in PHP to a request made through the javascript fetch API?

I have an application in PHP, which receives data from the client that is in another domain. Data arrives from the fetch API via the POST method, but PHP doesn't send a response to the fetch API.
foo.com/endpoint.php:
<?php
include_once('database/connection.php');
header('Content-Type: application/json');
$ip = $_POST["ip"];
$city = $_POST["city"];
$state = $_POST["state"];
$country = $_POST["country"];
$category = $_POST["category"];
// Checking if the req ip already have registered other req
$ip_query = "SELECT * FROM registers WHERE `ip` = '$ip'";
$ip_result = mysqli_query($conn, $ip_query);
$ip_check = mysqli_fetch_assoc($ip_result);
if (!$ip_check) {
// registering data after validation
$new_query = "INSERT INTO `registers` (`ip`, `city`, `state`, `country`, `category`, `created`) VALUES ('$ip', '$city', '$state', '$country', '$category', '2022-07-21 00:00:01')";
$new_create = mysqli_query($conn, $new_query);
$result = array(
'ok' => true,
'status' => 200
);
// sending response
http_response_code(200);
echo json_encode($result);
} else {
// sending response if already registered
http_response_code(503);
}
Client side fetch code:
fetch(this.url, {
method: 'POST',
mode: 'no-cors',
body: this.getFormValues(),
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
}
})
.then(resp => resp.json())
.then(data => {
console.log(data)
if (data.ok) {
this.Metrics.setSent()
} else {
throw Error(r.statusText)
}
})
.then(() => {
this.Metrics.setSent()
this.Metrics.dismiss()
})
.catch(erro => {
console.log("Erro: ",erro)
this.Metrics.dismiss()
});
It's all right about storing data, my problem is just sending the response :(
PHP does not parse the POST body into JSON automatically. To fix this, you have to add json_decode() to your code like this:
$ip = json_decode($_POST, true)["ip"];
I hadn't noticed that when making a request using the "no-cors" mode i'd get an opaque response.
I just added the code below to the beginning of my PHP file, changed the fetch mode to "cors" and everything worked as it was supposed to work:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header("Access-Control-Allow-Credentials: true");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization") ;
header("HTTP/1.1 200 OK");
die();
}
I made the adaptations suggested by #brrrrrrr and updated the queries to prevent SQL injections.
Thx everyone.

Decompress GZIP string response from a PHP server in NodeJS

I have an existing PHP code that is doing a curl request to a 3rd-party PHP server.
The 3rd-party server returns a GZIP string.
In PHP, I can use gzdecode to decode the gzip string.
How can I do it in NodeJS/Javascript? I tried using decompress-response with no avail.
Also tried using got instead of request, enabled auto-decompress, also doesn't work.
Edit: Also tried zlib and pako, also doesn't work.
Sample Code [ PHP ]
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 3000000,
CURLOPT_ENCODING => '',
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo false;
} else {
$response = gzdecode($response);
echo $response;
}
This is the solution that works for me.
I used got instead of axios because I can't get it to work there.
I set my request options:
const requestOptions = {
encoding: null, // this is important
headers: {
"Accept-Encoding": "gzip",
}
...
};
Don't forget that encoding: null line, because without that, the response will be automatically converted to a string. ( We need a buffer to make this work )
Then I created a function like this to handle my request:
const zlib = require("zlib");
async function performRequest(url, options) {
try {
const response = await got(url, options);
if (response.headers["content-encoding"] === "gzip") {
const body = response.body;
try {
const dezziped = zlib.gunzipSync(response.body);
response.body = JSON.parse(dezziped.toString());
} catch (error) {
response.body = body;
}
}
return response.body;
} catch (error) {
return error;
}
}
Note: This is a synchronous operation, you can use gunzip instead if you want to do the async way.

I am not able to see push notifications in notification bar/panel I am using phonegap-plugin-push

I am not able to see push notifications in notification bar/panel I am using https://github.com/phonegap/phonegap-plugin-push .However, I am receiving the messages sent from my php server (its showing in the alert).Can anyone please tell me why do not I see the notifications in the notification bar in android?
Here is my java script code in the index.html.
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
var push = PushNotification.init({
"android": {
"senderID": "111111111111"
},
"ios": {},
"windows": {}
});
push.on('registration', function(data) {
//alert("registration event");
//document.getElementById("regId").innerHTML = data.registrationId;
//alert(data.registrationId);
//console.log(JSON.stringify(data));
var url = 'http://mywebsite.com/reest/rest2.php?id='+data.registrationId;
// alert(url);
$.post( url, function( data ) {
//alert( "Data Loaded: " + data );
});
});
push.on('notification', function(data) {
alert("notification event");
alert(JSON.stringify(data));
var cards = document.getElementById("cards");
var push = '<div class="row">' +
'<div class="col s12 m6">' +
' <div class="card darken-1">' +
' <div class="card-content black-text">' +
' <span class="card-title black-text">' + data.title + '</span>' +
' <p>' + data.message + '</p>' +
' </div>' +
' </div>' +
' </div>' +
'</div>';
cards.innerHTML += push;
});
push.on('error', function(e) {
console.log("push error");
});
}
};
app.initialize();
And here below is my php code to send the gcm message from the my server
<?php
//------------------------------
// Payload data you want to send
// to Android device (will be
// accessible via intent extras)
//------------------------------
$data = array( message => 'Hello World! i am app',title => 'Large Icon');
//------------------------------
// The recipient registration IDs
// that will receive the push
// (Should be stored in your DB)
//
// Read about it here:
// http://developer.android.com/google/gcm/
//------------------------------
$ids = array( $_GET['id'] );//array( 'abc', 'def' );
//------------------------------
// Call our custom GCM function
//------------------------------
sendGoogleCloudMessage( $data, $ids );
//------------------------------
// Define custom GCM function
//------------------------------
function sendGoogleCloudMessage( $data, $ids )
{
//------------------------------
// Replace with real GCM API
// key from Google APIs Console
//
// https://code.google.com/apis/console/
//------------------------------
$apiKey = 'apikeyhere';
//------------------------------
// Define URL to GCM endpoint
//------------------------------
$url = 'https://android.googleapis.com/gcm/send';
//------------------------------
// Set GCM post variables
// (Device IDs and push payload)
//------------------------------
$post = array(
'registration_ids' => $ids,
'data' => $data,
);
//------------------------------
// Set CURL request headers
// (Authentication and type)
//------------------------------
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
//------------------------------
// Initialize curl handle
//------------------------------
$ch = curl_init();
//------------------------------
// Set URL to GCM endpoint
//------------------------------
curl_setopt( $ch, CURLOPT_URL, $url );
//------------------------------
// Set request method to POST
//------------------------------
curl_setopt( $ch, CURLOPT_POST, true );
//------------------------------
// Set our custom headers
//------------------------------
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
//------------------------------
// Get the response back as
// string instead of printing it
//------------------------------
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
//------------------------------
// Set post data as JSON
//------------------------------
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );
//------------------------------
// Actually send the push!
//------------------------------
$result = curl_exec( $ch );
//------------------------------
// Error? Display it!
//------------------------------
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
//------------------------------
// Close curl handle
//------------------------------
curl_close( $ch );
//------------------------------
// Debug GCM response
//------------------------------
echo $result;
}

meteor http post to other domain

So I want to use an sms service from 46elks in my meteor project. The following php script allows you to send an sms:
<?
// Example to send SMS using the 46elks service
// Change $username, $password and the mobile number to send to
function sendSMS ($sms) {
// Set your 46elks API username and API password here
// You can find them at https://dashboard.46elks.com/
$username = 'u2c11ef65b429a8e16ccb1f960d02c734';
$password = 'C0ACCEEC0FAFE879189DD5D57F6EC348';
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Basic ".
base64_encode($username.':'.$password). "\r\n".
"Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($sms),
'timeout' => 10
)));
return false !== file_get_contents(
'https://api.46elks.com/a1/SMS', false, $context );
}
$sms = array(
'from' => 'DummyFrom', /* Can be up to 11 alphanumeric characters */
'to' => '+46400000000', /* The mobile number you want to send to */
'message' => 'Hello hello!'
);
sendSMS ($sms);
?>
Now I need this in my meteor project and I've been trying to convert it to meteors http.call():
HTTP.call("POST", "https://api.46elks.com/a1/SMS", {
headers:
{
"Authorization": "Basic SomeLongBase46EncodedString",
"Content-type": "application/x-www-form-urlencoded"
},
data:
{
"from": "testFrom",
"to": "+46701111111",
"message": "test message"
}
},
function (error, result)
{
if (error)
{
console.log("error: " + error);
}
else
{
console.log("result: " + result);
}
});
But what I keep getting is the following error:
error: Error: failed [403] Missing key from
Change data to params:
params: {
"from": "testFrom",
"to": "+46701111111",
"message": "test message"
}
and use auth instead of Authorization (docs):
"auth": username + ":" + password
ok, I had to replace data: { ... } with the following formatted string:
content: "from=testFrom&to=+46701111111&message=test message"
This to convert the php http_build_query() correctly.

Categories