PHP Curl and json post error false - php

I'm a newbie when it comes to using PHP curl and ajax
I've been asked to do the following (an image is attached for your consideration).. there are the requirements
initially I tried sending request with jquery ajax but it was not working here is the code:
function sendAPI(){
$.ajax({
url: "https://someurl.com/api/page/index",
headers: {
'x-api-key':"[API KEY GIVEN BY THE COMPANY]",
'Content-Type':'application/json'
},
method: 'POST',
dataType: 'jsonp',
data: {
id: "7001345730",
recordNo: "1000000000",
recordDate: "2017-12-12",
phone: "+966555555555",
extension: "1234",
email: "feras#test.com",
managerName: "Amjad",
managerPhone: "+966555555555",
managerMobile: "+966555555555"
},
success: function(data){
console.log('lllk');
console.log('succes: ' + data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("textStatus: ", textStatus);
console.log("errorThrown: ", errorThrown);
}
});
}
sendAPI();
I get the following error message displayed on my console
Please note: I tried both json and jsonp dataType but same result
textStatus: error
errorThrown: error
Afterwards I tried php curl but I am getting the error on that too.
here is php curl code:
$id ="7001345730";
$recordNo = "1000000000" ;
$recordIssueDate = "2017-12-12" ;
$phone = "+966555555555" ;
$extension = "1234" ;
$email = "feras#test.com" ;
$managerName = "Adeel Essa" ;
$managerPhone = "+966555555555" ;
$managerMobile = "+966555555555";
$data = array(
"id" => $id,
"recordNo" => $recordNo,
"recordIssueDate" => $recordIssueDate,
"phone" => $phone,
"extension" => $extension,
"email" => $email,
"managerName" => $managerName,
"managerPhone" => $managerPhone,
"managerMobile" => $managerMobile,
);
$ch = curl_init('https://someurl.com/api/page/index');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"x-api-key: 56DAAC8KAD-SFOL9267B-B97E1A9E"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch); //get return String
echo json_encode($result);
if (curl_error($ch)) {
$error_msg = curl_error($ch);
}
curl_close($ch);
if (isset($error_msg)) {
print_r($error_msg);
}
When I execute the above code I get the following error:
false
Failed to connect to wasl.elm.sa port 443: Timed out
In the end my only question is:
If I am doing right or there is something is missing in my code.
On both JQuery and PHP CURL codes.
If so what do I need to change.
Requirements are also mentioned in the above image
Please Help

Related

How to handle error from php handler file

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"}';
}

can not get cUrl response to .ajax() for redirect

I have a php cURL request which is run when .ajax() is run on form submit:
// A sample PHP Script to POST data using cURL
$headers = array(
'Access-Control-Allow-Headers: Authorization',
'x-api-key: xxxxx',
'Content-Type: application/json',
);
$post_data = '{
"user_email": "'.stripslashes($_POST['email']).'",
"user_firstname": "'.stripslashes($_POST['personName']).'",
}';
// Prepare new cURL resource
$crl = curl_init('https://api.examplesite.com/api/site');
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLINFO_HEADER_OUT, true);
curl_setopt($crl, CURLOPT_POST, true);
curl_setopt($crl, CURLOPT_POSTFIELDS, $post_data);
// Set HTTP Header for POST request
curl_setopt($crl, CURLOPT_HTTPHEADER, $headers);
// Submit the POST request
$result = curl_exec($crl);
if(curl_exec($crl) === false) {
echo 'Curl error: ' . curl_error($crl);
} else {
$output = json_decode($result, true);
echo json_encode($output);
}
// close the request
curl_close($crl);
And here's the .ajax() post:
$.ajax({
type: "POST",
url: location.href,
dataType: "json",
data: {
ajaxRequest: 1,
sendDemoEmail: sendDemoEmail,
email: email.val(),
personName: name.length != 0 ? name.val() : 'no_name',
},
success: function (data) { // CANT RETRIEVE SUCCESS
console.log('yes result', data);
$('#result').html(data);
},
error: function (data) { // RUNS ERROR
console.log('no result', data);
$('#result').html(data); // EMPTY
},
The result from cUrl is as follows:
{"errors":[],"messages":[],"site_url":"https:\/\/www.site.com\/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ2ZXJpZmljYXRpb25fY29kZSI6IiQyeSQxMCQzWXQwWlE1d0FGd0ZWaHNFdnZwdm0uQnl4WVNyS29EejlKVTZEQ0xzNnBtUFd1VFA2MFwvSE8iLCJuZXdfdHJpYWxfZ"}
User flow:
submit form with email with .ajax() POST
send data with cUrl to API
retrieve data from API response in cUrl json_decode
use the cUrl API response in my .ajax() POST to redirect to the site_url in the reponse.
I am unable to get a success from the .ajax() POST (it return error) and also unable to also access the site_url in the .ajax() for a redirect after a success. What am I doing wrong here?
Needed to add a exit(); to the PHP cUrl after the curl_close so my JSON response would not include site HTML
// close the request
curl_close($crl);
exit();

Send JSON by cURL always returns "No access"

I have this JSON data:
$.ajax({
type: "GET",
url: "http://www.example.com/test.php",
data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
});
To send this data to http://www.example.com/test.php, I have tried with this code:
<?php
//API URL
$url = 'http://www.example.com/test.php';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'data' => 'code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
?>
But, it always retuns No access.
What are wrong in my code? Can you help me to fix it?
Sorry about my English, it is not good. If my my question is not clear, please comment below this question.
First check http://www.example.com/test.php
Ajax system can't be used with full domain name.
so you should use /test.php
Then checking for an error that occurs in your site or target site.
Then the code becomes:
$.ajax({
type: "GET",
url: "/test.php",
data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
success: function(data, textStatus) {
alert(data);
data = $.parseJSON(data);
},
error : function(data, textStatus, error){
alert(data + " : "+ textStatus);
}
});
Without the documentation to look out the only thing I can suggest is to remove the data from the array and just make it key code.
<?php
//API URL
$url = 'http://www.example.com/test.php';
$data = "?code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b"
//Initiate cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Execute the request
$result = curl_exec($ch);
?>

AJAX not posting data to PHP in IE only

So I have an AJAX call that I'm using to POST 1 variable to a PHP script I have on a separate server. The PHP takes this variable and returns data based off of what the variable is. This works on all browsers except IE9 and below. IE9 returns data but it's an error saying the variable is missing which to me shows that it isn't sending the data. Below I have the AJAX call I'm making:
(function (jQ) {
var inviteID = '00000000000';
jQ.ajax({
url: 'www.example.com/test.php',
type: 'POST',
dataType: 'json',
cache: false,
data: { classID: inviteID },
error: function (data, status, error) {
jQ('.statusField').append('Failure: ' + data + status + error);
},
success: function (data, status, error) {
jQ('.statusField').append('Success: ' + data);
}
});
})(jQuery);
And below I have the PHP script that's being used:
<?php
//first POST to grab token
function runPost($classID) {
$postdata = array(
'username' => 'username',
'password' => 'password'
);
//open connection
$ch = curl_init();
//set the url, POST data
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/login");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
curl_setopt($ch, CURLOPT_USERAGENT, 'example');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
list($message, $time, $token, $userID) = split(',', $result);
list($one, $two, $three, $four, $five) = split('\"', $token);
$four = json_encode($four);
$four = str_replace('"','',$four);
$secondaryPostData = array(
'token' => $four,
'data' => array( 'invitationID' => $classID
));
//open connection
$chu = curl_init();
//set the url, POST data
curl_setopt($chu, CURLOPT_URL, "https://www.example.com/classID");
curl_setopt($chu, CURLOPT_POST, 1);
curl_setopt($chu, CURLOPT_POSTFIELDS, json_encode($secondaryPostData));
curl_setopt($chu, CURLOPT_USERAGENT, 'example');
curl_setopt($chu, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($chu, CURLOPT_RETURNTRANSFER, 1);
//execute post
$secondResult = curl_exec($chu);
//close connection
curl_close($chu);
return json_encode($secondResult);
}
//Grab classID from javascript
echo runPost(trim($_POST['classID']));
?>
Again, this works fine in everything except IE. I've tried several different methods but everything gives me the same error. The network console in IE shows that the Request body does have the classID in it, but I'm guessing it's just not sending the data to the PHP script. I don't know if I'm missing something that IE needs to send this to the PHP script but any help with this would be GREATLY appreciated.
Have you tried using this ?
$("button").click(function(){
$.post("demo_test.php",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
works for me in chrome and IE.
$.post() is a short hand method for $.ajax();
It does every thing you could do in $.ajax(); when I started having this problem I never used $.ajax(); unless I had to send FormData an entire object off all the field inputs in a form

Why is this returning unidentified even when I manually assign it for testing?

This always throws the error that none of those params are valid. For example: Undefined index: dataNL
Receiving Code:
$ajax_arrayBTF = $_POST['dataBTF'];
$ajax_arrayLI = $_POST['dataLI'];
$ajax_arrayLS = $_POST['dataLS'];
$ajax_arrayNL = $_POST['dataNL'];
$agent_id = $_POST['agent'];
Here is the calling code I am using:
$data = array(
"dataBTF" => "0",
"dataNL" => "0",
"dataLS" => "0",
"dataLI" => "0",
"agent" => "53"
);
$data_string = json_encode($data);
echo $data_string;
$ch = curl_init('http://localhost/site1/backend/scripts/oppCAL.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
echo curl_exec($ch);
I don't get why this is happening, because I am MANUALLY assigning it. So it is valid. echo $data_string; displays
{"dataBTF":"0","dataNL":"0","dataLS":"0","dataLI":"0","agent":"53"}
Just like it should.. I decided to go with JSON, but even that is not working. CURL is enabled. What am I missing here?
EDIT:
When ajax was calling there was no issue. My ajax was:
$.ajax(
{
type: 'post',
url: 'scripts/oppCAL.php',
data:
{
dataBTF: $array_jsBTF,
dataLI: $array_jsLI,
dataLS: $array_jsLS,
dataNL: $array_jsNL,
agent: $agent_id
},
success: function(e)
{
console.log("done:");
} //success
}); // ajax
PHP doesn't parse JSON body data, only form encoded, like your jQuery ajax call sends. It looks something like this:
dataBTF=0&dataLI=0&dataLS=0&dataNL=0&agent=0
When receiving JSON, you can use something like this to get the data:
$body = file_get_contents('php://input');
$data = json_decode($body, true);

Categories