JavaScript variable when sending data via jQuery $.post() function - php

I have a problem when I want to send input data via jQuery's $.post. I have this input:
<input id="mydata" value='<?php echo $data; ?>' >
and I want to send its data via jQuery's $.post() function.
This $.post function runs, but it does't send anything:
var the_data = $('#mydata').val();
//alert(the_data); has correct data!!
$.post("http://php/server", the_data , function(data){
alert(data);
}, "html");
But this one sends data correctly:
$.post("http://php/server", <?php echo $data; ?> , function(data){}, "html");
I should use input for saving data and method 2 isn't suitable for me.

The data needs to be an object.
var the_data = {
mydata: $('#mydata').val()
};
You can access this in your PHP with $_POST['mydata'].

Related

How to return values from a function and send to AJAX using jquery?

When i click the button,am calling a function it will return some values.I need to get those values and send through AJAX using Jquery.
Give below the click button function.Inside this function am calling another function(here returning values i need to pass through ajax)
The problem is i cant able to send those values inside ajax.
Can anyone plz help me to do this?I dont know where am doing mistakes.
Here is the function am calling inside button click
in this eaxample i have send with the ajax request the name of the function that i want to use
let fd = new FormData();
fd.append('function_name', 'activity_submitted');
$.ajax({
url: "activity_submitted.php",
type: "POST",
data: fd,
complete: function (results) {
try {
var str = JSON.parse(results.responseText);
}
catch (e) {
}});
in the PHP file (according to the $_REQUETS['function_name']) go to your function, the function will echo a JSON with the values that you want to send back
$_REQUEST is a super global variable which is widely used to collect data after submitting html forms.
function activity_submitted() {
.
.
.
$res = array('articleid'=>$articleid);
$resBack = (json_encode($res, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
echo ($resBack);
}
?>

PHP capture data and join together

Okay so I need to parse two parts. Here is the code im trying to parse.
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
I would like it to parse and output like this once done.
10528935=12-1-D33D19A3F048E845A9AA885220729B98
Here is the site I'm trying to do this for
https://www.payqwiq.com/login?uid=582063bd-1973-42e4-8235-b28f5addf8bf
All I need is that data to be parsed and joined like above so I can continue with my program :)
Would appreciate some help if possible :)
I'm completely new in PHP.
Php is a back-end language. Since you are attempting to get data stored in a document object on the front-end, you should use a front-end language to parse the document object, then send the data to a php handler to do what you want with it on the back-end.
Using jQuery you can achieve the desired output with one line of code, then build an ajax call to send the output data to the desired php handler.
// when document is loaded
$(document).ready(function() {
// get data from document object to send to php handler
var combinedData = $('input').attr('name') + '=' + $('input').val();
// execute ajax method to send data to php handler
sendData(combinedData);
});
function sendData(data) {
// ajax method to send data to php handler
$.ajax({
url: 'pageToSendTo.php',
type: 'POST',
data: {
"data": JSON.stringify(data)
},
dataType: 'JSON',
success: function(data) {
console.log(data);
},
error: function(xhr) {
console.log('error: ' + xhr.responseText);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
<!-- this is the "pageToSendTo.php" php handler. -->
<?php
if ($_POST['data']) {
//echo 'received data!';
$data = json_decode($_POST['data']);
// do stuff with data
print_r(json_encode($data));
}
?>

jsonp, jQuery & PHP to make cross-domain ajax call

http://serverA.com/list.php:
html:
<form id="myform">
<input id="inputfield" name="view">
</form>
js:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: inputdata,
dataType: 'jsonp'
});
});
http://serverB.com/detail.php
php:
<?php
$view = $_GET['callback'].'('.json_encode(name) .')';
?>
html:
<h4><?php echo $view; ?></h4>
what the code does is:
from serverA, assign a value "ocean-view" to an input field, submit this form to serverB, and display this value in a h4 tag.
I couldn't quite figure out how to write the server-side code to output the value, even though I have found the following posts.
this and this.
Any kind of help is appreciated.
UPDATE:
I used YQL to help to see the jsonp callback response, here is the json structure:
callback({
"query": {
"count": 1,
"created": "2013-07-29T13:01:12Z",
"lang": "en-US",
"results": {
"h3": {
"class": "mytitle",
"content": "Example"
}
}
}
});
Actually You are very close to success... just read these points.
Whenever you are making an ajax request the browser sends a hit on ajax URL with respected parameters and details. On respected URL PHP code executes. It can return data in some format. It can not return data in directly PHP variable.
Formats are:
text/html
json
xml
......
Mainly for cross domain requests we use JSONP.
And it means PHP script will return data in JSON.
So you will just echo your json_encode in directly script. That will be the response of your ajax request.
Now when you have got the data in ajax function, then jQuery uses success: function(response){ } where you response will come.
So variable response will contain JSON.
You can access JSON and put data in any tag by using jQuery selector.
$().html(response.);
These thing can be analyzed in any browser in debug console. That what is requested and what is returned.
even you can use Firebug in Mozilla to inspect ajax request.
So you will do three changes.
In Ajax function write a success function:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: "inputdata="+inputdata,
dataType: 'jsonp',
success:function(response){
// response will be json type so access it
// print ur json in html tag like resposne is {"data":23}
$(<jquery selector>).html(reponse.data);
}
});
});
<?php
// echo this
$inputdata = $_GET['inputdata'];
// perform you logic ,
// make an array to encode it in json
echo $_GET['callback'].'('.json_encode($responseArr) .')';
?>
and remove PHP code from h4 tag.

How to send a json string back to jquery

I need to send some data to an external php page and that page has to send the required data back to jQuery. My question is how can I send the data from the external page back to jQuery on the page that send it.
This is the jQuery code that sends the data to the external page:
function LoadImageData(url)
{
$.ajax({
url: 'get_image_data.php',
dataType: 'json',
data: {'url': url },
success: SetTag()
});
}
This is the PHP code htat receives the data and is required to send some data back:
<?php
require_once('FaceRestClient.php');
$apiKey = '**********************';
$apiSecret = '**********************';
$api = new FaceRestClient($apiKey, $apiSecret);
$active_url = $_POST['url'];
$photos = $api->faces_detect($active_url);
return $photos;
?>
So my problem is, how can I send the data backto jQuery. Just a simple return does not seem to work.
Thanks in Advance,
Mark
You need to echo the resulting JSON:
echo $photos;
If $photos is not already JSON, use json_encode:
echo json_encode( $photos);
One would think the REST API would give you JSON, but you need to check if it's valid JSON (JSONP is not valid here) ?
You could just drop the dataType in your Ajax function and let jQuery figure it out, that way atleast you'll get something back if it's not valid JSON.
Try this:
$.ajax({
url: 'get_image_data.php',
type: 'POST',
data: {'url': url }
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log('Your ajax just failed');
});
Open the console, and see what is printed
At the end of a PHP function I tend to do :
exit(json_encode($someData));
To return the data as JSON, but anything that prints the data is ok.
try this
echo json_encode( $photos);
you need to echo
echo $photos;
and as metntoned by #nickb if $photo is not already a json then convert it into json first and then echo.
echo json_encode($photos)
in jQuery if you want to fetch the data
onSuccess: function(data, status) {
//var data contains the returned json.
}

How to retrieve $_POST variable from jquery serializearray()

I have a problem in retrieving the $_POST data from jquery serializeArray();. I tried to for loop the $_POST to get the data but failed.
This is my JavaScript code:
function update_cart(){
var fields = $(':input').serializeArray();
console.log(fields);
var url = "update_cart.php";
$.post(url, {fields:fields}, function(data) {
alert(data);
}, "html");
return false;
}
In my PHP code :
var_dump($_POST);
The result is this:
array(1) {["fields"]=> string(15) "[object Object]"}
So, can anyone please teach me how to access the $_POST data?
You don't need to nest your serialized object; that seems to be what's causing the error. Just set your post call to:
$.post(url, fields, function(data) {
alert(data);
}, "html");
That should work; you might also want to change from using serializeArray to using serialize.
Once this is properly configured, if you have:
<input name="foo" value="bar" />
It can be accessed as:
$_POST["foo"]; //bar

Categories