Getting PHP variable to jquery script file by AJAX call - javascript

So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results.
My php file is echoing data that should be printed in my results div.
Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??

Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1 on the javascript.

You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so
echo data[0];
which in this case wiill echo the text peiceofdata.

write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({
type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});

Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});

Related

How to can I print an array transferred from javascript to php from $_POST

I am trying to transfer a javascript array to a php array and I used the following code in my php file to do so:
var rowArr=[];
var currow=$(this.closest('tr'));
var col1=currow.find('td:eq(0)').text();
rowArr.push(col1);
var col2=currow.find('td:eq(1)').text();
rowArr.push(col2);
var col3=currow.find('td:eq(2)').text();
rowArr.push(col3);
var myJSONText = JSON.stringify( rowArr );
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function() {
alert("Success");
}
});
so when I run this code, I get the success alert but I am not seeing any of the array elements being printed out. I am also not getting any error messages.Here is my jsonRecieve.php:
<?php
$rowAr=$_POST['emps'];
print_r($rowAr);
?>
is there a way to verify that it has been transferred? I don't believe it has but if it hasn't can someone help?
Seems you need to decode the json string with json_decode() to get your emps value on the server side and to alert the server response need to send something from the server. Let's debug this way-
ON JS
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function(data) {
alert(data); // alert your data to see that returns from server
}
ON PHP
<?php
$rowAr=$_POST['emps'];
$array = json_decode($rowAr,1); // 2nd params 1 means decode as an array
print_r($array);
die('response from the server');
?>

How to pass json object values to php dinamically?

Hi I'm newbie in JSON and Ajax and my question is probably quite stupid but when learning, also the stupid questions are fundamental.
I need to pass two parameters via Ajax (giorno and periodo),
for example
'giorno' = 2017-05-10 and
'periodo' = 2:
$.ajax({
type:'POST',
data: JSON.stringify({
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
}),
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
The JSON object passed perfectly and the result in Firebug Console is:
{"giorno":"2017-05-10","periodo":"2"}
If I try to manually copy and paste the object on the php page like this:
<?
$json = '{"giorno":"2017-05-10","periodo":"2"}'; //pasted manually
$json = json_decode($json, TRUE);
$giorno = $json['giorno'];
$periodo = $json['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
the two echoes show me the values. OK!
My problem start and stop here. I'm not able to bring the JSON object to be decoded.
I'm quite sure is a stupid solution but I don't know how to do that.
I need to create a function that wrap the Ajax call and then call the function in json_decode??
PS
I also tried to simply get the values with "$_POST['giorno']" etc.. instead of using JSON but without success.
Can someone help me please? Thank you for your patience.
UPDATE 10/05/2017
Hi I've followed your suggestions so I tried one time more to simplify the code like this:
$('input:radio[name=periodo]').change(function() {
var giorno = document.getElementById("dataselezionata").value; // from datepicker
var periodo = $('input:radio[name=periodo]:checked').val(); // from radio button
var post_data = ("giorno="+giorno+"&periodo="+periodo);
$.ajax({
type:'GET',
data: post_data,
url:"http://www.rinnovipatenti.com/prenota/prenotazione.php",
});
if (this.value == '1') {
$('#orario').show();
$('#orari-mattina').show();
$('#orari-pomeriggio').hide();
}
else if (this.value == '2') {
$('#orario').show();
$('#orari-pomeriggio').show();
$('#orari-mattina').hide();
}
using GET method instead of the POST one and in the PHP page prenotazione.php the code now is:
<?
$giorno = $_GET['giorno'];
$periodo = $_GET['periodo'];
echo"$giorno";
echo"$periodo";
?>
In Firebug console the parameters are ok
giorno 2017-05-10
periodo 2
the formatted link is:
http://www.rinnovipatenti.com/prenota/prenotazione.php?giorno=2017-05-10&periodo=2
the html console preview works correctly but the page don't.
I'm in the corner!
Is very strange. I have only one doubt: can I send data by GET/POST method to the same page where the data are collected?
In other word can the page foo.php send data to foo.php like a cycle without refresh?
And the ajax call could be wrapped inside the .change function or must be outside?
$.post( "http://www.rinnovipatenti.com/index2.php?a=prenotazione", {
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
} );
you do not need to stringify your JSON
on PHP side you just use
$giorno = $_POST['giorno'];
$periodo = $_POST['periodo'];
to get the values
you can use the following function. you have it already. it worked fine for me.
$('input:radio[name=periodo]').change(function() {
var giorno = '2017-05-15';
var periodo = '2';
$.post( 'http://www.rinnovipatenti.com/index2.php?a=prenotazione', {
giorno: giorno,
periodo: periodo
});
/*....*/
});
Method 2
You don't have to stringify the JSON object
$.ajax({
type:'POST',
data: {
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
},
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
So you php code will be like this
<?
$giorno = $_POST['giorno'];
$periodo = $_POST['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
Method 2
If you want to stringify the JSON object then put it in a key
$.ajax({
type:'POST',
data: 'data='+JSON.stringify({
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
}),
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
So you php code will be like this
<?
$json = $_POST['data'];
$json = json_decode($json, TRUE);
$giorno = $json['giorno'];
$periodo = $json['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
When you send application/json payload to php to access that payload use:
$json = json_decode(file_get_contents('php://input'), TRUE);
As mentioned in other comments and answers if you stay with $.ajax default form encoding and don't json stringify the data then use $_POST

Return only a json object to ajax caller

I'd like to return/access just an array on my success callback.
But I only get the whole html page.
$.ajax({
'URL': 'getData.php',
success:function(data){
alert(data); //Whole html file
}
})
getData.php
<?php
//Feed the array with database content
echo json_encode( $columns );
?>
How may I access the just the content of $columns
Obs1: My php file contains ONLY php code, 100%.
This is what is printed with alert above:
Your script is has HTML which cannot be parsed so make sure it returns only json string.
I know what do you mean, you can parse the json in javascript which was sent by PHP using JSON.parse(string);
Make sure your php doesn't return any other string or HTML other than encoded json.
Here is your modified JS, It should work as intended, You can check your desired output in browser console.
$.ajax({
'URL': 'getData.php',
success:function(data){
data = JSON.parse(data);
console.log(data);
alert(data); //Whole html file
}
})
I think that you have to set the dataType, and put url without single quotes.
Try to do this...
$.ajax({
type: 'GET',
url: 'getData.php',
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
/* Operate with each array row */
});
}
});

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

Making Key Value pair for the form elements in JavaScript

I have a module where the forms created are dynamic. So the number of inputs can defer always. Also, the array key can also defer.
My current method of posting form is this:
name = form_options[option_1] value = 1
On submitting the form using POST, I get the form as array in $_POST, which looks like this.
form_options(
option_1 => 1
)
But, now I am trying to implement the same thing using AJAX. So, I would need a common module to get all form values.
I found a way to do it.
var objectResult = $('#options_form').serializeArray();
console.log(objectResult);
This gives me a result like this:
0: Object
name: "form_options[option_1]"
value: "1"
How can parse this result to get an array like $_POST array, which I can send as data in AJAX.
P.S: All the form elements have name field as form_options[key]
You should use this for get post data in PHP file.
// You can use like this
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: "POST", // Enter Request type GET/POST
url: 'action.php', // Enter your ajax file URL here,
dataType: 'json', // If you are using dataType JSON then in php file use die( json_encode($resultArray) );
data: objectResult, // Put your object here
beforeSend: function(){
alert('before');
},
error: function(data) {
console.log(data);
},
success: function(response){
console.log(response);
}
});
// In php file get values like this way
$_POST['form_options']
try like this,
In JQuery:
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: 'POST',
url: 'yoururl'',
data: objectResult ,
success:function(data){
alert(data);
}
});
In your php:
<?php echo var_dump($_POST);?>
You can use jquery serialize with ajax directly, there is no need to use serializeArray:
$.ajax({
type:"post",
url:"formHandleSkript.php",
data: $("#options_form").serialize(),
success: function(response){
$(".result").html(response);
}
});
For more information see http://api.jquery.com/serialize/

Categories

Resources