Multiple JSON arrays as reponses - AJAX & PHP - javascript

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.

Related

Unable to parse json string in wordpress UI

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

return multiple values from PHP to JS function (AJAX/SQL)

I want to have something like a small search engine for the FAQ section on my website. All it does is search the SLQ_DB for the term upon pressing a button.
I want to output the question and the answers in two seperate divs. Therefore I have $data and $data1 which belong to the divs.
$('input#name-submit').on('click',function()
{
var name = $('input#name').val();
//alert(name);
if($.trim(name) != "")
{
$.post('ajax/name.php',{name:name},function(data, data1)
{
$('div#name-data').html(data);
alert(answer);
$('div#name-data1').html(data1);
});
}
});
But when I hit enter the second div shows "success". But the first one has data and data1 in it. When I write function(data1, data) in the js file, the data1 has all the information, and data is just "success".
What's happening here?
The echo function in PHP outputs the content of a variable to the response body. This body is a "string" that your web application receives.
Let's say you have a code like this:
<?php
$var1 = "hello";
$var2 = "world";
echo $var1;
echo $var2;
?>
The resulting response body will look like this: helloworld.
Now let's say this is your JS code:
$.post('ajax/name.php',{name:name},function(data) {
console.log(data); // "helloworld"
});
jQuery will pass the response body to the data variable, which now contains heloworld.
You need to somehow separate the individual variables inside the response body, e.g. using JSON.
First step is to encode the data on the server, that's as simple as that:
<?php
echo json_encode(["var1"=>$var1, "var2"=>$var2]);
?>
This will create a response body that looks like this: {"var1":"hello","var2":"world"}.
The next logical step is to decode this JSON using JavaScript:
$.post('ajax/name.php',{name:name},function(data) {
var res = JSON.parse(data);
console.log(res.var1); // "hello"
console.log(res.var2); // "world"
});

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>

Display an alert based on a json data

I am having 2 portions of code (php and javascript).
In the PHP file, I use the function json_encode() to create a JSON data which will be sent to the Javascript file.
PHP FIle
<?php
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
$product_code = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove
if(isset($_SESSION["products"][$product_code])) {
unset($_SESSION["products"][$product_code]);
}
$total_items = count($_SESSION["products"]);
if($total_items == 0){
unset($_SESSION["products"]);
}else{
//Calculate total of items in the cart
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
$product_price = $product["price"];
$product_quantity = $product["quantity"];
$subtotal = $product_price * $product_quantity;
$total += $subtotal;
}
}
die(json_encode(array('items'=>$total_items, 'total'=>$total)));
}
?>
Javascript File
<script>
$(document).ready(function(){
$(".contentwrapper .content").on('click', 'a.removebutton', function() {
var pcode = $(this).attr("data-code"); //get product code
$.getJSON( "phpfile.php", {"remove_code":pcode}, function(data) {
alert(data.items);// the total number of item
});
});
</script>
Anytime the query $.getJSON( "phpfile.php", {"remove_code":pcode}... is successful, an alert is displayed showing the data.items. The problem I am facing is that, when data.items is greater than or equal to 1 the alert is prompted, but when data.items is equal to 0, no alert is prompted.
Kindly help me solve this problem
Looks like a PHP error. $total variable is only declared inside the 'else' condition, so when ($total_items == 0) $total is undefined. But as you've called die(json_encode(array('items'=>$total_items, 'total'=>$total))); the server doesn't have a chance to complain (maybe returning no data and hence no alert). If you try declaring $total = 0 before your condition it should also fix the issue, without having to die early.
One possibility is that actually data variable is undefined/null e.t.c., see this for example, second alert is not shown. Instead an error is shown on the browser console.
var data = {items:0};
alert(data.items);
data = null;
alert(data.items);
Adding die(json_encode(array('items'=>$total_items))); at the end of the condition if($total_items == 0) and it solves the problem. But I really can't explain what is happening. Up to now I do not really know the origin of the problem. Any explanation will be welcomed

When to escape data being sent with AJAX

I need to escape text that is being outputted via AJAX. If I submit script to the database, like <script>alert('hello world');</script>, then a popup is executed on the page.
This here is my function that is setting the data, and then grabbing data to be sent via AJAX.
function add_order() {
if($_SERVER['REQUEST_METHOD'] == "POST") {
$add_order = $this->order_model->set_order($_POST['text']);
if($add_order==false){
echo "fail";
return false;
}
$order_data = $this->order_model->get_order_by_id($add_order);
echo json_encode($order_data);
return true;
}
}
Jquery Code:
$('#create_order').submit(function(){
$.post('/order/add_order/', $('#create_order').serialize(), function(data){
var obj = $.parseJSON(data);
var obj_item = obj[0];
$('tr.'+obj_item.id).append("<td>" + obj_item.text + "</td>");
msg('success', 'Part #'+obj_item.number+' has been successfully created');
});
}
return false;
});
How do I stop obj_item.text from executing scripts?
You need to build DOM elements and set text instead of building HTML:
$("<td />", { text: obj_item.text }).appendTo('tr.tr.' + obj_item.id);
If the submitted data can only contain plain text, ensure that you use .text() to re-insert it back into the DOM - using .text will prevent any embedded tags from being rendered as HTML or otherwise handled by the browser.
You should also validate data on the server before it's stored, and for extra measure perform client-side verification before posting the data to the server. IMHO, it's better to reject bad data than to simply escape it.

Categories

Resources