jQuery serialize serializes the URL wrong - php

I have a form which I submit and I use .serialize to help me gather all data from the form. Now, I've checked in firebug what is sent in POST and I can see a nice formated string like example
index.php?data=sth&data2=sth
but the problem is with this & in the PHP - the PHP outputs it like this:
index.php?data=sth& a m p ;data2=sth
See this amp? Well it is written without spaces and it's and encoded (as I found out in google) version of &. So, what should I do to input this url correctly in the database and then fetch it a nd show it on the site without this & amp; ?
edit: if it's possible I would like a string with that & to be put in that format to DB. (so, with & sign).
edit#2:
how I send data:
var formData = $("#myForm :input[value]").serialize();
$.ajax({
type: 'POST',
cache:false,
url: '_ajax/updateGameInfo.php',
async: false,
dataType: 'text',
data: allData,
success: function(jsonObj) {
if (jsonObj){
$msg = 'Data sucessfully updated! Reloading page...';
alert($msg);
}
else{
$msg = 'Error with the update!';
alert($msg);
}
}
});
And here is my updateGameInfo.php:
$gameRepos = new GameRepository();
$game = $gameRepos->updateGame();
echo json_encode( $game );
And if you also like, here is my updateGame function from GameRepository:
public function updateGame()
{
$cleanPost = array_map( array('GameRepository', 'cleanPostData'), $_POST);
$attributes = array_keys($cleanPost);
$values = array_values($cleanPost);
$table = $this->resolveTableName( $cleanPost["selectedTypeId"] );
$id = $cleanPost["selectedGameId"];
if ($this->openConnection())
{
$pairs = "";
foreach ($cleanPost as $attribute => $value){
if ($attribute != "selectedGameId" && $attribute != "selectedTypeId"){
if ($attribute == "url")
$value = str_replace("amp;", "", $value);
$pairs .= $attribute . "='" . $value . "',";
}
}
$pairs = rtrim($pairs, ','); //remove last comma
$query = "UPDATE $table SET $pairs WHERE id=$id;";
$result = pg_query($query);
if (!$result){
mysql_error());
return false;
}
else
return true;
}
else
return false;
}

If you are passing in the URL as a POST variable, then PHP is going to automatically encode any special characters. So, assuming the POST variable name is url, you would want to do this in your php script before everything else:
$_POST['page_url'] = htmlspecialchars_decode($_POST['page_url']);
The issue isn't with jquery, it's with php. You'll run into similar issues when passing json strings.

Did you check the charset in the html header of the page?
Try to change it!

Related

returned ajax query data undefined

Hello I am attempting to create an ajax query but when my results are returned I get Undefined as a response. Except for the object called "hello" which returns back as "h" even though it is set to "hello". I have a feeling it has something to do with the way ajax is sending the data but i'm lost as to what may be the issue. Any help would be greatly appreciated.
here is the ajax
function doSearch() {
var emailSearchText = $('#email').val();
var keyCardSearchText = $('#keyCard').val();
var userNameSearchText = $('#userName').val();
var pinSearchText = $('#pin').val();
var passwordSearchText = $('#password').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: {
"hello": "hello",
"emailtext": "emailSearchText",
"keycardtext": "keyCardSearchText",
"usernametext": "userNameSearchText",
"pinText": "pinSearchText",
"passwordtext": "passwordSearchText"
},
dataType: "json",
success: function (data) {
alert(data.msg);
var mydata = data.data_db;
alert(mydata[0]);
}
});
}
Then here is the php
include_once('connection.php');
if(isset($_POST['hello'])) {
$hello = $_POST['hello'];
$emailSearchText = mysql_real_escape_string($_POST['emailSearchText']);
$keyCardSearchText = mysql_real_escape_string($_POST['keyCardSearchText']);
$userNameSearchText = mysql_real_escape_string($_POST['userNameSearchText']);
$pinSearchText = mysql_real_escape_string($_POST['pinSearchText']);
$passwordSearchText = mysql_real_escape_string($_POST['passwordSearchText']);
$query = "SELECT * FROM Students WHERE (`User name`='$userNameSearchText' OR `Email`='$emailSearchText' OR `Key Card`='$keyCardSearchText')AND(`Password`='$passwordSearchText'OR `Pin`='$pinSearchText')";
$students = mysql_query($query);
$count = (int) mysql_num_rows($students);
$data = array();
while($student = mysql_fetch_assoc($students)) {
$data[0] = $student['First Name'];
$data[1] = $student['Last Name'];
$data[2] = $student['Date of last class'];
$data[3] = $student['Time of last class'];
$data[4] = $student['Teacher of last class'];
$data[5] = $student['Membership Type'];
$data[6] = $student['Membership Expiration Date'];
$data[7] = $student['Free Vouchers'];
$data[8] = $student['Classes Attended'];
$data[9] = $student['Classes From Pack Remaining'];
$data[10] = $student['5 Class Packs Purchased'];
$data[11] = $student['10 Class Packs Purchased'];
$data[12] = $student['Basic Memberships Purchased'];
$data[13] = $student['Unlimited Memberships Purchased'];
$data[14] = $student['Groupon Purchased'];
};
echo json_encode(array("data_db"=>$data, "msg" => "Ajax connected. The students table consist ".$count." rows data", "success" => true));
};
Your PHP script is likely producing error messages because the $_POST values you are trying to access don't match the key names you are sending in the request. For example: $_POST['emailSearchText'], yet you used emailtext in the AJAX call.
This is most likely causing jQuery to not be able to parse the response as JSON, hence the Undefined.
First of all, you have to remove the quotes or you will be passing those literals instead of the variables.
$.ajax({
...
data: {
hello: "hello",
emailtext: emailSearchText,
keycardtext: keyCardSearchText,
usernametext: userNameSearchText,
pinText: pinSearchText,
passwordtext: passwordSearchText
},
...
});
And then, like ashicus point out, in your PHP file:
$emailSearchText = mysql_real_escape_string($_POST['emailtext']);
$keyCardSearchText = mysql_real_escape_string($_POST['keycardtext']);
$userNameSearchText = mysql_real_escape_string($_POST['usernametext']);
$pinSearchText = mysql_real_escape_string($_POST['pinText']);
$passwordSearchText = mysql_real_escape_string($_POST['passwordtext']);
JS file looks ok, so this few clues to check PHP file.
See if there are even POST params there (printr all $_POST in php)
Check if your even enters IF. Add an else statement and echo some dummy json.
Check what is actually in encoded json that is echoed. Assign it to var then print.

Send array from php to javascript

I'm screen scraping a site with a php script which creates an array in the end that I want to send back to the javascript caller function. In the code below I've tried to print it out with 'print_r', which doesn't give me any results at all (?). If I echo out on of the elements (e.g $addresses[1]) the element is shown.
So, why ain't I getting anything out from the php function, and what is really the best way to send back the array to the calling js function?
Thanks a lot in advance!
js:
$.post(
"./php/foo.php",
{
zipcode: zipcode
},
function(data) {
$('#showData').html(data);
}
);
php:
$tempAddresses = array();
$addresses = array();
$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode;
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
$cell = $row->find('td', 0);
array_push($tempAddresses, $cell);
}
$tempAddresses = array_unique($tempAddresses);
foreach ($tempAddresses as $address) {
array_push($addresses, $address);
}
print_r($addresses);
You can use JSON to return an array back to the client-side, it can be send by AJAX same what you are doing on your existing code.
Use json_encode() of PHP, this function will make your PHP array into a JSON string and you can use it to send back to your client by using AJAX
In your PHP code(Just for demonstration how it works)
json.php
<?php
$addresses['hello'] = NULL;
$addresses['hello2'] = NULL;
if($_POST['zipcode'] == '123'){ //your POST data is recieved in a common way
//sample array
$addresses['hello'] = 'hi';
$addresses['hello2'] = 'konnichiwa';
}
else{
$addresses['hello'] = 'who are you?';
$addresses['hello2'] = 'dare desu ka';
}
echo json_encode($addresses);
?>
then in your client script(much better you use the Jquery's long AJAX way)
$.ajax({
url:'http://localhost/json.php',
type:'post',
dataType:'json',
data:{
zipcode: '123' //sample data to send to the server
},
//the variable 'data' contains the response that can be manipulated in JS
success:function(data) {
console.log(data); //it would show the JSON array in your console
alert(data.hello); //will alert "hi"
}
});
references
http://api.jquery.com/jQuery.ajax/
http://php.net/manual/en/function.json-encode.php
http://json.org/
js should be
$.ajax({
url:'your url',
type:'post',
dataType:'json',
success:function(data) {
console.log(JSON.stringify(data));
}
});
server
$tempAddresses = array();
$addresses = array();
$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode;
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
$cell = $row->find('td', 0);
array_push($tempAddresses, $cell);
}
$tempAddresses = array_unique($tempAddresses);
foreach ($tempAddresses as $address) {
$arr_res[] =$address;
}
header('content-type:application/json');
echo json_encode($arr_res);

Ajax variable not displaying on response

I am trying to incorporate some ajax into my code, at the moment it works great, when a user clicks a button it sends some hidden inputs to another php script, performs some actions, then sends the result back and outputs it, all updating with no refresh etc.
However, the last part I am trying to send and receive back is a variable that shows some html code, in other words the other variables that are being sent back and outputed are just numbers and letters, where as this one is actual div's, however it is not outputting it, I have tried it without the ajax, when the page first loads and it works great, but doesn't when i try it with the ajax, hopefully the code below will make more sense. The variable I want to be able to send back is $sl_output.
AJAX code on main page
<script>
$(document).ready(function (){
$(".add_detail_land_down").click(function(){
var hidden_count = $('input[name=addon_detail_hidden_count]').val();
var land_required = $('input[name=addon_hidden_land_required]').val();
var sl_array = $('input[name=addon_hidden_shopping_list_array]').val();
var button_tok = "land_down";
$.ajax({
type: "GET",
url: "addon_detail_calc.php",
data: { hidden_count: hidden_count, button_tok: button_tok, land_required: land_required, sl_array: sl_array },
dataType: "json",
success: function (data) {
$("#res_expected_gain").html(data.total_hidden);
$("#output").html(data.output);
$("#res_expected_profit").html(data.land_required);
$("#res_total_supply_time").html(data.test_time);
$("#land_selected_token").html(data.total_hidden);
$("#sl_output_div").html(data.sl_output);
}
});
return false;
})
});
Code in addon_detail_calc.php
<?php
// header('application/json');
$hidden_count = $_GET["hidden_count"];
$button_tok = $_GET["button_tok"];
$land_required = $_GET["land_required"];
$sl_array = $_GET["sl_array"];
$sl_output = "";
if($button_tok == "land_up"){
//MAIN CODE SHALL BE DONE HERE
$hidden_count = $hidden_count + 1;
$test_time = $hidden_count * 66;
$new_sl_array = array();
$final_sl_array = array();
foreach ($sl_array as $columnName => $columnData) {
if($columnName == "0"){
unset($sl_array[$columnName]);
}else{
$new_columnData = $columnData * 54;
$new_sl_array[$columnName] = $new_columnData;
}
}
foreach ($new_sl_array as $columnName => $columnData) {
$sl_output = "";
$sl_output = '<li class="add_detail_content_ele_wrap_ele"><div class="add_detail_content_ele_wrap_ele_header">'.$columnName.'</div><!--end add_detail_content_ele_wrap_ele_header--><div class="add_detail_content_ele_wrap_ele_pic"></div><!--end add_detail_content_ele_wrap_ele_pic--><div class="add_detail_content_ele_wrap_ele_amount">47 Required</div><!--end add_detail_content_ele_wrap_ele_amount--><div class="add_detail_content_ele_wrap_ele_user_amount">You Have 0</div><!--end add_detail_content_ele_wrap_ele_user_amount--></li>';
$final_sl_array[$columnName] = $sl_output;
}
$array_result = implode("", $final_sl_array);
}else{
$hidden_count = $hidden_count;
}else{
$hidden_count = $hidden_count;
}
$output = "";
$output = '<input type="hidden" name="addon_detail_hidden_count" id="addon_detail_hidden_count" class="addon_detail_hidden_count" value="'.$hidden_count.'" />';
include 'connect_to_mysql.php';
echo json_encode(array("total_hidden" => $hidden_count, "output" => $output, "land_required" => $hidden_count, "test_time" => $test_time, "sl_output" => $final_sl_array ));
?>
I guess the question is, can the html code variable being transported be viewed and re-outputed?
EDIT
I have updated my code above, it seems that the first problem, was the foreach loop wasn't handling the right data, i had to shuffle things around and add another array. Because of this i have to put every value in array final_sl_array into a single variable, i have tried to implode this, it worked when i ran it through normal php when the page opens, however, now when i try it through ajax, it is not working, and not returning any result, any ideas why it works for one and not the other?

jquery autcomplete returning source array

I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )

JSON save in Database and load with JQuery

I create a huge JSON-Object and save it in my database. But when I load the "string" and echo it in PHP, I can't access the JSON Object in JQuery. Do I have to consider something if I want to save my JSON Object in a MySQL Database (when I just create the Array and then echo it with "echo json_encode($arr);" it works fine, but I need to save the Object for caching).
{"247":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]},{"248":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]}}
just an excerpt
If I just echo this JSON-Object, everything works fine, but if I load the same string from the database and echo it, it doesn't work.
Update 1: forget to tell that I'm using a TEXT-Field with UTF8_general_ci collation
Update 2: Maybe a little bit more code:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data[247][0]);
}, "json");
return false;
});
}
this loads the script and should alert "This is a question"
<?php
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
echo $output;
?>
this is the script, where I load the database entry with the JSON-Object.
Update 3:
I think I solved the problem. Some break sneaked into my JSON-Object so I do this, before the output:
$output = str_replace("\n", "", $output);
$output = str_replace("\r", "", $output);
$output = str_replace("\r\n", "", $output);
I'd suggest looking at what your javascript is seeing. Instead of asking jQuery to interpret the json for you, have a look at the raw data:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data);
}, "text");
return false;
});
}
For example, if part of the string gets oddly encoded because of the UTF-8, this might cause it to appear.
Once you've done that, if you still can't spot the problem, try this code:
var data1, data2;
function start() {
$(".start").click(function () {
$.post("load_script.php", {src: "db" }, function(data){
data1 = data;
}, "text");
$.post("load_script.php", {src: "echo" }, function(data){
data2 = data;
}, "text");
if (data1 == data2) {
alert("data1 == data2");
}
else {
var len = data1.length < data2.length ? data1.length : data2.length;
for(i=0; i<len; ++i) {
if (data1.charAt(i) != data2.charAt(i)) {
alert("data1 first differs from data2 at character index " + i);
break;
}
}
}
return false;
});
}
And then change the PHP code to either return the data from the database or simply echo it, depending on the post parameters:
<?php
if ($_POST['src'] == 'db')) {
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
}
else {
$output = '{"247":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]},{"248":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]}}';
}
echo $output;
?>
Hope that helps!
I got this to work in a slightly different manner. I've tried to illustrate how this was done.
In Plain English:
use urldecode()
In Commented Code Fragments
$json = $this->getContent($url); // CURL function to get JSON from service
$result = json_decode($json, true); // $result is now an associative array
...
$insert = "INSERT INTO mytable (url, data) ";
$insert .= "VALUES('" . $url . "', '" . urlencode(json_encode($result)) . "') ";
$insert .= "ON DUPLICATE KEY UPDATE url=url";
...
/*
** Figure out when you want to check cache, and then it goes something like this
*/
$sqlSelect = "SELECT * FROM mytable WHERE url='" . $url . "' LIMIT 0,1";
$result = mysql_query($sqlSelect) or die(mysql_error());
$num = mysql_numrows($result);
if ($num>0) {
$row = mysql_fetch_assoc($result);
$cache = json_decode(urldecode($row['data']), true);
}
Hope this is helpful
Maybe you use varchar field and your string just doesn't fit in 255 chars?

Categories