AJAX only saving the first letter of input - javascript

I have an AJAX request which serializes form data and sends it to a database. When teh data is serialised, I see it renders the full text inout, but when it stores it in the database, it only saves the first letter of every word?
For example it will serialize this to be sent:
splashText=Silver Glaze
but the database will save if there is none line:
S
if there are multiple rows in the submitted table data is captured in the database as follows:
row 1 would = S
row 2 would = i
Where as I'm trying to get it as follows:
row 1 would = Silver Glaze
row 2 would = Next option selected in the row and so on...
The serialised data POSTed is as follows (with 2 rows):
job_ref=3123&job_desciption=321&sil_cost=1&sil_cost_price=2.00&sub_total=119.75&item_name%5B%5D=1&item_quantity%5B%5D=1&item_unit%5B%5D=1&item_glass%5B%5D=110&item_splash%5B%5D=20&item_colour%5B%5D=-&item_HQuan%5B%5D=1&item_HDiam%5B%5D=2.25&item_CQuan%5B%5D=1&item_Total%5B%5D=56.25&item_cil_row%5B%5D=0.000001&item_name%5B%5D=1&item_quantity%5B%5D=1&item_unit%5B%5D=1&item_glass%5B%5D=110&item_splash%5B%5D=20&item_colour%5B%5D=-&item_HQuan%5B%5D=1&item_HDiam%5B%5D=7.5&item_CQuan%5B%5D=1&item_Total%5B%5D=61.50&item_cil_row%5B%5D=0.000001&glassText=6mm Toughened Extra Clear6mm Toughened Extra Clear&splashText=Rainbow SparkleRainbow Sparkle&holeText=22mm27mm
The code to serialise the form:
var form_data = $(this).serialize() + '&glassText=' + $('.item_glass').children("option").filter(":selected").text() + '&splashText=' + $('.item_splash').children("option").filter(":selected").text() + '&holeText=' + $('.item_HDiam').children("option").filter(":selected").text();
The + is for getting the text value of the input instead of the value. I think this may be the problem but im not sure how to fix it?
PHP Post:
for($count = 0; $count < count($_POST["item_name"]); $count++)
{
$query = "INSERT INTO tbl_order_items
(order_id, item_name, item_quantity, item_unit,item_glass, item_splash, item_HQuan,item_HDiam,item_CQuan,item_colour,item_total,user_id)
VALUES (:order_id, :item_name, :item_quantity, :item_unit,:item_glass,:item_splash,:item_HQuan,:item_HDiam,:item_CQuan,:item_colour,:item_total,:user_id)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':order_id' => $order_id,
':item_name' => $_POST["item_name"][$count],
':item_quantity' => $_POST["item_quantity"][$count],
':item_unit' => $_POST["item_unit"][$count],
':item_glass' => $_POST["glassText"][$count],
':item_splash' => $_POST["splashText"][$count],
':item_HQuan' => $_POST["item_HQuan"][$count],
':item_HDiam' => $_POST["holeText"][$count],
':item_CQuan' => $_POST["item_CQuan"][$count],
':item_colour' => $_POST["item_colour"][$count],
':item_total' => $_POST["item_Total"][$count],
':user_id' => $user_id
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
It is a dynamic table being saved. Thats what the count is.
To put context on the dynamic table here is a screenshot:
:

Because you don't provide the html code, so I assume the 'Review Quote' button is the submit button. So, try this:
change from
var form_data = $(this).serialize() + '&glassText=' + $('.item_glass').children("option").filter(":selected").text() + '&splashText=' + $('.item_splash').children("option").filter(":selected").text() + '&holeText=' + $('.item_HDiam').children("option").filter(":selected").text()
To:
var glassText = '';
$('.item_glass').each(function(){
glassText+='&glassText[]='+$(this).find(":selected").text().replace(' ','+');
});
var splashText = '';
$('.item_splash').each(function(){
splashText+='&splashText[]='+$(this).find(":selected").text().replace(' ','+');
});
var holeText = '';
$('.item_HDiam').each(function(){
holeText+='&holeText[]='+$(this).find(":selected").text().replace(' ','+');
});
var form_data = $(this).serialize() + glassText + splashText + holeText;

Related

Can't create desired json data and read their values correctly (php, ajax)

I'm making a clothes store and I want to display data in modal when product link is clicked. Each product can have more sizes and each size have its quantity.
This line opens modal (this work fine)
<span>View</span>
The code below sends "id" to fetch_id.php file and displays data in modal
<script type="text/javascript">
$(document).ready(function() {
$('.quick-view-btn').bind('click', function() {
var id=$(this).attr("id");
$.ajax({
url:"fetch_id.php",
cache:false,
data:'id='+id,
dataType: "json",
success:function(data){
var aslika = data['artikli']['artslika']; //get picture
var aime = data['artikli']['artime']; //get name
var acijena = data['artikli']['artcijena']; //get price
var artcode = data['artikli']['artcode']; //get art code
var aopis = data['artikli']['artopis'];
$('.a_slika').attr("src", 'slike/'+aslika);
$('.a_ime').html(aime);
$('.a_cijena').html(acijena+' Kn');
$('.a_artcode').html('šifra: '+artcode);
$('.a_opis').html(aopis);
$('.a_id').attr("href", 'single-product.php?id='+artcode);
}
});
});
});
</script>
Here is my fetch_id.php file
$prid = $_GET['id'];
$active = 1;
if ($stmtart = $mysqli->prepare("SELECT aid, art_code, glkat, kat, ime_a, opis, kolicina, cijena, stara_cijena, ocjena, slika, status, datum, xs, s, m, l, xl, xxl, xxxl FROM artikli WHERE status = ? and aid = ? LIMIT 1")) {
$stmtart->bind_param('ii', $active, $prid );
$stmtart->execute();
$stmtart->store_result();
$stmtart->bind_result($a_id, $aart_code, $a_glkat, $a_kat, $a_ime, $a_opis, $a_kolicina, $a_cijena, $a_scijena, $a_ocjena, $a_slika, $a_status, $a_datum, $a_xs, $a_s, $a_m, $a_l, $a_xl, $a_xxl, $a_xxxl);
$stmtart->fetch();
}
if ($stmtvelicine = $mysqli->prepare("SELECT vid, oznaka, kolicina FROM velicine WHERE artid = ? ORDER BY vid ASC")) {
$stmtvelicine->bind_param('i', $prid );
$stmtvelicine->execute();
$stmtvelicine->store_result();
$stmtvelicine->bind_result($v_id, $v_oznaka, $v_kolicina);
}
$artikli = array("artikli" => array("artslika"=>$a_slika, "artime"=>$a_ime, "artcijena"=>$a_cijena, "artcode"=>$aart_code, "artopis"=>$a_opis));
$counter = 0;
while($stmtvelicine->fetch()) {
$counter = $counter + 1;
$velicine = array('vel'.$counter => $v_oznaka);
$komada = array('kom'.$counter => $v_kolicina);
array_push($artikli, $velicine);
array_push($artikli, $komada);
}
$json = json_encode($artikli);
echo $json;
The result I'm receiving is in this format...
{"artikli":{"artslika":"sn.jpg","artime":"Dress","artcijena":"129.56","artcode":"PD1001","artopis":"Default Description"},"0":{"vel1":"XS"},"1":{"kom1":5},"2":{"vel2":"L"},"3":{"kom2":2},"4":{"vel3":"XL"},"5":{"kom3":4}}
The problem is that my "while loop" creates numbers as keys so if some product have many sizes it will have many unknown keys.
Can you help me to read their values with ajax? Is there a better way to solve this?
Thank you very much,
Ivan.

Yii 2: Add prompt text field on clicking on GridView

I've created action onClick in GridView and it redirects me to an action in controller.
Code in Index.php:
},
'rowOptions' => function ($model, $key, $index, $grid) {
return ['id' => $model['id'], 'onclick' => 'var myid=this.id; var enteredValue = prompt("Please enter a number");
window.location.href = "index.php?r=patientservices%2Fpassing" + "&id=myid, " + enteredValue; '];
},
In my Controller code:
public function actionPassing($id,$price)
{
$ser= $this->findModel($id);
$model = new Receipts();
$countclinic=Receipts::find()
->where(['patient_services_id'=>$id])
->count();
if ($countclinic== 0) {
$model->patient_id=$ser->patient_id;
$model->price=$price; // the price that i need to pass
$model->doctor_id=$ser->doctor_id;
$model->patient_services_id=$ser->id;
$model->reg_date=DATE('y-m-d h:m:s');
$model->description='دفعة تحت الحساب';
$model->userin = \Yii::$app->user->identity->id ;
$model->save();
$models = $this->findModel($id);
$models->state=2;
$models->save();
JS Code :
$this->registerJs("
$('.custom_button').on('click', function() {
alert(id);
var enteredValue = prompt('Please enter a number');
if (enteredValue != null) {
window.location.href = 'index.php?r=patientservices%2Fpassing' + '&id=, ' + enteredValue;
}
});
");
What I need is:
When the user clicks on the Row in GridView a prompt text appears for the user and the number inserted in the prompt text is passed with the ID to controller to use it there but the js code pass the id as a character not like number
$model->price=$ser->price;
Here's how you can do it:
Instead of using link, use # as a link since you don't want to redirect user just yet.
After user clicks on button, you want to "summon" a prompt. This can be achieved by JavaScript/jQuery only.
Inside the JavaScript/jQuery code you can insert PHP code, too, and form an URL.
For example (in GridView):
'buttons' => [
'passing' => function () {
return Html::a('Content', '#', [
'class' => 'btn btn-primary custom_button',
'title' => 'تسجيل القيمة كـ إيصال',
]);
},
],
Then at the end of file:
$this->registerJs("
$('.custom_button').on('click', function() {
var enteredValue = prompt('Please enter a number');
if (enteredValue != null) {
window.location.href = '".$url."' + '&id= ' + enteredValue;
}
});
");
Worth to note I have included a class custom_button since we want to know if the button user clicked is the correct one, not any.

jQuery form, exist checking

So i am creating a simple form that checks whether or not the value that the user is inputting exists or not in my DB using jQuery. Everything up until now is working so far however i find myself stuck at this next part.
To easily explain i will just show an example of what i am trying to achieve.
For this example i will be "weeden"
weeden has an ID of 255 in the company table of my database.
If the user types in "weeden" into the client field
To the right of the client field (on the web form), the text "weeden is unavailable" will appear
what i would like to have happen instead is this: "ID 255 is unavailable"
Here is the relevant code.
HTML FORM
<form action="addrecord.php" method="post" autocomplete="off"/>
<div class="form-field">
<label for="client">Client: </label>
<input type="text" name="client" id="client" class="check-exists" data-type="client" placeholder="#">
<span class="check-exists-feedback" data-type="client"></span>
</div>
jQuery Function
$.fn.existsChecker = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function(){
var self = $(this),
selfType = self.data('type'),
selfValue,
feedback = $('.check-exists-feedback[data-type=' + selfType + ']');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()){
selfValue = self.val();
if(selfValue.length >= 1){
$.ajax({
url: 'check.php',
type: 'get',
dataType: 'json',
data: {
type: selfType,
value: selfValue
},
success: function(data){
if(data.exists !== undefined){
if (data.exists === true){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is available');
}
}
},
error: function(){
}
});
}
}
}, 1000);
}
});
});
};
Check.php
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,
array('client')
)
){
switch($type){
case 'client':
$check = $db->prepare("
SELECT COUNT(*) AS count
FROM company
WHERE name = :value
");
break;
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
Any help/suggestions would be greatly appreciated. I consider myself a beginner, this is my first time working on a web project.
Just to clarify ahead of time, there are many other input fields on the same webform such as: email, date, first, last, etc.
I hope my question was clear enough. Thank you
You have to change your Query to something like this:
$check = $db->prepare("
SELECT id, COUNT(*) AS count
FROM company
WHERE name = :value
");
I assume that your primary key field on the company-table is named id.
And finally store the id in the output-Array
$result = $check->fetchObject();
$output['exists'] = $result->count ? true: false;
$output['id'] = $result->id;
Then you can output the id like so:
if (data.exists === true){
feedback.text('ID ' + data.id + ' is unavailable');
}
You can handle everything in query
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,array('client'))){
switch($type){
case 'client':
$check = $db->prepare("
SELECT (CASE WHEN(COUNT(id)>0) THEN id ELSE FALSE END) AS count
FROM company WHERE name = :value ");
break;
}
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
}
In Ajax success
if(data.exists !== undefined){
if (!data.exists){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is already taken.');
}
}

Converting a html table into a json object and sending it to a php page ,the table has a input field

i have got a html table which is dynamically created by php code taking db data.
the table's last field is a input field for entering a number.
the data from the table has to be sent to another php page for sql insert.
i am new to xml and ajax pls help me out with the above javascript code.
<script>
$(document).ready("enter").click(function(event){
event.preventDefault();
var elementTable = document.getElementById("form_table");
var jObject = [];
for (var i = 0; i < elementTable.rows.length; i++)
{
jObject[i] = [];
jObject[i][0] = elementTable.rows[i].cells[1].innerHTML;
jObject[i][1] = elementTable.rows[i].cells[2].innerHTML;//data from input field
}
console.log(jObject);
var JSONObject = encodeURIComponent(
JSON.stringify(jObject));//GETTING ERROR HERE
var url = "submit.php";
var requestData = "&dtable=" + JSONObject;
var XMLHttpRequestObj = FileResort.Utils.createRequest();
XMLHttpRequestObj.open("POST", url, true);
XMLHttpRequestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XMLHttpRequestObj.send(requestData);
});
</script>
as long as you are using JQuery, adapt this jsfiddle example
$("button").click(function(event){
event.preventDefault();
var tableArray = [];
$("table tbody tr:has(td)").each(function(index,element){
tableArray.push([
$(this).find("td:eq(1)").html(),
$(this).find("td:eq(2)").html()
]);
});
console.log(tableArray);
$("div").text(encodeURIComponent(
JSON.stringify(tableArray)
));
return false;
});
which is mostly what you want for the table serialization minus the ajax call ( which I think should be a POST, but that is my personal opinion )

Posting a JSON string with multiple values to ext js panel

I am working on an element of an application I am developing. I have a small web app dedicated to keep track of clients for a business. Currently my capability is pretty limited. I store the note along with other attributes in the clients table. I decided to try and make it a bit better by adding a note table and updating an ext js panel with the notes.
Everything works if I only have one note in my notes query.
Otherwise I receive this error.
SyntaxError: invalid property id
..._date":"2013-10-08","note_body":"abcd"},{"username":"rcox","bdev_firstname":"Tre...
This is the PHP I am using.
case 'note':
$userid = $_REQUEST['clientID'];
$query = $dbh->prepare("SELECT a.username, b.bdev_firstname, b.bdev_lastname, n.note_date, n.note_body FROM admin a, bdevs b, clients c, notes n WHERE c.clientID=".$userid.";");
$query->execute();
while($cli = $query->fetch()) {
$json = '{"username":"'.$cli['username'].'","bdev_firstname":"'.$cli['bdev_firstname'].'","bdev_lastname":"'.$cli['bdev_lastname'].'","note_date":"'.$cli['note_date'].'","note_body":"'.$cli['note_body'].'"},';
$note .= $json;
}
$note = trim($note, ',');
echo '{success: true, data:'.$note.'}';
break;
This is my ext js function.
function getNote(){
var selectedNote = userGrid.getSelectionModel().getSelected();
Ext.Ajax.request({
url: 'inc/template.php',
params: {list: 'note',
clientID: selectedNote.get('clientID')
},
method: 'POST',
success: function(f,a){
var jsonData = Ext.util.JSON.decode(f.responseText);
if(jsonData.success == true)
{
var username = jsonData.data.username;
var bdev_firstname = jsonData.data.bdev_firstname;
var bdev_lastname = jsonData.data.bdev_lastname;
var note_date = jsonData.data.note_date;
var note_body = jsonData.data.note_body;
RightPanel.update('<b>Admin:</b> ' + username + '<br/><b>Buissiness Dev Rep:</b> ' + bdev_firstname + bdev_lastname + '<br/><b>Note Date:</b> ' + note_date + ' <br/>----------<br/> ' + note_body);
}
else
{
RightPanel.update('Access Denied');
}
},
failure: function(f,a){
Ext.Msg.alert("Error", "Access Denied");
}
});
}
This has been answered below. For more troubleshooting on this topic you can visit my question on Sencha Forums. http://www.sencha.com/forum/showthread.php?273478-MOVED-POST-Posting-a-JSON-array-with-multiple-values-to-ext-js-panel&p=1002545#post1002545
What's the point of using json if you actually don't use it.
case 'note':
$userid = $_REQUEST['clientID'];
$query = $dbh->prepare("SELECT a.username, b.bdev_firstname, b.bdev_lastname, n.note_date, n.note_body FROM admin a, bdevs b, clients c, notes n WHERE c.clientID = ?");
$query->execute(array($userid));
$response = json_encode(array('success'=> true, data => $query->fetchAll(PDO::FETCH_ASSOC)));
echo $response;
break;
And then ext.js part where your error lies - if data is an array, you need to iterate over it, before you can access associative fields, right?
if(jsonData.success == true)
{
var i, item;
for( i = 0; i < jsonData.data.length; i++; ) {
item = jsonData.data[i];
RightPanel.update('<b>Admin:</b> ' + item.username + '<br/><b>Buissiness Dev Rep:</b> ' + item.bdev_firstname+" "+item.bdev_lastname + '<br/><b>Note Date:</b> ' + item.note_date + ' <br/>----------<br/> ' + item.note_body);
}
}

Categories