creating query from data recived from javascript via ajax - javascript

I have the following javascript:
function update_number_of_adds_found(field_dropdown, selected_value) {
selected_value="";
for(i=0; i<document.submitadd.elements.length; i++){
if(document.submitadd.elements[i].value !='' && document.submitadd.elements[i].value != 'Αναζήτηση' && document.submitadd.elements[i].checked !=''){
selected_value += (document.submitadd.elements[i].name +'-' + document.submitadd.elements[i].value +' ');
}
}
var result5 = $.ajax({
'url': '<?php echo site_url('search/findNumberOfAdds'); ?>/' + selected_value,
'async': false
}).responseText;
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(result5);
}
This script send the data in the following format:
addtypeid-1%20isnew-1%20geographicareaid-3
I am a bit restriced in which symbols i can use, because I am using codeigniter, and if I use & for example i get message that i use dissalowed characters in my url.
My question is how can i transform this data in the format $key['fieldname'] = $value['fieldvalue'] so i can built my where clausule?
I was trying something with explode or replace, but without success so far. Any help will be deeply appreciated.
Regards, John

Just following up on my comment above ... You can try something like this ... I haven't tested it but should give you ideas to how to go about ...
jQuery('.submit').click(function(){
var str = $("#myForm").serialize();
str += '&serialize=' + encodeURIComponent(str);
str += '&action=myformsubmit';
jQuery.ajax('phpscripturl.php', {
method: 'POST',
data: str,
success: function(response) {
alert('Got this from the server: ' + response);
},
beforeSend: function(){
alert('Sending...');
}
});
return false;
});
By serializing the form inputs with jQuery's serialize you create a string like:
a=1&b=2&c=3&d=4&e=5&postID=10
So you can fetch this serialized data as
$data = $_POST['serialize'];
foreach($data as $key => $value) {
if($value == '') continue; //skip empty values as per your request
//else save in db etc ...
}

Build an JSON object then Stringify and post it in one variable. Then use json_decode($_POST['key']) to create a PHP object and can access the values easily.
In JS
var ValueToSend = new Object();
ValueToSend.field1 = value1;
var postString = JSON.stringify(ValueToSend)
In PHP
$Object = decode_json($_POST['key']);

Related

Fetching a single record is outputting more than the records contents and json.parse not logging the correct data

I set up a new table called triggers. What I am doing is setting up a simple binary system that triggers things from showing or not showing. The code below is from an attempt I just made at doing this.
I'm running into two issues with the code below.
The echo json_encode is actually echoing onto the file's page. I have never had this happen before, so I'm unsure why it is doing so.
The echoed result is this:
{"specialPopStatus":{"setting":"1","0":"1"}}
The only number that should be showing up is 1. I don't understand where the trailing 0 and 1 are coming from.
The console.log results from the JSON.parse is [object Object]. I don't understand why, if at the very least, the 1, 0 and 1 isn't outputting.
Ultimately, all I am wanting is the setting result from the db for the single record I indicate by the name. Then I want to fetch this record via my ajax function. It will always be either 0 or 1.
What am I doing wrong?
PHP
try {
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$special_pop_sql = "
SELECT setting
FROM triggers
WHERE trigger_name = 'Special Pop'
LIMIT 1
";
if ($special_pop_stmt = $con->prepare($special_pop_sql)) {
$special_pop_stmt->execute();
$special_pop_row = $special_pop_stmt->fetch();
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
echo json_encode(['specialPopStatus' => $special_pop_row]);
JS
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
obj = JSON.parse(data);
specialPopStatus = obj.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
EDIT - New JS:
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
//Catalog Requests
specialPopStatus = data.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
The reason for the extra data in the json string is that you use
$special_pop_row = $special_pop_stmt->fetch();
the default of which is to return an assoc array AND a numeric array, notice the data value is 1 in both cases.
So fix that by doing this small mod
$special_pop_row = $special_pop_stmt->fetch(PDO::FETCH_ASSOC);
Also in the javascript because you have given
datatype: 'json',
as the paramter, you dont have to parse the json as jQuery will do that for you
So the javascript code be written
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
specialPopStatus = data.specialPopStatus;
//status2 = specialPopStatus;
console.log(specialPopStatus + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();

JSON array to and from MySql. Saving and Looping

<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}
This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.

Parsing JSON objects to post

I am learning to build a simple API, I have the following code creating the following json:
Code:
$sql = "SELECT * FROM posts WHERE `user_id` = '$user_id' AND post_date > CURDATE() - INTERVAL 2 YEAR ORDER BY post_date DESC ";
$result = $dbc->query($sql);
$rows = array();
while ($row = mysqli_fetch_array($result))
{
$rows["posts"][$row['post_date']] = $row['post_content'];
}
echo json_encode($rows);
JSON created:
{"posts":{"2015-03-03":"33","2014-03-03":"33 33"}}
How do I parse this? I know the following code is a good start, but have not been able to go anywhere from there with success:
$.ajax({
url : "http://localhost:8888/290_project/api_write.php",
dataType: 'json',
type: 'get',
cache: false,
success : function(data){
}
});
Maybe I should then do something like in this w3 schools example?
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
I have yet to have luck thus far with this though, but I know I am so close!
To have a clearer interface to interact with, you may consider changing your script to return data in a form that is easier to work with:
while ($row = mysqli_fetch_array($result))
{
$post = array();
$post['date'] = $row['post_date'];
$post['content'] = $row['post_content'];
$rows["posts"][] = $post;
}
In your success function, you have access to the data as a javascript object
success : function(data){
alert(data.posts[0].date);
alert(data.posts[0].content);
}
You can manipulate this data here any way you like without parsing it.
I think $.parseJSON is your solution. You can do this in your success event:
$.ajax({
url : "http://localhost:8888/290_project/api_write.php",
dataType: 'json',
type: 'get',
cache: false,
success : function(data){
var data = $.parseJSON(data);
console.log(data);
}
});
You actually don't even need to parse it if you use
$.getJSON('http://localhost:8888/290_project/api_write.php', function(alreadyParsedJsonData) {
// do stuff
});

Ajax - after "success" go to another page retrieve user id from the url there

var JSONonj = {"name": "James","age":"25"};
var data = "This data i would like to retrieve and print in the main.html page after success call in ajax.";
$.ajax({
url: "/user",
type: "POST",
data: JSONobj,
dataType: "json",
success: function() {
window.location.href = "main.html";
},
contentType: "application/json"
});
Here is the deal. After success i want to redirect to main.html and when I get there, I would like to retrieve and print data variable there.
The redirection works fine. But I can not receive the data there.
There are two main ways to achieve that :
somehow send the data to the server (see the other answers for possible ways to do that)
use the browser's localStorage :
success: function() {
localStorage.setItem('myMainKey', data);
window.location.href = "main.html";
}
// in main.html's javascript :
var data = localStorage.getItem('myMainKey');
if (data !== undefined) {
//do something
}
Note : if you want to store and retrieve a complete javascript object, you would have to use JSON.stringify() / JSON.parse() for storing / retrieving it.
you can also do this:-
window.location.href="main.html?data="+data;
In main.html
var user = decodeURI(getUrlVars()["src"]);
`//Now do some stuff with this data`
`function getUrlVars() {
var vars = [], hash;
var hashes =
window.location.href.slice(window.location.href.indexOf('?') +
1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}`
Here's function that can be applied if you're using jQuery.
var redirect = 'http://www.example.com/';
$.redirectPost(redirect, {x: 'exemplo', y: '123'});
// jquery extend function
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
value = value.split('"').join('\"')
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
}
});
You would have to send that data in the querystring and reconstruct it with javascript. Or you would have to POST to a handler/controller (who knows what you are using..) with that json data and reconstruct it... either way you if you are going to change the location you will have to send the data.
If you are using HTML5 then local storage would be a good option as LeGEC advised.
Storing Objects in HTML5 localStorage

Using Javascript with php

I know this question has already been asked a few times, but I'm trying to use javascript with php. I have a file called parsing.php that parses through a xml feed and converts the metadata into JSON Object called "data". The parsing is done using ajax calls with JavaScript and JQuery.
<script src="json2.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
category.videos.push(video);
}
data.categories.push(category);
}
});
window.data = JSON.stringify(data);
<script>
"<?php
$dataVar = ?> <script type=text/javascript>window.data</script><?php;?>"
"<?php
print_r($dataVar,true);
?>"
The only reason why I need to use javascript and php is because I want to use the "print_r()" function from php which allows me to return the information rather than just printing it to the screen, but unfortunately I can't get it to work. If anybody knows of other alternative or could give some advice that would be greatly appreciated.
Here is what I believe you are trying to achieve, written in PHP:
$dom = new DOMDocument();
$dom->load("fakeFeed.xml");
$data = ["categories"=>[]]; // may need to use array() instead of [] depending on PHP version
foreach($dom->getElementsByTagName('item') as $item) {
$name = trim($item->getElementsByTagName('category')->item(0)->textContent);
if( !isset($data['categories'][$name])) {
$cat = ["name"=>$name,"videos"=>[]]; // again, adjust if you're on an older version
// I'm not entirely sure what you're trying to achieve on this part.
// you seem to be getting the same video five times...
// revise your approach, comment if needed, and I can try to help
// for now, "insert code here"
$data['categories'][$name] = $cat;
}
}
// we were using the name as a key for simplicity, now just take the values
$data['categories'] = array_values($data['categories']);
// done! $data now has your data.
var_dump($data);
If you really want to use this instead of using document.log for JS:
$.ajax({
type: "POST",
url: "some_php.php",
data: JSON.stringify(data);
})
.done(function( msg ) {
document.write(msg);
});
and the some_php.php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Categories

Resources