Defined Var not echoing value jquery and php - javascript

Hi I am trying to get my php variables to echo in my js code. I know technically php doesnt work in js/jquery but I've searched for workarounds and they dont seem to be working as expected. This is what I have --
<script type="text/javascript">
var stR = "<?php echo $htitle ?>";
var seq = "<?php echo $sequence ?>";
var coM = "<?php echo $comment ?>";
mrp_data_callbacks.push( function(index, data, stR) {
data["htitle-" + seq] = stR;
return data;
});
mrp_data_callbacks.push( function(index, data) {
data["comment-seq"] = coM;
return data;
});
</script>
And this is what is printed --
var stR = "testing comments";
var seq = "0";
var coM = "testing";
mrp_data_callbacks.push( function(index, data, stR) {data["htitle-" + seq] = stR;
return data;});
mrp_data_callbacks.push( function(index, data) {data["comment-seq"] = coM;
return data;});
So the php echos correctly when defining the variables but when using them in my functions, nothing works. I tried different combination of things and still nothing.
Basically in my functions I need "coM, seq, and stR" to echo the values.
What am I doing wrong?
EDIT:
This is my goal and what I mean by I need the values to echo. ---
modify to add your custom meta field values.
jQuery(document).ready(function() {
mrp_data_callbacks.push( function(index, data) {
data["hello"] = "world";
return data;
});
});
"Hello" -- My meta key
"World" -- The Value
data["hello"] = "world";
Where it says world, I am trying to have to output of the var(s) I created.
var stR = "testing comments";
data["htitle-" + seq] = testing comments;

The code uses the values you provided, but there is no code that actually calls the callback functions you have defined.
I have taken your code and added some tests around it, so to show that the values are indeed available to the two functions:
// Initialise the array of functions.
// Probably this is done by a library you loaded,
// of which you have provided no information:
mrp_data_callbacks = [];
// --- Original code BEGIN ---
var stR = "testing comments";
var seq = "0";
var coM = "testing";
mrp_data_callbacks.push( function(index, data, stR) {data["htitle-" + seq] = stR;
return data;});
mrp_data_callbacks.push( function(index, data) {data["comment-seq"] = coM;
return data;});
// --- Original code END ---
// Define data
var data = {};
// Call the above functions for testing the result:
mrp_data_callbacks.forEach( function(fun, index) {
fun(index, data, stR);
});
// check if everything worked, and data has received
// the expected properties. We use JSON.stringify to
// have a complete view of the data object:
alert(JSON.stringify(data));
The alert at the end outputs this:
{"htitle-0":"testing comments","comment-seq":"testing"}
So, this proves the values provided by PHP are readily available in the functions, through the variables stR, seq, coM. But you need to actually call these functions to see anything happening in your data object.
NB: console does not refer to what you see in "view source" in your browser, but to the tool in which you can query information about the displayed web document.
Edit
If you want the PHP values to be directly injected in the relevant Javascript functions, then you don't need the Javascript variables (stR, seq, coM), and you can do as follows in PHP:
<script type="text/javascript">
mrp_data_callbacks.push( function(index, data) {
data["<?php echo "htitle-" . $sequence ?>"] = "<?php echo $htitle ?>";
return data;
});
mrp_data_callbacks.push( function(index, data) {
data["comment-seq"] = "<?php echo $comment ?>";
return data;
});
</script>
This will come to the browser as this:
<script type="text/javascript">
mrp_data_callbacks.push( function(index, data) {
data["htitle-0"] = "testing comments";
return data;
});
mrp_data_callbacks.push( function(index, data) {
data["comment-seq"] = "testing";
return data;
});
</script>

Related

Passing Array to PHP from Javascript

I'm trying to pass my JS array to PHP array and all of the solutions that I have found here is useless or I can integrate these solutions to my problem.
Javascript
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
PHP
function ekleme(){
if($_POST['siparisListe']){
$liste = $_POST['siparisListe'];
echo $liste;
}
}
instead of this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
modify you code in to this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
var input_data = new FormData();
$.each(splitListe,function(index,value){
input_data.append("siparisListe["+index+"]",value)
});
$.ajax({
url: "menu.php",
data: input_data,
type: "POST",
success: function(data) {
$("#passwordMatch").html(data);
},
error: function(data) {}
})
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
Remove the [] from the POST field name and pass it an array (jQuery will JSON encode it for you).
$('#siparisButon').click(function() {
let splitListe = ($('#siparis-block span').text() || '').split('- ');
if (splitListe) {
$.post("menu.php", { siparisListe: splitListe });
$('#fonksiyon').show();
}
});
Then in your PHP to verify:
function ekleme() {
if ($liste = $_POST['siparisListe']) {
var_dump($liste);
}
echo 'No $liste array in POST.';
}

How to make the ajax 'data' that come with 2 values to get each value separately?

<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr[] = array($arrResult, // include only one value
$response_array['status'] );//success or not success value
return $return_arr;
}
?>
This $return_arr[] value return to the javascript ajax file >>
$.ajax({
url: 'PHPMethodCalls_AL.php',
type: 'post',
data: {... post many values to php function.. },
success: function(data) {
alert(data);
//data is successfully come as this format >> [[["Testing123"],"success"]]
var results = JSON.parse(data);
alert(results);
// this alert got >> Testing123,success
},
//this one is post value to function
$newCIarrayList = array();
$newCIarrayList = phpfunction(..data include );
echo json_encode($newCIarrayList);
What should I do to get each value as "Testing123" and "success" value separately? I tried with split(",") function but it didn't work.
You can seperate in php function before response to ajax like below .Then you can get easy
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr = array("data" =>$arrResult, // include only one value
"status" =>$response_array['status'] );//success or not success value
return $return_arr;
}
?>
var results = JSON.parse(data);
alert(results.data || results.status);
What you get back in success: function(data) is a stringified json of a nested array: [[["Testing123"],"success"]].
To get your status and payload out of this structure, you can use the following snippet.
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
console.log(parsedData); // quite nested
var status = parsedData[0][1];
console.log(status);
var payload = parsedData[0][0][0];
console.log(payload);
Or using ES6 destructuring:
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
[[[payload], status]] = parsedData;
console.log(status);
console.log(payload);
I would however suggest that you revise your php-side code, and make it so that it forms a simpler structure, ideally:
{"status": "success", "payload": "Testing123"}

jquery post form and variables together

I used this Code to send a form + a variable to a php-script.
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos }).done(function (data) {
alert(data);
});
}
now the PHP-Code:
$data = $_POST['infos'];
echo $data;
returns: formfield1=value1&formfield2=value2&formfield3=value3&test
All values are in this variable...
But how i can use them seperatly with PHP?
For example:
$data = $_POST['formfield1'];
didn't worked :(
Use jQuery's serializeArray(). It will return you with array of objects that contain 2 properties: name and value. You can then parse it and pass it as data.
It could look like this
var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
infos[formdata[i].name] = formdata[i].value;
}
// To add separate values, simply add them to the `infos`
infos.newItem = "new value";
$.post("ajax.php", infos).done(function (data) {
alert(data);
});
Then in PHP, you'll retrieve values using $_POST["formfield1"].
Try to explode them with -
$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();
foreach ($form_data as $value) {
list($key, $val) = explode('=', $value);
$posted_data[$key] = $val;
}
var_dump($posted_data);
You can use the parse_str method to convert the query string into an array.
In your case, you can do something like this:
parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need
More details here: http://php.net/manual/en/function.parse-str.php
// here is the jquery part
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos },function (data) {
alert(data); // the fetched values are alerted here.
});
}
//the php part is here
$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
foreach($form_data_val AS $form_vals){
$vals=explode($val_seperator,$form_vals);
echo $vals[1];// here the value fields of every form field and the test is fetched.
}
try this .

Unable to get variable from passing through URL

I have a variable stored username and I wish to pass this through a link to the next page. So I have:
Go!
When you land on register-form.php there is an onload event for the script:
<body onload="inputUsername()">
function inputUsername(){
console.log("I'm running" + username);
document.getElementById('inputUsername').value = username;
}
However I get an undefined variable error for username.
It seems to me that the URL is not passing the variable correctly. Should I be seeing my actual variable in the address line? Should I be seeing username=myusernameisthis ?
In essence, all I'm after is passing the variable username from page 1 to page 2. That's all.
Parameters passed in a url query string don't get magically loaded into the javascript global scope.
As #Archios says you can parse the query string with javascript with something like:
var username = getUrlVars()["username"];
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
but personally I prefer:
function inputUsername(){
var username= "<?php echo isset($_GET[username])?$_GET[username]:''; ?>";
console.log("I'm running" + username);
document.getElementById('inputUsername').value = username;
}
what would be even easier, is if you changed:
<input id="inputUsername" type="text" name="username">
to
<input id="inputUsername" type="text" name="username" value="<?php echo $_GET[username]">
and remove the onload event.
the href on the previous page should look something like:
Go!
assuming $username holds the current username
where your script says
username = wordOne + wordTwo + wordThree;
add the line
$('.userNameButton a').attr('href','register-form.php?username='+username);
I think You are trying to get query string variable to javascript not to php. Try something like:
Get query string parameter to js
You are getting an undefined variable error because you have not set the js variable 'username' anywhere. Setting this in the URL is NOT the same as defining a variable.
If you are setting the URL correctly you shouls see something like 'register-form.php?username=Francesca'
You can do this with a mix of PHP and javascript.
In your register-form.php:
register-form.php:
if(isset($_GET["username"])) {
$username = $_GET["username"];
} else {
$username = "not set";
}
in your js (this is better than calling <body onload="inputUsername()">):
window.onload=function(){
var username = <?php echo $username ?>
console.log("I'm running" + username);
document.getElementById('inputUsername').value = username;
};
Better yet would be to not use js at all and do this all in PHP:
<?php
if(isset($_GET["username"])) {
$username = $_GET["username"];
} else {
$username = "not set";
}
?>
<input name="username" id="username" type="text" value="<?php echo $username ?>">
Here ya go. I commented the code so it makes more sense hopefully. Basically, we get the url from the address bar and parse out the pieces one by one to get what we want.
window.ParseQueryString = function () {
//Get the current location in the address bar
var url = window.location.href,
parameterSet = [],
//Get everything to the right of the '?'
parameterString = url.split('?')[1];
//Do we have anything to work with?
if (parameterString) {
//Lets get all individual parameter in the parameter string
var parameterParts = parameterString.split('&');
for (var i = 0, e; e = parameterParts[i++];) {
//Get the parameter key and the value
var parameter = e.split('=');
//Push it into the array
parameterSet.push({
'key': parameter[0],
'value': parameter[1]
});
}
}
//Give me my prettyfied query string array plz!
return parameterSet;
}
console.log(ParseQueryString());
Using this code with a window location of http://www.home.com?s=search&f=images will yield:
[{ key: 's', value: 'search'}, {key: 'f', value: 'images'}]
With this, in your onload callback, you can call the ParseQueryString and look through it to find the username value and populate it to textbox.
Edit
I am added a function that instead of returning an array of key/value pairs, it will return an object with the query string keys as the fields on the object.
window.ParseQueryString = function () {
//Get the current location in the address bar
var url = window.location.href,
parameterSet = {},
//Get everything to the right of the '?'
parameterString = url.split('?')[1];
//Do we have anything to work with?
if (parameterString) {
//Lets get all individual parameter in the parameter string
var parameterParts = parameterString.split('&');
for (var i = 0, e; e = parameterParts[i++];) {
//Get the parameter key and the value
var parameter = e.split('=');
//Add a new field to the object
parameterSet[parameter[0]] = parameter[1];
}
}
//Give me my prettyfied query string array plz!
return parameterSet;
}
Here is a fiddler demonstrating your specific use case. Please note that the fiddler is appending a query string to the url as fiddler wouldn't allow it otherwise. This occurs on line 3

Running loop from javascript to save in Mysql

Hello i am currently running a javascript on my php page (below) and it comes out with each data that i need is there any way i can connect this through to mysql database? (i am new to javascript)
<script>
var allItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
for(var i = 0; i < allItems.length; i++) {
var item = allItems[i];
console.log('Current item: %o', item);
}
</script>
'itemsArray comes from a save function'
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {};
var num = document.getElementById("num").value;
newItem[num] = {
"methv": document.getElementById("methv").value
,'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
});
Thanks
PS I already have the connection for the database setup
Post your data with ajax/json request to a php function and do all database related work with php. Next return successful or failure status which will be catch in this called js function, and then you can display the success or failure message with javascript.
Example:
Include jQuery library:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
Script for ajax request with jQuery:
var path = 'http:/your_url/your_php_script_file.php';
var data = 'json_data=' + JSON.stringify(newItem[num]);
$.ajax({
url: path,
type: "POST",
data: data,
cache: false,
success: function ($returm_msg){
alert($returm_msg);
}
});
PHP for save/update in database:
$receive_value = json_decode($_POST['json_data'], true));
You will get values like
$receive_value['methv'],$receive_value['q1'],....,$receive_value['comm'];
Now do save operation in database.
$result = mysql_query("INSERT INTO .....") or die(mysql_error());
if($result){
return "Success!"; // if not function then simply echo "Success!";
}else{
return "Failure!"; // if not function then simply echo "Failure!";
}
Helpful links:
http://www.bennadel.com/resources/presentations/jquery/demo21/index.htm
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Categories