jQuery $.ajax() with PHP - php

I'm trying to use jQuery $.ajax() but I'm facing some difficulties.
Here's the textbox field that I want to use for POST:
<input name="url" class="url" type="text" >
Here's the code:
$.ajax({
type: "post",
url: "file.php",
data: $(this).serialize(),
success: function(data) { ...............
Now this is the file.php:
<?php
if( $_REQUEST['url'] )
{
$url = $_REQUEST['url'];
$url = file_get_contents($url);
// I would need now to return something here but not sure how??!!
}
?>
Now, my question is, how to return variables in this PHP code and use them in my code above, I mean in the success part of $.ajax(). Also if I want to perform some additional stuff on the $url variable, how to do it? How to return them? :/

If you want to return some variables/fields, the best way would be to echo a JSON string. Here is a small example:
PHP Code:
<?php
if( $_REQUEST['url'] )
{
$url = $_REQUEST['url'];
$url = file_get_contents($url);
$result['var1'] = 'something';
$result['var2'] = 500;
echo json_encode($result);
}
?>
JS Code:
$.ajax({
type: "post",
url: "file.php",
data: $(this).serialize(),
dataType: 'json', // maybe not needed? I do not know if jQuery autodetects it
success: function(data) {
// here you can use data.var1 and data.var2 to read the fields
}
});

You just print/echo your 'return' value.
file.php
<?php
if( $_REQUEST['url'] )
{
$url = $_REQUEST['url'];
$url = file_get_contents($url);
// I would need now to return something here but not sure how??!!
echo "something";
}
?>
Then in your JS:
$.ajax({
type: "post",
url: "file.php",
data: $(this).serialize(),
success: function(data) {
console.log(data); // "something"
}
});
As a side note. Your script looks like it accepts any URL and fetches it. It is possible to abuse scripts like that. Make sure you are aware that.

Related

PHP cannot pass two parameter to another php using ajax

I need to call php and get data from another server and I am using proxy.php to call from ajax.
proxy.php
<?
header('Content-type: application/json');
$url=$_GET['url'];
$json=file_get_contents($url);
echo $json;
?>
And my code looks
function scanFunction(){
var url="http://address/scan.php?user=user1&video=video1";
console.log(url);
url = 'proxy.php?url='+url;
$.ajax({
url: url,
type: "POST",
data: {
},
dataType: "JSON",
success: function (jsonStr) {
if(jsonStr.length>0){
var obj = jsonStr;
console.log(obj);
}
else{
console.log(" error...");
}
}
});
}
And this code works fine when I use one parameter to the url passing to proxy.php where as second argument missing
That is
echo $url; inside proxy.php print
http://address/scan.php?user=user1
event I pass two argument like,
proxy.php?url="http://address/scan.php?user=user1&video=video1"
That is second argument video missing inside proxy.php and so I am not getting expected result.
You may be having issues with your GET variables in the GET['url'] variable.
Try encoding your url when you send it to proxy.php to avoid such issues.
var url = encodeURIComponent("http://address/scan.php?user=user1&video=video1");
url = 'proxy.php?url='+url;
Then on the PHP side you need to decode it.
$url=$_GET['url'];
if (is_string($url)) {
$url = urldecode($url);
}
proxy.php cannot know which arguments are meant for it, and which are meant for scan.php. Eg, When you call url:
proxy.php?url=http://address/scan.php?user=user1&video=video1
Your proxy scripts thinks that the query parameters are:
url:"http://address/scan.php?user=user1"
video:"video1"
But your intent was for everything after url to be one parameter. A better approach is to use POST parameters instead of URL query parameters.
$.ajax({
url: url,
type: "POST",
data: {
resource_url: "http://address/scan.php?user=user1&video=video1"
},
....
});
Now, in proxy.php:
<?php
header('Content-type: application/json');
$url=$_POST['resource_url'];
$json=file_get_contents($url);
echo $json;
?>
Use the data: property of the ajax call to pass as much or as many parameters as you like
function scanFunction(){
$.ajax({
url: 'proxy.php',
type: 'POST',
data: {
url: 'http://address/scan.php',
user: 'user1',
video: 'video1'
},
dataType: "JSON",
success: function (jsonStr) {
if(jsonStr.length>0){
var obj = jsonStr;
console.log(obj);
} else {
console.log(" error...");
}
}
});
}
Then build whatever you want from those parameters in the php script
Oh and you used type: 'POST' in your javascript, so you should be using the $_POST array in your PHP script.
proxy.php
<?php
$url = $_POST['url'] . '?user=' . $_POST['user'] . '&video=' . $_POST['video'];
$json=file_get_contents($url);
header('Content-type: application/json');
echo $json;
?>

Pass angularjs value to PHP variable

I am starting with angularjs with ngStorage. I can save and display data successfully.
I display value as before
{{myobj.session}}
I would like to pass whatever stored value into php variable. Shown below is my imaginary logic and I know thats not gonna work. My question is how to assign such value into PHP variable in a correct manner?
<?php
$name = {{myobj.session}}
?>
You can use this angular variable: students.tiffen_type
PHP variable : $value
<?php
$value = "{{ students.tiffen_type }}";
?>
You can do a ajax request like this:
$http({
url: "urltopost.php",
method: "POST",
data: {
data: variable
}
}).success(function(response) {
console.log(response);
});
And on the backend you can get the variable like this
<?php
$request = json_decode( file_get_contents('php://input') );
$variable = $request->data
From there you can do everything you want with that variable, still I'm not sure what are you trying to achieve.
You can't assign directly angularjs value to php variable, use the following method it will help you
$http({
method: "POST",
url: "test.php",
data: {
data: postvariable
}
}).success(function(response) {
console.log(response); //get the echo value from php page
}).error(function(response) {
console.log(response);
});
test.php
<?php
$data = json_decode(file_get_contents("php://input"));
echo $data->data;
?>
send.js
$http({
method: "post",
url: "ajax/request.php",
data: {
angular_var: $scope.angular_var // $scope.angular_var is angular variable e.g. ng-model="angular_var"
}, headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
console.log(data)
});
ajax/request.php
$request_arr = json_decode( file_get_contents('php://input') );
$angular_var = $request_arr->angular_var;

How to send json to php via ajax?

I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/

Take html and variable with AJAX

I have this ajax code
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(html)
{
LastDiv.after(html);
}
});
I am new with this Ajax thing.
This code is to load getData.php file and send variables through type POST.
The variables are in this var ValueToPass = "lastid="+LastId+"&br="+br;.
Other thing this code does is return the getData.php's HTML after loading.
Probably with this. success: function(html)
How can I return this $br variable from getData.php after loading, so I can use it again through the next cycle. Cuz what happens here is that I can put the variable in the getData.php with the Ajax and working with it, but when the file getData.php is loaded, outside this file, the variable is not known(not declared). And I'm losing the counting :S
I want to return the HTML and the variable.
You can return json data in your php file like
$response = array ('br'=> $br, 'html'=> $html);
echo json_encode($response);
Here both html and data are returned.
And this to use it in your ajax callback :
success: function(data)
{
br = data.br;
LastDiv.after(data.html);
}
I'd consider setting a Session variable with the value from the $br variable passed via AJAX. Then when you call getData.php from another file or location, you can use the Session variable since session variables retain their value anywhere in the session.
You can try this to get the data from your `getData.php' :
$.ajax(
{
type: "POST",
url: "getData.php",
data: { ValueToPass: ValueToPass},
cache: false,
success: function(data)
{
LastDiv.html(data);
}
});
and in your getData.php you have to pass ValueToPass
maybe like this:
$ValueToPass = mysqli_real_escape_string($db, $_POST['ValueToPass']);
If I understand your question correctly, and if you want to return the $br variable then include it in a JSON object in the successs callback function. So, something like this (I'm not familiar enough with PHP so my PHP syntax might be incorrect):
// create JSON object
<?php
$result = array('br' => $br, 'html' => 'htmlContent);
echo json_encode($result);
?>
// return JSON object
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(result)
{
var $br = result.br;
LastDiv.after(result.html);
}
});

Posting data to php file

I have the following variable in Javascript. I want to know how to pass this data to a PHP so that I can display the contents of the data once redirected.
postData = {
'dates_ranges': datesAndRanges,
'action':'build',
'output_type': output_type,
'form_html': formHtml,
'width': formBuilder.width(),
'rules':validationRules,
'theme': theme,
};
Use JQuery post method to pass data to PHP file:
$.post("/path/to/script.php", postData, function(result) {
// work with result
});
In PHP use $_POST global to get the variables:
print $_POST['dates_ranges'];
print $_POST['action'];
// ...
using jquery it goes easy & clean like this:
$.post('script.php', postData, function(response){
// process/display the server response
});
you can use:
$.post("YOUR_URL", postData, function(response) {
// handle with response
});
OR:
$.ajax({
url: YOUR_URL,
data: postData,
type: 'post',
success: function(response) {
// handle with response
}
});
And In your PHP file:
if(isset($_POST) && !empty($_POST)) {
$d = $_POST;
echo $d['date_range']; // and so more
}

Categories