I getting data from a Webpage and it have a jQuery Ajax Request. its Method is GET and it have some data, i wanna know how i can send request with cURL-php.
i did run a curl session and send data with curl_setopt($ch,CURLOPT_POSTFIELDS,$datas)
but it didn't respond.
// $.ajax({type: 'GET', dataType: 'json', url : 'http://example.com/some', data: $('#media_form').serialize()})
// $('#media_form').serialize() = string=string&link=https%3A%2F%2Fexample.com
actually i put #media_form data in an array into postfields in cURL, but in fact i even dont know how should i send request. how should i send data in GET without any Attribute ?
GET parameters are put in the URL, not the POST fields.
So it should be:
$url = 'http://example.com/some?string=string&link=https%3A%2F%2Fexample.com';
You can use the http_build_str() function to construct the query string from an associative array of parameters.
Related
I have an Ajax call:
let jFormData = JSON.stringify(formData);
// {"list":["17810","17811","17812"],"chosen":"17812"}
$('#json').val(jFormData);
$.ajax({
url : 'db_ajax/regDupAjax.php',
type : 'POST',
data : jFormData, // our data object
dataType : 'json',
})
The JSON has been validated.
It is being sent to a php script and being read by
$json = $_POST['jFormData'];
but $json is an empty string.
What have I overlooked? I have tried dataType text, and have reviewed all the suggested similar questions without success.
The parameter data in ajax request wait for object. If you want pass json string to jFormData key in $_POST you must pass it as new object:
$.ajax({
url : 'db_ajax/regDupAjax.php',
type : 'POST',
data : { jFormData: jFormData }, // our data object
dataType : 'json',
})
Using the browser's developer console, you can track ajax post from the network section and check the sent values. You will be sure whether the values are sent correctly or if the post operation is successful.
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);
I've been debugging this for hours. Tried to set the header etc but no luck!
My controller
$http({
url: 'http://myphp.php/api.php',
method: "POST",
data: {'wtf':'test'}
})
.then(function(response) {
console.log(response);
},
function(response) { // optional
// failed
}
);
and my php
<?php
echo "test";
echo $_POST["wtf"];
?>
In my network tab this is how it look like
Not sure what's wrong man, really exhausted, I'm stuck for hours! Why my $_POST['wtf] didn't echo?
$http is serializing the data to JSON in the request body but PHP's $_POST is looking for key/values parsed from posted form data. These are two different mechanisms for posting data so you need to choose one and use that mechanism on both sides.
You have two options to solve this:
In your PHP code, parse the request body as JSON data and then use that object to retrieve your data. See this StackOverflow question for more information.
Modify your $http request to post the data as form data. See this StackOverflow question for more information.
$http.post (by default) does not send the data as key/value pairs. It sends it as post request.
Therefore, in your php script you should consume it like this:
$input = file_get_contents('php://input');
And then parse it like this:
$data = json_decode($input, true);
Im not quite sure how to explain this but im experimenting with creating my own API. At the moment things are working quite well by doing cURL requests or jQuery AJAX requests.
My problem is I see using other APIs that you specify you want a JSON response in the arguments root of the jQuery object. With my API I have to specify I want a JSON response in the data argument. How exactly are APIs picking up this JSON argument? Example:
$.ajax({
url: 'url',
type: 'POST',
data: {dataType : 'json'}, //I need this for PHP to know I want a JSON response
dataType: 'json' //how do other APIs grab this on the API side?
}).
done(function(response){
console.log(response);
});
In PHP I can only pickup the data object VIA $_POST. If I remove the data object from the AJAX request I dont get data back. So what should I do in PHP to pickup the "root" dataType argument to know to return JSON?
<?php echo serialize($_POST) ?>
When you set dataType, jQuery sends that info as part of the Accept header, it probably looks something like this: Accept: application/json, text/javascript, */*; q=0.01.
On the PHP side of things, you can access it with the $_SERVER superglobal:
$accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null;
if ($accept && false !== stripos($accept, 'application/json')) {
// send back JSON
}
If you happen to be using Symfony's HttpFoundation component, it has some nice facilities to deal with Accept headers:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\AcceptHeader;
$r = Request::createFromGlobals();
$accept = AcceptHeader::fromString($r->headers->get('Accept') ?: '*/*');
if ($accept->has('application/json')) {
// send json
} elseif ($accept->has('application/xml')) {
// send xml
} else {
// send whatever
}
I'm trying to make an ajax request in straight javascript (jQuery is not available to me) with some JSON parameters.
The javascript:
var params = {'ajax': true, 'albumid': albumid, 'sequencenum': sequencenum};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
}
}
xhr.open("GET","viewpicture.php",true);
xhr.setRequestHeader("Content-Type", "application/json")
console.log("sending request");
xhr.send(JSON.stringify(params));
In viewpicture.php, a var_dump($_GET) yields an empty array. What am I doing wrong?
In short, when you make a GET request, .send is expected to have 0 params (or be null).
The only way to send the data through GET would be to append it to the URL itself.
To wit:
If you were sending in form-data, in a POST, the anticipation would be that send would contain the form-encoded data (json for json-data, etc), and the URL would just be the access point on the server.
A GET request is just fetching data from that access point (including query string).
See where I'm going with this?
So if you want this to work in a GET, you need to set your JSON as a property of a query parameter (or turn it into query params/values).
If you want to send in the request body you should use a POST request, however if you need to use a get request you should send the data as key value pairs in the url. e.g. xhr.open("GET","viewpicture.php?data=" + encodeURIComponent(JSON.stringify(params)),true); Then retrieve via $_GET['data'].