I am trying to modify Wordpress page UI. I have written a js function:
<script type="text/javascript">function myfunction()
{
var userSettings = {"url":"\/","uid":"xyz","time":"1584212082","secure":"1"};
alert (userSettings);
if (window.JSON && window.JSON.parse)
{
alert ("true");
var auser = window.JSON.parse(userSettings);
if (auser == null)
{
alert ("Yes");
}
else
{ alert ("No") }
}
else
{
alert ("false");
}
}
</script>
when i call this function i get the [object Object] for alert(userSettings); That means object is surely there. Then i get true message. That means window.JSON is working. After this none of the alert message is displayed.
My main objective is to parse the json and get the uid from json string.
i also read this link for some help https://www.learningjquery.com/2016/12/jquery-parsejson-vs-json-parse
userSettings is already in JSON format. Just use userSettings.uid
Related
First of all, Hello Everyone, I'm new in here.
I have searched all over the site and I can't seem to find an answer to my problem...
I have an input, being generated via AJAX-PHP dynamically, and I want the user to enter some Value there, then send the data via Ajax for processing it into Mysql.
Thing is, javascript is reading the input value of the as Null:
"Uncaught TypeError: Cannot read property 'value' of null"
Here's the code:
function addBandMember() {
var Btn = _("addBandMem");
var errorMsg = _("UpWinMsg");
var url = window.location.href;
var mmbr = _("#newBandMember").value; // <-THIS IS RETURNING NULL
if (mmbr == "") {
errorMsg.innerHTML = "Please enter a USERNAME";
} else {
errormsg.innerHTML = "please wait...";
var ajax = ajaxObj("POST", url);
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
//SETTINGS RECEIVED
if (ajax.responseText != "member_added") {
errorMsg.innerHTML = ajax.responseText;
} else {
toggleUpWin();
receiveUserData();
}
}
};
ajax.send("mmbr=" + mmbr);
}
}
I believe this is happening because the Input field is being generated AFTER the document loads, via Ajax and PHP... Am I wrong? How can I address this newly-generated ID?
Thanks!
Try this one to get the value of input box.
var mmbr =$("#newBandMember").val();
OR
var mmbr =_("#newBandMember").val();
Found the answer... It was just a stupid mistake...
I have a function set for "getElementById" which requires a string, without "#".
so it'd be:
var mmbr = _("newBandMember").value; // <-THIS IS NOT RETURNING NULL
instead of:
var mmbr = _("#newBandMember").value; // <-THIS IS RETURNING NULL
Thanks to everyone who answered!
I m trying to post the value from my java_post.js into php_post.php and then retrieve in another javascript page, index.html. So far i can post the value into the php_post.php and retrieve back into my java_post.js as alert(data)
but i cannot retrieve from my index.html
Java_post.js
var url_link ="index.html";
//On Click Select Function
$("#table_hot").on('click', 'tbody tr',function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
$.post('PHP_post/php_post.php',
{
postvalue:value
},
function(data){
alert(data);
}
);
});
//Window Pop Out Function
function hotspot_pop(url_link){
newwindow = window.open(url_link, '', "status=yes,
height=500; width=500; resizeable=no");
}
The value is retrieve when the client click the selected table and then post into the php_post.php. The php_post.php will filter the result and return to index.html.
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
echo $filtered_students;
So now i m able to retrieve the value and post into as an alert for my java_post.js but the value is no pass into index.html and i receive the error for undefined postvalue.
<html>
<script src="js/jquery-1.11.1.min.js"></script>
<body>
<div id="result"></div>
<script>
var xmlhttp_user = new XMLHttpRequest();
var url_user = "PHP_post/php_post.php";
xmlhttp_user.onreadystatechange=function() {
if (xmlhttp_user.readyState == 4 && xmlhttp_user.status == 200) {
document.getElementById("result").innerHTML=xmlhttp_user.responseText; }
}
xmlhttp_user.open("GET", url_user, true);
xmlhttp_user.send();
</script>
</body>
</html>
So my problem is now, is there any method that allow me to show the value in index.html from php_post.php. As a reminder the alert(data) from java_post.js is just a testing purpose to show the value did post and return from php_post.php
The issue you're having is that when you pass the data into your PHP file and receive the data back in your JavaScript, the information only lasts as long as your current request.
To fix this issue, consider using PHP Session variables to store your data, so that you can retrieve it later.
Example:
// php_post.php
<?php
start_session(); // initializes session for persistent data
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
$_SESSION["filtered_students"] = $filtered_students; // You can now retrieve this in
// Another PHP file
?>
Now in another file (you would switch your HTML file to get from php_get.php):
//php_get.php
<?php
start_session(); // Don't forget to start the session
echo $_SESSION['filtered_students'];
?>
More information here: http://www.w3schools.com/php/php_sessions.asp
You can set the desired value into PHP session while at php_post.php.
This way, you can retrieve the session's value on any page you desire.
I want save the server response from the periodical updater as a string that I can then parse.If I put the alert inside the function everything works fine. However in the js code below the alert will show up blank. Any help would be greatly appreciated
<script>
var str='';
var on=new Ajax.PeriodicalUpdater("onlinelist",
"manageuser.php?action=onlinelist",
{method:’get’,onSuccess:function(transport){str+=transport.responseText;},
frequence:1000});
alert(str);
</script>
Not sure what your intention is there.
onSuccess method will fire once data is received successfully.
<script>
var str='';
var on=new Ajax.PeriodicalUpdater("onlinelist",
"manageuser.php?action=onlinelist",
{
method:"get",
onSuccess:function(transport){
str+=transport.responseText;
// continue using once it is available
doSomething(str);
},
frequence:1000
});
function doSomething(str) {
// logic that requires str
}
</script>
The javascript is supposed to handle form submission. However, even if called with
script src="js/registerform.js"> Uncaught ReferenceError: sendreg is not defined .
The function is called onclick. Can be reproduced on www.r4ge.ro while trying to register as well as live edited. Tried jshint.com but no clue.
I will edit with any snips required.
function sendreg() {
var nameie = $("#fname").val();
var passwordie = $("#fpass").val();
var emailie = $("#fmail").val();
if (nameie == '' || passwordie == '' || emailie == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/register.php", {
numeleluii: nameie,
pass: passwordie,
mail: emailie
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
setTimeout(fillhome, 1000);
});
}
}
function sendpass() {
var oldpassw = $("#oldpass").val();
var newpassw = $("#newpass").val();
if (oldpassw == '' || newpassw == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
xoldpass: oldpassw,
xnewpass: newpassw
}, function(data2) {
alert(data2);
$('#passform')[0].reset(); // To reset form fields
});
}
}
function sendmail()
{
var curpass = $("#curpass").val();
var newmail = $("#newmail").val();
if (curpass == '' || newmail == '')
{
alert("Please fill all the forms before submitting!");
}
else
{
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
curpass: curpass,
newmail: newmail
}, function(data3) {
alert(data3);
$('#mailform')[0].reset(); // To reset form fields
});
}
}
I'm guessing here but... I imagine you are doing something like
...<button onclick="sendreg">...
And you have your <script> in the bottom on the code. Just put them on top or use $("#mybtn").click(sendreg)
Try using $("#mybtn").click(sendreg) instead of inline onclick.
The script wasn't called in the html. sorry for wasting time. A simple
<script src="js/registerform.js"></script> Fixed it.
There is no syntax error there, and I don't see any such error when trying the page.
The error that you get is that you can't make a cross domain call. Do the request to the same domain:
$.post("http://www.r4ge.ro/php/register.php", {
or:
$.post("/php/register.php", {
I have a PHP script setup that echo's JSON responses depending on what the user has done (or not done as the case may be):
The responses look like this:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
Each response is generated like this:
echo $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
This is picked up by pNotify and displayed - lovely. (See below .done function for ajax request)
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var array = json_to_array(msg);
}
if (array['type'] !== 'none') {
if (array['title'] !== null) {
pushNotification(array['title'], array['response'], array['type'], array['hide']);
} else {
pushNotification(ucfirst(array['type']), array['response'], array['type'], array['hide']);
}
}
ready_status();
});
If the response cannot be validated by tryParseJSON(); the reponse is written directly to the page for debugging.
The problem is when I echo multiple responses back like this:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NDat]","title":"Exception","hide":false}
tryParseJSON() sees it as mumbo jumbo and prints it to the page.
Question
How do i pick up the above two lines as separate responses and parse them through my function and sub-sequentially to pNotify without combining them into a single JSON array?
Solution
As pointed out this was over complicated. Instead I combined each response (PHP side) into a an array:
$res['json'][] = $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
Then echo'ed it at the end of the script:
echo json_encode($res['json');
On client side, I used a for loop, sending them to pNotify in each iteration:
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var obj = json_to_array(msg);
}
for (var i=0;i<obj.length;i++) {
if (obj[i]['type'] !== 'none') {
if (obj[i]['title'] !== null) {
pushNotification(obj[i]['title'], obj[i]['response'], obj[i]['type'], obj[i]['hide']);
} else {
pushNotification(ucfirst(obj[i]['type']), obj[i]['response'], obj[i]['type'], obj[i]['hide']);
}
}
}
ready_status();
});
Instead of creating so sperate JSON-Outputs merge it to one single output string.
For this just wrap your two arrays you are currently outputting separately in an array like so
$myOutput[0] = responseArray1;
$myOutput[1] = responseArray2;
echo json_encode($myOutput);
This way you will get a valid JSON-response. Everything else is just some dirty workaround and causes shivers to everyone who has to review your work.