Retrieve Result from Ajax Process - javascript

I need a way of retrieving data from a processing script into a Request page using Ajax, PHP. The code below shows this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 13 of the JSON data
var data4=JSON.parse(data4);
Please, note that I have search but have not been able to get solution. So, I thought maybe there is a way of passing the result to the requesting page without using json_encode.
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select.partno").change(function() {
var selectedCustomer = $(".partno option:selected").val();
$.ajax({
type: "POST",
url: "process-grpid.php",
dataType: "json",
data: {
custid: selectedCustomer
}
}).done(function(data4) {
var data4 = JSON.parse(data4); //Error Area
//using php-mysql before
$("#desc").html(data4.ref);
$("#purch").html(data4.lprice);
});
});
});
</script>
<form>
<table>
<tr>
<th>Item Code/Part NO:</th>
<?php
include("db_connection.php");
$s = mysqli_query($connection,"SELECT * FROM tab_stock ORDER BY itemName ASC");?>
<td>
<select name="partno" class="partno">
<option>Select PartNo</option>
<option value="N/A">N/A</option>
<?php while($rw = mysqli_fetch_array($s)){ ?>
<option value="<?php echo $rw['itemName'];?>">
<?php echo $rw['itemName'];?>
</option>
<?php };?>
</select>
</td>
<th>Description:</th>
<td id="desc"></td>
</tr>
<tr>
<th>Last Purchase Price:</th>
<td id="purch"></td>
</tr>
</table>
</form>
process-grpid.php (Processing Script)
<?php
if (isset($_POST["custid"])) {
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$partid = $_POST["custid"];
if ($partid !== 'Select PartNo') {
$gets = "SELECT * FROM tab_stock WHERE itemName='" . $partid . "'";
$get = mysqli_query($connection, $gets);
$row = mysqli_fetch_array($get);
$desc = $row['description'];
$lprice = $row['Rate'];
if ($partid == 'N/A') {
$res["sta"] = 0;
$res["ref"] = "<input type='text' class='desc' name='descr' size='50' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' required='required'/>";
} else {
$res["sta"] = 1;
$res["ref"] = "<input type='text' value='$desc' class='desc' name='descr' size='50' readonly='readonly' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' value='$lprice' readonly='readonly' required='required'/>";
}
echo json_encode($res);
}
}
?>
When I run this Application, it shows an error of SyntaxError: JSON.parse: unexpected character at line 1 column 13 of the JSON data
var data4=JSON.parse(data4)
But when checked with Firebug, in the HTML and RESPONSE TAB, it shows the expected result. Question, what alternative way of getting result from a processing script to the requesting page, withput uisng json_encode and JSON.parse(response)?

Try removing
dataType: "json"
of the call ajax
Update:
If the configuration is dataType: json, you'll get a javascript object is no longer necessary JSON.parse

Try not using the JSON.parse at all ... as you get a native JavaScript Object back, not a JSON String ...

I took your code and made some tests. Next code works for me:
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
var selectedCustomer = 1; // DATA FOR PHP.
$.ajax( { type : "POST",
url : "test.php",
data : { "custid" : selectedCustomer }, // DATA FOR PHP.
success: function ( data4 ) {
var data4 = JSON.parse( data4 );
alert( data4.custid );
alert( data4.sta );
alert( data4.ref );
alert( data4.lprice );
$("#desc").html( data4.ref ); // <TD> IN <BODY>.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
<button onclick="myAjax()">echo hello</button>
<table>
<tr>
<td id="desc"></td>
</tr>
</table>
</body>
</html>
test.php
<?php
if ( isset( $_POST[ "custid" ] ) )
{ $res = array();
$res["custid"] = $_POST[ "custid" ];
$res["sta"] = 2;
$res["ref"] = "<input type='text' class='desc' name='descr' size='50' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' required='required'/>";
echo json_encode( $res );
}
?>
Notice I deleted the ajax line dataType : "json",, because as soon as I include it this code throws an error. Copy-paste previous codes in two files called "test.html" and "text.php", they work fine.

Instead of
echo json_encode($res);
Use:
echo json_encode(array('res' => $res));
And instead of:
var data4 = JSON.parse(data4);
Use:
var d = data4.res;
And than use "d" like an array. Here is the JS code I am trying to tell you:
$(document).ready(function() {
$("select.partno").change(function() {
var selectedCustomer = $(".partno option:selected").val();
$.ajax({
type: "POST",
url: "process-grpid.php",
dataType: "json",
data: {custid: selectedCustomer}
}).done(function(data4) {
var d = data4.res;
$("#desc").html(d['ref']);
$("#purch").html(d['lprice']);
});
});
});
If still there is an error, it is probably in the usage of "d" and you can change d['ref'] to d[1] and d['lprice'] to d[2].
I see that there is also a mistake when trying to concatenate $desc and $lprice to the input strings.
$res["ref"] = "<input type='text' value='" . $desc. "' class='desc' name='descr' size='50' readonly='readonly' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' value='" . $lprice . "' readonly='readonly' required='required'/>";
And a plus... if you use these variables only if $partid != 'N/A', why don't you move the query to inside the else statment? Doing this, you avoid to execute the query all the time.
if ($partid !== 'Select PartNo') {
if ($partid == 'N/A') {
$res["sta"] = 0;
$res["ref"] = "<input type='text' class='desc' name='descr' size='50' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' required='required'/>";
} else {
$gets = "SELECT * FROM tab_stock WHERE itemName='" . $partid . "'";
$get = mysqli_query($connection, $gets);
$row = mysqli_fetch_array($get);
$res["sta"] = 1;
$res["ref"] = "<input type='text' value='" . $row['description'] . "' class='desc' name='descr' size='50' readonly='readonly' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' value='" . $row['Rate'] . "' readonly='readonly' required='required'/>";
}
echo json_encode($res);
}

Related

POST submit to mysql using php the value from append javascript

I'm trying to POST submit the data to mysql using php from append javascript.
Here's the modal where data come from append which is in php.
<tr onload="calculate()">
<?php
foreach ($conn->query("SELECT * FROM panapricelist") as $info){
echo "<td><input type='checkbox' id='promotitle' name='check' value='".$info['ProductId']."' ></td>";
echo "<td><textarea rows='4' cols='7' maxlength='60' name='pcode' class='pcode' id='ProductCode' disabled>".$info['ProductCode']."</textarea></td>";
echo "<td><br><textarea rows='5' cols='40' maxlength='50' name='puse' class='productuse' id='productuse' disabled>".$info['ProductUse']." </textarea></td>";
echo "<td><br><textarea rows='4' cols='50' maxlength='50' name='pdesc' class='description' id='productDesc' disabled>".$info['ProductDesc']."</textarea></td>";
echo "<td id='msrp'><textarea rows='4' cols='10' maxlength='50' name='Msrp' class='msrp' id='productMsrp' disabled>".$info['Msrp']."</textarea></td>";
echo "<td style='width: 10%;'><textarea rows='4' cols='10' name='cost' maxlength='50' class='cost' id='cost' disabled>".$info['DealerPhp']."</textarea></td></tr>";
}
?>
</tbody>
Here's the append js from modal to table.
$(document).ready(function() {
$("#button_add").click(function() {
var favorite = [];
$.each($("input[name='check']:checked").each( function() {
// favorite.push($(this).val());
var getRow = $(this).parents('tr'); //variable for the entire row
var value = (getRow.find('td:eq(1)').html()); // Product Code
var value1 = (getRow.find('td:eq(2)').html()); // for Suggested Product Use
var value2 = (getRow.find('td:eq(3)').html()); // for product Description
var value3 = (getRow.find('td:eq(4)').html()); // for MSRP PHP
var value4 = (getRow.find('td:eq(5)').html()); // for Dealer PHP
var value5 = (getRow.find('td:eq(0)').html()); // for Dealer PHP
$('#item-row').append('<tr><td class="item-name"><textarea value="'+ value +'</textarea></td><td class="item-name"><textarea class="check" name="check[]" value= "' + value1 + ' </textarea> </td><td class="item-name"><textarea value= "' + value2 +' </textarea></td><td class="item-name"><textarea value= "' + value3 + ' </textarea> </td><td><textarea name="Msrp" value="' + value4 + '</textarea></td><td class="item-name"><textarea class="qty" id="qty" name="qty[]"> </textarea></td><td class="item-name"><textarea id="price" class="price" name="price[]" disabled></textarea></td></tr>');
}));
});
});
Questions is. how can i POST submit to mysql using PHP PDO the value come from append javascript??
You'll need to put any input data inside of a form, then create a PHP script that handles the POST request and INSERTS the data into your MySQL database.
Your form tag should look something like this:
<form class="post-form" action="script_that_handles_post.php" method="post">
So, you'll want to use $_POST['']. For example, the name in your first table row is name="check", you'll use $_POST['name'] to get the value of that field. Do that for each field that you want to store. Preferably, you should store each of those in their own variables or an array.
Then, for your AJAX you'll have to include the library somehow. If you aren't already, put this in your footer below the jquery source:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
Now you can add your AJAX POST request. Here's some code that should do it:
$(".post-form").submit(function (event) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url:$form.attr('action'),
type:'POST',
data: serializedData
});
request.fail(function (jqXHR, errorThrown){
console.error(
"Error: " + errorThrown
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
What this code is doing is taking the action path of your form and posting the data from the inputs of the fields there.
I hope this helps.

PHP and jQuery insert into MySQL

I am trying to insert data into mySQL using jQuery. The code does not return any error and no any result as well. Please help me to sort this out.
$(document).ready(function() {
$("#submit").click(function() {
var data;
var eid = 101;
data = "eid=" + eid;
for (i = 0; i <= 10; i++) {
data += "&Text_" + (i + 1) + "=" + $("#Text_" + (i + 1)).val();
data += "&Amount_" + (i + 1) + "=" + $("#Amount_" + (i + 1)).val();
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="Amount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="Amount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="Amount[]" id="Amount_3" /></td>
</tr>
I am adding the process.php snippet also in order to know where is the error.
process.php
$eid=$_POST['eid'];
$length = sizeof($_POST["Text"]);
$i=1;
while ($i<=$length){
if(!empty($_POST['Text'][$i])) {
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$msg = array('status' => !$error, 'msg' => 'Failed! updation-1');
if(!$error) {
$sql = "UPDATE TblCustom SET Text='" . $Text . "', Amount='" . $Amount ."' WHERE ID='$eid'";
$status = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$msg = array('error' => $error, 'msg' => 'Success! updation : '. $sql );
}
else {
$msg = array('error' => $error, 'msg' => 'Failed! updation-2 ');
}
}
echo json_encode($msg);
}
Thanks
You have 3 problems.
Problem number one and two are related. Firstly, you are specifying dataType: 'json', but you are passing your data in application/x-www-form-urlencoded format. Secondly, your php script expects data to be in the following format:
$_POST = [
'Text' => ['text_1', 'text_2', 'text_3'],
'Amount' => ['amount_1', 'amount_2', 'amount_3']
];
While your data looks something like this:
$_POST = [
'Text_1' => 'text_1',
'Text_2' => 'text_2'
// and so on
];
The single fix to this problem is as follows:
$(document).ready(function() {
$("#submit").click(function() {
const data = {
// we are grabbing all inputs with name=Text[]
// and mapping them to array containing their values.
// The `...` is a spread operator introduced
// with the new js standard (ES6),
// that converts jQuery object to regular javascript
// array of inputs.
// you can do all of this with a for loop, but the map way
// is prefered
Text: [...$('input[name="Text[]"]')].map(input => input.value),
Amount: [...$('input[name="Amount[]"]')].map(input => input.value)
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
The third problem is that have created an SQL Injection vulnerability. That means some bad guy can inject and SQL statement into Text variable, which then you are putting directly into your sql update, thus he can do whatever he wants (for example drop all database).
More on SQL Injection
The solution is simple: use PDO and bindValue method.
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$conn = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
// 500 means internal server error
// that's handy information for the client-side
http_send_status(500);
echo json_encode([
'error' => [
'message' => 'Unable to connect to database'
]
]);
exit;
}
$eid = $_POST['eid'];
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$sql = "UPDATE TblCustom SET Text = :text, Amount = :amount WHERE ID = :id";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':text', $Text);
$stmt->bindValue(':amount', $Amount);
$stmt->bindValue(':id', $eid);
if (!$stmt->execute()) {
// 400 means something went wrong when updating
// also a handy information for the client-side
http_send_status(400);
echo json_encode([
'error' => [
'message' => 'Unable to update'
]
]);
exit;
}
// 204 measn everything went okay, and we don't return anything
http_send_status(204);
exit;
Hint: if you are sending correct status codes the jQuery lets you handle errors like this:
$.ajax({
// ...
success: function(response) {
// this code will be executed
// only when status code == 2xx
},
error: function(response) {
// this code will be executed
// only when status code == 4xx | 5xx (if I remember correctly)
},
always: function(response) {
// this code will be executed no matter what
// as the name implies
},
});
So there is no need for additional if statements.
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="form_signup" name="form_signup">
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="SAmount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="SAmount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="SAmount[]" id="Amount_3" /></td>
</tr>
<input type="submit" name="signup" value="Sign Up!"/>
</form>
<script>
$(document).ready(function() {
$("#form_signup").click(function() {
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: $(this).serialize(),
success: function(response) {
alert(response);
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
</script>
</body>
</html>
process.php
<?php
print_r($_POST);
?>

PHP: trying make ajax call from foreach loop

I am looping through data form a database to a form that makes a Ajax request to add an item to a shopping basket/cart. Everything works fine except that only the first item in the array is added? I have tried using classes as apposed to id's(unique
echo "<div class='col-100 border-temp bg-orange'>";
echo "<div class='col-50 border-temp'>";
foreach ($result as $key => $result) {
$m = $result["model_no"];
$q = $result["qty_available"];
echo "<form method='post' action='/stock-clearance' class='stock_clearance bg-blue'>";
echo "<label for='model_no'><h2>Model No</h2></label>";
echo "<input id='model_no' name='model' type='text' placeholder='Paste model no... ' value='$m' />";
echo "<span id='model_error'></span>";
echo "<label for='quantity'>Quantity</label><br />";
echo "<input id='quantity' name='quantity' value='1' type='number' min='1' max='$q'>";
echo " <span id='quantity_error'></span>";
//echo "<input id='sc_add_to_cart' name='' value='$key' type='button'>";
echo "<input id='sc_add_to_cart' name='sc_add_to_cart' value='Add to Basket' type='submit'>";
echo "</form>";
} // End foreach loop
echo "</div>";
)
My JS code is as follows:
$('#sc_add_to_cart').on('click', function(e) {
e.preventDefault();
var form = $('.stock_clearance');
hideStockClearanceMessages(form);
var request = $.ajax({
beforeSend: function() { form.css({ opacity: 0.4 }); },
url: 'ajax.php',
cache: 'false',
data: {
action: "sc-add-to-cart",
model: $('input[name="model"]').val(),
quantity: $('input[name="quantity"]').val()
}
});
enter image description here
You can not have the same one ID for a different inputs. ID must be UNIQUE. Instead of ID use CLASS attribute
1- Sometimes because of caching problem it will not work so you have to add seed to your call.
seedrandom()
function seed() {
return Math.floor((Math.random() * 10000) + 1);
}
$('#sc_add_to_cart').on('click', function(e) {
e.preventDefault();
var form = $('.stock_clearance');
hideStockClearanceMessages(form);
var request = $.ajax({
beforeSend: function() { form.css({ opacity: 0.4 }); },
url: 'ajax.php?sid=' + seed(),
cache: 'false',
data: {
action: "sc-add-to-cart",
model: $('input[name="model"]').val(),
quantity: $('input[name="quantity"]').val()
}
});
Please use IDs only for one element. They must be unique. You can use CLASS instead.

how to check checkbox in javascript loop

I already get the id from a php loop for my checkboxes, and pass them as a string(maybe not because I could not split them with comma) in parameter, then I need to check if the checkbox is checked in javascript using the ids I passed through.
It doesnt seem like I can split it in javascript as well, and after I ran the for loop, the data is undefined in the new string.
Do you have any ideas? Please help
here is my php
echo "<div id='addstock'>";
$ids = '';
while($row_add = mysqli_fetch_array($result_add)){
$id=$row_add['id'];
$company = $row_add['companyname'];
//create checkbox for company
echo "<p class='checkbox'><input type='checkbox' name='stocks' id='".$id."' value='".$id."'>".$company."</p><br>";
$ids .= $id;
}
echo "</div>";
echo "<p class='input'><input type='submit' class='submitbutton' value='Submit' onclick='updatetable(".$ids.",".$user.")'></p>";
here is my javascript
//update table after add to stock
function updatetable(ids,user){
var url = "update.php";
//var res= ids.split(" ");
alert(ids);
var stocks = "";
//check if the checkbox is checked
for(var id in ids){
if(document.getElementById(ids[id]).checked)
{
stocks += ids[id];
alert(ids[id]);
}
}
//alert(stocks);
var data = "ids="+stocks+"&user="+user;
alert(data);
ajaxRequest(url, "POST", data, true, proceedUpdate);
}
function proceedUpdate(response){
target_div = document.getElementById("tablediv");
target_div.innerHTML = response;
}
Try this:
<div id="addstock">
<?php
$ids = array();
while($row = mysqli_fetch_array($result_add)) {
$ids[] = $row_add['id'];
echo '<p class="checkbox"><input type="checkbox" name="stocks" id="' . htmlspecialchars($id) . '" value="' . htmlspecialchars($id) . '">' . htmlspecialchars($company). '</p><br>' . "\n";
}
?>
</div>
<p class="input">
<input type="submit" class="submitbutton" value="Submit" onclick="updatetable('<?php echo htmlspecialchars(implode(',', $ids)); ?>', '<?php echo htmlspecialchars($user); ?>')">
</p>

get post data in a php page called by ajax

I have called the page search.php from ajax:
function search(){
var title=$("#search").val();
if(title!=""){
$.ajax({
type:"post",
url:"search.php",
data:"title="+title+"&idTratta="+<?php echo $idTratta ?>,
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
}
}
Now in search.php I get the result of a query in a html table and I created radio buttons in a form that when each form is submitted I get the value of the radio button's clicked and update a row in the db:
$title = $_POST["title"];
$idTratta = $_POST["idTratta"];
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers -> searchUser($title, $idTratta);
foreach ($users as $user) :
echo "<tr>
<td>" . $user["nome"] . "</td>
<td>" . $user["role"] . "</td>
<td class='right'><form action='' method='post'><label>
<input type='radio' name=" . $user["nome"] . " id='c' value='1' ";
if ($user["role"] == 'configuratore')
echo "checked='checked' />C</label>";
else
echo "/>C</label>";
echo "<label>
<input type='radio' name=" . $user["nome"] . " id='va' value='2' ";
if ($user["role"] == 'visualizzatore avanzato')
echo "checked='checked' />VA</label>";
else
echo "/>VA</label>";
echo "<label>
<input type='radio' name=" . $user["nome"] . " id='v' value='3' ";
if ($user["role"] == 'visualizzatore')
echo "checked='checked' />V </label>";
else
echo "/>V </label>";
echo "<input type= 'submit' name='sub_" . $user["nome"] . "'value='Cambia'/></form></td>
</tr>";
$sub = 'sub_';
if ($_POST[$sub . '' . $user["nome"]]) {
$permission = $_POST[$user["nome"]];
$SimpleUsers -> updateUserPermission($user["nome"], $idTratta, $permission);
}
endforeach;
The problem is that in search.php I am unable to catch POST variables, how I can get it?
EDIT
This is the piece of code which doesn't work:
if ($_POST[$sub . '' . $user["nome"]]) {
$permission = $_POST[$user["nome"]];
$SimpleUsers -> updateUserPermission($user["nome"], $idTratta, $permission);
}
The data shouldn't be parsed as text but instead as an js array like this:
data: {title: title, idTratta : <?php echo $idTratta ?>},
EDIT:
A example for sending the form data would be:
var formData = JSON.stringify($("#myForm").serializeArray());
formData['idTratta'] = <?php echo $idTratta ?>;
$.ajax({
type:"post",
url:"search.php",
data:formData,
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
And than using json_decode in your php form to turn it into a PHP array again. Its kind of dirty but it should work
Try this method
$.post("`search.php`", { title : title , idTratta : '<?php echo $idTratta ?>'},
function (data) {
$("`#result`").html(data);
$("`#search`").val("");
});

Categories

Resources