my ajax is:
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: full_val+'='+add,
success: function(data)
{
}
});
if the javascript variable value changes depending on the conditions, then how will i $_GET[] the variable full_val? I want it to be something like:
$_GET[full_val]
is there a way to pass the variables of javascript to php?
If you want the literal index full_val, then use it in the query string:
data: 'full_val='+add,
So that in PHP, you'd be able to use $_GET['full_val']
Alternatively, you could also put an object in that field:
data: {full_val: full_val, add: add},
Here is the description:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
Your data just has the values and does not have the keys. See below for how to pass the keys and values.
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: {full_val:full_val,add:add},
success: function(data)
{
}
});
In your PHP use $_GET['full_val'];
send your values with data parameter correctly and add type:get to define GET method
add = 'request';
full_val = 'barrack obama';
$.ajax({
type: "get",
url: 'plugins/add_friend.php',
data: {'full_val':full_val,'add':add},
success: function(data) {
}
});
Then you will get values on php :-
use $_GET['full_val'] rather $_GET[full_val]
Try Using this
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'add.php',
data: 'full_val='+add,
success: function(data)
{
alert(data);
}
});
You can use the .get() method. The variables you can set using an object literal. For example:
$.get("/plugins/add_friend.php", {
add: "request",
full: "Barrack Obama"
}).done(function(data) {
console.log("Status:", data.status);
console.log("Received:", data.received);
});
And the PHP could be done something like this:
$add = filter_input(INPUT_GET, 'add', FILTER_SANITIZE_STRING);
$full = filter_input(INPUT_GET, 'full', FILTER_SANITIZE_STRING);
echo json_encode(array(
'status': 'OK',
'received': "{$add} and {$full}",
));
Related
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;
I read similar answer here in this question: How to insert into MYSQL row from multiple $_POST arrays and How to insert into MYSQL row from multiple $_POST arrays but the problem is these answers do not work in my code. Is it because im using an ajax? and i only get the value of the first array.
If i also place the variable declaration inside the for loop it is not working too.
Here is my ajax:
var name = [];
$('input[name="name[]"]').map(function(){ name.push($(this).val()); }); var studid = [];
$('input[name="studid[]"]').map(function(){ studid.push($(this).val()); }); var nameStr = name != '' ? '&name='+ name : '';
var studStr = studid != '' ? '&studid='+ studid : '';
var dataString = 'subject='+ subject + '§ion=' + section + studStr + nameStr;
$.ajax({ type: "POST", url: 'save.php', data: dataString, dataType: "html",
success: function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); }); },
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); } });
return false;
});
Here is my php:
if(isset($_POST['studid']) || isset($_POST['name'])){
$studid = array_map(mysql_real_escape_string, explode(",",$_POST['studid']));
$name = array_map(mysql_real_escape_string, explode(",",$_POST['name']));
for ($i=0; $i<count($studid); $i++){
$sql_1 = "INSERT INTO tbl_student(StudentID, StudentName, SubjectID) VALUES ('".$studid[$i]."', '".$name[$i]."', LAST_INSERT_ID())";
mysqli_query($con,$sql_1);
}
}
use mysql_insert_id();
instead of LAST_INSERT_ID()
You're not sending data correctly from the jQuery and its seems you'r mixing arrays and string together.
This is a simple request that posts studid-array from jQuery
var saveData = $.ajax({
type: 'POST',
data: {studid: studid},
url: 'save.php',
dataType: 'html'
});
saveData.done(function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); });
});
saveData.fail(function(ts) {
alert(ts.responseText);
});
When save.php is called, $_POST['studid'] would be set (if there are anything in the array)
If you instead do like this:
var saveData = $.ajax({
type: 'POST',
url: 'save.php?studid=' + studid,
dataType: 'html'
});
When save.php is called, $_GET['studid'] would be set (if there are anything in the array). The best way though is to use data-option in the ajax-function call (in my first case). If you choose to use this option you would have to serialize the stuid-array before putting it in as a part of an url.
UPDATE
If you want to pass multiple arrays you would have to do something like this:
var saveData = $.ajax({
type: 'POST',
data: {studid: studid, name_arr2: data_arr2},
url: 'save.php',
dataType: 'html'
});
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);
}
});
I have a PHP-Script that expects:
$_REQUEST['asdf']['bsdf']['csdf']
to be set when it is called, and I cannot change this.
I want to call this PHP-Script via ajax:
myurl = 'example-url.com';
myid = $(this.$element).attr('id'); //gets the id of a textfield: csdf
value = 'somevalue';
$.ajax({type: 'POST',
url: myurl,
data: {'asdf[bsdf][myid]': value},
success: function (data) {
/* blabla */
}
});
It does not work though, because the var "myid" is not filled with the supposed value "csdf".
Can someone help me how to do this?
PS: I cannot access the PHP-File, so no changes in structure possible...
Try something like this:
var myurl = 'example-url.com';
var myid = $(this.$element).attr('id'); //gets the id of a textfield: csdf
var value = 'somevalue';
var param = {};
param[myid] = value;
$.ajax({type: 'POST',
url: myurl,
data: {'asdf[bsdf]' : param},
success: function (data) {
}
});
You can build the param object outside the data you pass via the ajax call to keep the correct key in place.
in JS
... {
...
data: {[['first', 'array', 'nested'], 'other', 'in', 'parent', 'array']},
...
}
In PHP getting the POST vars is with other sentence
http://php.net/manual/en/reserved.variables.post.php
I need (recently) to get an array from the server after an ajax call created by jquery. I know that i can do it using JSON. But i don't know how to implement it with JQuery (im new with JSON). I try to search in internet some example, but i didnt find it.
This is the code :
// js-jquery function
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
// here i need to manage the JSON object i think
}
});
return false;
}
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo $linkspon;
}
in fact, i need to get the array $linkspon after the ajax call and manage it. How can do it? I hope this question is clear. Thanks
EDIT
ok. this is now my jquery function. I add the $.getJSON function, but i think in a wrong place :)
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
$.getJSON(url, function(data) { alert(data[0]) } );
}
});
return false;
}
Two things you need to do.
You need to convert your array to JSON before outputting it in PHP. This can easily be done using json_encode, assuming you have a recent version of PHP (5.2+). It also is best practice for JSON to use named key/value pairs, rather than a numeric index.
In your jQuery .ajax call, set dataType to 'json' so it know what type of data to expect.
// JS/jQuery
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
console.log(data.key); // Outputs "value"
console.log(data.key2); // Outputs "value2"
}
});
return false;
}
// PHP
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon["key"]= "value";
$linkspon["key2"]= "value2";
echo json_encode($linkspon);
}
1) PHP: You need to use json_encode on your array.
e.g.
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo json_encode($linkspon);
}
2) JQUERY:
use $.getJSON(url, function(data) { whatever.... } );
Data will be passed back in JSON format. IN your case, you can access data[0] which is "my";