created input form by json doesn't show in $_POST - php

I use json for retrieving data from database. When I click on an option it retrieves some input form. But when I print $_POST it doesn't show those inputs.
print_r($_POST); // print all except input fields which retrieved from json
My php code:
foreach($html->result() as $row){
$html_input .= '<input name="' . $row->Feature_Eng_Name . '" type="text" style="color:#888" placeholder="'. $row->Feature_Name . '">';
$html_input .= "<br>";
}
$result = array('status' => 'ok', 'content' => $html_input);
echo json_encode($result);
Script:
$(document).ready(function(){
$("#maintype").click(function(){
var base_url = "<?php echo base_url(); ?>" ;
var isOption = $("option:selected").val();
var cat_id = isOption;
if(isOption == ""){
$("#feature_ajax").html("");
}
else{
$.post(base_url + 'administrator/submit_product/ajax_get_feature_by_cat', {cat_id}, function(data){
if(data.status == 'ok'){
//alert("yes");
$('#feature_ajax').html(data.content);
}
else{
$('#feature_ajax').html("");
}
}, "json");
}
});
});

ok after inspecting your code, the problem was your FORM tags. They were being placed in the wrong places. Make sure if you open a form tag inside a div, you need to close it inside that same div, not outside or the DOM will break it.

Related

How to pass php array to ajax function

So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.
public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if($stmt->rowCount()>0){
foreach($results as $row){
echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';
//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}
Here is my Ajax call to send the info to my php file
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Then here is the php file that handles the call.
if(isset($_POST['upVoteIncrement'])){
$upVoteIncrement = $_POST['upVoteIncrement'];
$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();
$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}
Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!
If your using a loop to populate the row id, which it looks like you are here are your problems.
The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.
I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.
See if this helps:
PHP:
if(isset($_SESSION['user_session'])){
echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';
}
JS:
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Hope it helps!
I also want to point out that in the code below:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
echo $up;
exit();
}
}
You are exiting the script on the first iteration of the loop and you will only ever get one result back.
If you need to return an array of data it should look like this:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit();
}
}
echo json_encode($results);
You will then need to set your datatype to json instead of html.
The response in your ajax will now be an array. To see the array:
success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.
function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();
You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:
<input onclick="upVoteIncrementValue" />
Then your handler:
function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();
Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.

While loop Mysql updating checkboxes where to start

I have a question how can I update the database if person unchecks or check a checkbox and update the boolean field
in mysql? For days stuck with this problem, because problem I don't know how to make a form or check if
it is validate inside of a while loop here is my code:
<?
$result= mysql_query("SELECT * FROM cars");
$counter = 1;
while($row = mysql_fetch_array($result)) {
echo '<tr>
<td>' . $counter++ . '</td>
<td><input type="checkbox"';
if ($row['show'] == true) {
echo 'checked></td>';
} else {
echo 'unchecked></td>';
}
echo '<td><img src="../xml/'.$row['cars_id'].'-1.JPG" width="120px"></td>';
echo "<td><h3> ", $row['brand']," " . $row['model'], " " . $row['type'],
" € " . $row['price'], " </h3></td>";
echo '</tr>';
}
?>
p.s. I am aware of the mysql to mysqli or pdo but it is a HUGE script...
Oh! No issue here is the solution:
Try using jquery and ajax. For example.
if ( $("#chkbx").prop('checked') == true) {
// do ajax call to update the database
} else {
// do anything if check box is unchecked
}
I am not writing the ajax call just see the jquery ajax manual. If you face any problem come back.
See the above code will create a event listener in the DOM so that when the check box is checked a event should fire.
Now I am extending my code to show you a ajax call.
if ( $("#chkbx").prop('checked') == true) {
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { name: "test"} // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}
Now in the php file do the updating part of database or anything you want. The done function will show the msg you returned if the php file execute properly. There are numerous functions in ajax that you can use.Also try to use jquery it's handy and easy to use.
Thank you so much, now I only have to focus on how database works in Ajax
This is what I added and with this I can echo out that it does work now what rest is change the boolean value row['show']
<script type="text/javascript">
function change_checkbox(el){
if(el.checked){
alert("On");
}else{
alert("Off");
}
}
I got pretty far that all is working except for 1 particulair thing.
The problem what I now face is that I cannot send the DATA ID's from the checkbox to the test.php page how can I do this correct this is what I came up with so far:
<?
$result= mysql_query("SELECT * FROM cars");
$counter = 1;
while($row = mysql_fetch_array($result)){
echo '<tr>
<td>' . $counter++ . '</td>
<td><input id="'.$row['cars_id'].'" onchange="change_checkbox(this)" type="checkbox"';
if ($row['toon'] == true){
echo 'checked></td>';
}else
{
echo 'unchecked></td>';
}
echo '<td><img src="../xml/'.$row['cars_id'].'-1.JPG" width="120px"></td>';
echo "<td><h3> ", $row['brand']," " . $row['model'], " " . $row['type'], " € " . $row['price'], " </h3></td>";
echo '</tr>';
}
?>
</tbody>
</table>
</section>
<script type="text/javascript">
function change_checkbox(el){
var id = null;
if(el.checked){
alert("On");
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { id: id } // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}else{
alert("Off");
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { name: "test"} // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}
}

JQuery Ajax - Dynamic created input elements want to be able to upload with Ajax submit

I have a jquery file that dynamically creates input elements. One of the elements is for uploading an image file. When the user clicks save it will add it to a database via ajax. I want the ability to be able to upload on the same save click. I am not able to get the file element to submit.
Below is my jquery:
var trcopy;
var editing = 0;
var tdediting = 0;
var editingtrid = 0;
var editingtdcol = 0;
var inputs = ':checked,:selected,:text,textarea,select,:hidden,:checkbox,:file';
var notHidden = ':checked,:selected,:text,textarea,select,:file';
$(document).ready(function(){
// set images for edit and delete
$(".eimage").attr("src",editImage);
$(".dimage").attr("src",deleteImage);
// init table
blankrow = '<tr valign="top" class="inputform"><td></td>';
for(i=0;i<columns.length;i++){
// Create input element as per the definition
//First elements in array are hidden fields
if(columns[i] == '_fk_PO_Req_ID'){
input = createInput(i,'');
blankrow += input;
}else{
input = createInput(i,'');
blankrow += '<td class="ajaxReq" style="text- align:center;">'+input+'</td>';
}
}
blankrow += '<td><img src="'+saveImage+'"></td></tr>';
// append blank row at the end of table
$("."+table).append(blankrow);
// Add new record
$("."+savebutton).on("click",function(){
// alert('save clicked');
var validation = 0;
var $inputs =
$(document).find("."+table).find(inputs).filter(function() {
// check if input element is blank ??
//if($.trim( this.value ) == ""){
// $(this).addClass("error");
// validation = 0;
// }else{
// $(this).addClass("success");
// }
validation = 1;
return $.trim( this.value );
});
var array = $inputs.map(function(){
console.log(this.value);
console.log(this);
return this.value;
}).get();
var serialized = $inputs.serialize();
alert(serialized);
if(validation == 1){
ajax(serialized,"save");
}
});
createInput = function(i,str){
str = typeof str !== 'undefined' ? str : null;
//alert(str);
if(inputType[i] == "text"){
input = '<input class="input-small" type='+inputType[i]+' name="'+columns[i]+'" placeholder="'+placeholder[i]+'" value="'+str+'" >';
}else if(inputType[i] == "file"){
input = '<input class="input-small" type='+inputType[i]+' name="new_receipt" placeholder="'+placeholder[i]+'" value="'+str+'" >';
}else if(inputType[i] == "textarea"){
input = '<textarea name="'+columns[i]+'" placeholder="'+placeholder[i]+'">'+str+'</textarea>';
}else if(inputType[i] == "hidden"){
input = '<input type="'+inputType[i]+'" name="'+columns[i]+'" value="'+hiddenVal[i]+'" >';
}else if(inputType[i] == "checkbox"){
input = '<input type="'+inputType[i]+'" name="'+columns[i]+'" value="'+str+'" >';
}else if(inputType[i] == "select"){
input = '<select class="input-medium" name="'+columns[i]+'">';
for(i=0;i<selectOpt.length;i++){
// console.log(selectOpt[i]);
selected = "";
if(str == selectOpt[i])
selected = "selected";
input += '<option value="'+selectOpt[i]+'" '+selected+'>'+selectOpt[i]+'</option>';
}
input += '</select>';
}
return input;
}
ajax = function (params,action){
// alert(params);
// alert(action);
$.ajax({
type: "POST",
url: "ajax.php",
data : params+"&action="+action,
dataType: "json",
success: function(response){
switch(action){
case "save":
var seclastRow = $("."+table+" tr").length;
// alert(response.success);
if(response.success == 1){
var html = "";
html += "<td>"+parseInt(seclastRow - 1)+"</td>";
for(i=0;i<columns.length;i++){
if(columns[i] == '_fk_PO_Req_ID'){
html += '';
}else{
html +='<td style="text-align:center" class="'+columns[i]+'">'+response[columns[i]]+'</td>';
}
}
html += '<td><img src="'+editImage+'"> <img src="'+deleteImage+'"></td>';
// Append new row as a second last row of a table
$("."+table+" tr").last().before('<tr id="'+response.id+'">'+html+'</tr>');
if(effect == "slide"){
// Little hack to animate TR element smoothly, wrap it in div and replace then again replace with td and tr's ;)
$("."+table+" tr:nth-child("+seclastRow+")").find('td')
.wrapInner('<div style="display: none;" />')
.parent()
.find('td > div')
.slideDown(700, function(){
var $set = $(this);
$set.replaceWith($set.contents());
});
}
else if(effect == "flash"){
$("."+table+" tr:nth-child("+seclastRow+")").effect("highlight",{color: '#acfdaa'},100);
}else
$("."+table+" tr:nth-child("+seclastRow+")").effect("highlight",{color: '#acfdaa'},1000);
// Blank input fields
$(document).find("."+table).find(inputs).filter(function() {
// check if input element is blank ??
this.value = "";
$(this).removeClass("success").removeClass("error");
});
}
break;
}
},
error: function(){
alert("Unexpected error, Please try again");
}
});
}
You cannot upload a file like a regular form field when you use ajax.
There are two solutions for that:
Use FormData. This will work in modern browswers;
Use a jQuery file upload plugin. This is only necessary if you need to support browsers that do not support FormData: Internet Explorer 9 and below.
You can find a nice explanation of the use of FormData here on SO: How to use FormData for ajax file upload

Does not save html select data from ajax query to session

I'm creating a form where the users have to select their country and city from a select field, which is dynamically updated corresponding to the actual country selected. However when the form is submitted everything is getting saved successfully except the city.
I'm using jquery select2 and jquery validation plugin, I think those could cause the problem.
Here is the main code:
$('#country').select2().change(function() {
$("#city").select2('data', null);
$.ajax({
type: 'post',
url: 'search_city.php',
data: 'country=' + $(this).val(),
dataType: 'html',
success: function(response) {
$('#city').html(response);
}
});
});
and
<label>* City:</label>
<select id="city" name="property_city" required>
<option></option>
</select>
and this is search_city.php
echo '<option></option>';
while($city = mysqli_fetch_object($cities)) {
if($_SESSION['property_city'] == $city->id) {
echo '<option selected value="'.$city->id.'">'.$city->name.'</option>';
} else {
echo '<option value="'.$city->id.'">'.$city->name.'</option>';
}
}
When the form is submitted a validation php runs where I save the data to session variables. There are more inputs, not just the country and the city, and they are saved successfully except the city I mentioned.
I can't figure out what the problem is. I did't include all the code, maybe something else could cause the problem, however if someone could find it here I would be relieved.
You need to write,
$html = '<option value=""></option>';
while($city = mysqli_fetch_object($cities)) {
if($_SESSION['property_city'] == $city->id) {
$html .= '<option selected value="'.$city->id.'">'.$city->name.'</option>';
} else {
$html .= '<option value="'.$city->id.'">'.$city->name.'</option>';
}
}
echo $html;

how to get data to javascript from php using json_encode?

I am trying to map traceroutes to google maps.
I have an array in php with traceroute data as
$c=ip,latitude,longitude, 2nd ip, its latitude, longitude, ....target ip, its lat, its lng
I used json_encode($c, JSON_FORCE_OBJECT) and saved the file
Now, how do I access this using javascript, by directly equating it to new JS object?
earlier I used to have a data format like this on harddrive
var data12 = {
"route":[
{
"ip": "some ip",
"longitude": "some lng",
"latitude": "some lat",
.....
and in my javascript it was used as
data=data12.route;
and then simply acces the members as data[1].latitude
I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.
For parsing JSON, simply do
var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );
You can now access everything easily:
alert ( obj.name );
Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval () method.
Edit: To get data from the server side to the client side, there are two possibilities:
1.) Use an AJAX request (quite simple with jQuery):
$.ajax ( {
url: "yourscript.php",
dataType: "json",
success: function ( data, textStatus, jqXHR ) {
// process the data, you only need the "data" argument
// jQuery will automatically parse the JSON for you!
}
} );
2.) Write the JSON object into the Javascript source code at page generation:
<?php
$json = json_encode ( $your_array, JSON_FORCE_OBJECT );
?>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );
//]]>
</script>
I know this is old, but I recently found myself searching for this. None of the answers here worked for my case, because my values had quotes in them. The idea here is to base64 encode the array before echo'ing to the page. That way the quotes don't conflict.
< ?php
$names = ['first' => "some'name"];
?>
var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
console.log(names['first']);
I could get the JSON array by using PHP's json_encode() from backend like this example:
<!doctype html>
<html>
<script type="text/javascript">
var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
console.log(json[1]);
console.log(json.abc);
</script>
</html>
No quotation marks means an eval() of whatever was printed out. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.
no need for jquery, just:
var array= <?php echo json_encode($array); ?>;
console.log(array->foo);
we have to display the json encode format in javascript , by using below one:
var responseNew = JSON.parse(' {"name" : "John"} ' );
alert(responseNew['name']);
This function works for you I guess:
function json_encode4js($data) {
$result = '{';
$separator = '';
$count = 0;
foreach ($data as $key => $val) {
$result .= $separator . $key . ':';
if (is_array($val)){
$result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
continue;
}
if (is_int($val)) {
$result .= $val;
} elseif (is_string($val)) {
$result .= '"' . str_replace('"', '\"', $val) . '"';
} elseif (is_bool($val)) {
$result .= $val ? 'true' : 'false';
} elseif (is_null($val)) {
$result .= 'null';
} else {
$result .= $val;
}
$separator = ', ';
$count++;
}
$result .= '}';
return $result;
}
$a = array(
"string"=>'text',
'jsobj'=>[
"string"=>'text',
'jsobj'=>'text2',
"bool"=>false
],
"bool"=>false);
var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}"
var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"
HTML
<select name="sub" id="subcat" class="form-control" required="required">
</select>
PHP
$this->load->model('MainModel');
$subvalue = $this->MainModel->loadSubData($var);
echo json_encode($subvalue);
//if MVC
// or you can just output your SQLi data to json_encode()
JS
$("#maincat").change(function(){
var status = this.value;
$.ajax({
type: 'POST',
url: 'home/subcat/'+status,
success: function(data){
var option = '';
var obj = JSON.parse(data);
if(obj.length > 0){
for (var i=0;i<obj.length;i++){
option += '<option value="'+ obj[i].id + '">' + obj[i].name + '</option>';
}
//Now populate the second dropdown i.e "Sub Category"
$('#subcat').children("option").remove();
$('#subcat').append(option);
}else{
option = '<option value="">No Sub Category Found</option>';
$('#subcat').children("option").remove();
$('#subcat').append(option);
}
},
error: function(){
alert('failure');
}
});

Categories