I've been a lurker for some time, but this is my first post (and motivated me to sign up), I've searched countless posts, but can't find a solution that best works. This is part of a project where users search a database and have the option to add returned results to a saved location (posting the id, resid, to a separate mysql table).
The search function is in a separate php file, the relevant parts of the code are below (I've stripped out a lot of the formatting):
// Output HTML formats
$html ='<tr >
<form id="myForm" method="post">
<input type="hidden" id="resid" name="resid" value="ther3sidd">
<input type="hidden" id="lesid" name="lesid" value="liD1">
<input type="button" id="submitFormData" onclick="SubmitFormData()" value="Submit" />
</form>
</tr>';
The values "ther3sidd" and "liD1" get replaced with values unique to the item returned by the search, and are numerical values. There will also be multiple of the forms returned on the user facing page all with the same id of myForm (but different lesid and resid).
The search results are outputted to the page the user is on and a button can be pressed to add the result to a mysql table using the script below (stored in the page the user is on).
function SubmitFormData() {
var lesid = $('input[name="lesid"]').val();
var resid = $('input[name="resid"]').val();
var dataString = {lesid: lesid, resid: resid}
$.ajax({
type: "POST",
url: 'lesresadd.php',
data: dataString,
})}
Below is the php file lesresadd.php (without the connection info)
$lessonid = $_POST['lesid'];
$resourceid = $_POST['resid'];
$sql = "INSERT INTO lessons_resources (lesson_id, resource_id)
VALUES ('$lessonid', '$resourceid')";
$result = $conn->query($sql)
The code works fine and can submit data to the mysql table, however, the main issue is that the values for resid and lesid are for the first result from the search function (and not the one selected with the button click). I know that I need to use 'this' somewhere on the variable, however, I am not sure of the correct syntax. For example, I have tried the following (and many variants on it):
var lesid = $this().('input[name="lesid"]').val();
But this does not work. Maybe, there is more I need to do to the code, and it isn't as simple as just adding 'this' somewhere. I am reasonably new to AJAX and entirely self taught from visiting sites just like stack overflow. Any advice would be greatly appreciated.
It's not the neatest solution, but here goes:
$html = "";
$i = 1;
while($r = mysql_fetch_object($res))
{
$html .='<tr>
<input type="hidden" id="resid'.$i.'" name="resid" value="ther3sidd">
<input type="hidden" id="lesid'.$i.'" name="lesid" value="liD1">
<input type="button" class="submitFormData" onclick="SubmitFormData('.$i.')" value="Submit" />
</tr>';
$i++;
}
Then in your JavaScript:
function SubmitFormData(id) {
var lesid = $('#lesid'+id).val();
var resid = $('#resid'+id).val();
var dataString = {lesid: lesid, resid: resid}
$.ajax({
type: "POST",
url: 'lesresadd.php',
data: dataString,
})}
Related
I'm trying to insert a row in the db, without refreshing the page, using LARAVEL and AJAX, but when, I click the submit button,I receive the following error in the browser console response:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'writer_id2' cannot be null.
I guess, that the input data has not been submitted and the values are null, but then how do I receive the response/input data in the controller and insert it in the db at the same time?
Route:
Route::post('writers', ['as'=>'add-writer' ,'uses'=> 'HomeController#addWriter'])->name('add-writer');
Controller:
public function addWriter(){
$i = new Input();
$dm= new DataModel();
$data= response()->json(['data'=>$i::all()]);
$encode = json_encode($data);
$decode = json_decode($encode,true);
$decoded = [];
$decodedNeeded = [];
$inc = 0;
$i2 = 0;
foreach ($decode as $k=>$v){
$inc++;
$decoded[$inc] = $v;
}
foreach($decoded[2] as $k3 =>$v3){
$i2++;
$decodedNeeded[$i2] = $v3;
}
$this->insertUser = $decodedNeeded;
$dm->addWriterMethod($decodedNeeded[1]['writer_id2'],$decodedNeeded[1]['status'],$decodedNeeded[1]['writer-skills']);
AJAX
$('#add-writer-btn').click(function(e) {
e.preventDefault();
var id = $('input[name=writer_id2]').val();
var status = $("input[name=status]").val();
var skills = $('textarea').val();
var form2 = $(this);
var url2 = form2.attr('action');
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
method: "POST",
ContentType: 'application/json',
url: url2,
dataType: 'json',
data: {
'id': id,
'status': status,
'skills': skills
},
success: function (data) {
alert('Added successfully!');
}
});
});
HTML
<div id="add-writer">
<b>Add writer</b>
<form action="{{url('add-writer')}}" method="POST">
<input type="hidden" name="_token" value="{{csrf_token()}}">
Writer_id2 <input type="number" id="writer-id-2" name="writer_id2">
<br>
Open to suggestions <input type="radio" value="Open to suggestions" name="status">
<br>
Searching for orders <input type="radio" value="Searching for orders" name="status">
<br><br>
Writer skills <textarea name="writer-skills"></textarea>
<input type="submit" value="Add" id="add-writer-btn" >
</form>
</div>
Based on your comments, it seems it works - but redirects - when you don't use ajax, but it does not work when you use ajax.
That would seem logical: When you don't use ajax, you send 4 key-value pairs to the server:
_token
writer_id2
status
writer-skills
And when you use ajax, you only send 3 key-value pairs, of which only 1 has the correct key:
id
status
skills
So at the very least you need to change the data you send when using ajax.
So this:
data: {
'id': id,
'status': status,
'skills': skills
},
Should be:
data: {
'writer_id2': id,
'status': status,
'writer-skills': skills
},
Now you have at least the data part sorted, but it could still fail due to a missing _token and if that is the case, you would need to add that one too.
However, strangely enough the error message you receive, suggests that the token is unnecessary, which probably indicates a configuration error.
To simply add everything without having to assign variables manually, I would recommend using this instead:
data: $('form').serialize(),
Now you will receive the exact same data as with the "normal" / non-ajax post.
Apart from that, I would also recommend listening for the form submit event instead of the button click so that your javascript will also handle any submits that are caused for example by using the enter-key.
Some comments...
1) If your are using id in html tags maybe you can use $('#yourid').val() to get data.
2) Controller en Laravel receive one parameter by default it's $request, so
public function addWriter(Request $request) {
3) If you are using 2. You can use $request->all(); or Input::get('writer_id2'); it's not necessary instance a new Input();
4) In ajax you can use $('div#add-writer form').serialize() to serialize values in data.
5) In the controller you can use
$dm->addWriterMethod($request->writer_id2,$request->status,$request->writer_skills);
6) Don't use "-" in vars, ids, names... use "_" eg. writer_skills
7) Delete all crazy foreach (Or leave if they are necesary)
Please try these and let me know how it works :)
Let's have a example:
file.html
<input type="text" name="txtname" id="txtname">
<input type="text" name="txtemail" id="txtemail">
<input type="text" name="txtaddress" id="txtaddress">
now file.php
assume connection already done and the variable $con.
$userid = $_SESSION['userid'];
$qry = mysqli_query($con, "SELECT name, email, address from users where id='$userid'");
$row = mysqli_fetch_array($qry);
$txtname= $row['name'];
$txtemail = $row['email'];
$txtaddress = $row['address'];
Now i don't want to write any single code of php in the html file let it be pure hmtl. also do not want to write any html code in php file let it be pure php.
is there any secure (minimum) way to put the results of php files in respective form field of the html file using jquery ajax???
may be it is a stupid question. But i want to with clarification as i am learning now. i do not want to use PDO and OOPS as i don't know.
Yes using Ajax its possible.
First In php file echo out your result like below
echo json_encode($row);
and then you can write below code in html file in script tag and populate fields accordingly
$.ajax({
url: 'data.php',
dataType: "json",
success: function (data) {
$('#txtname').val(data.name)
$('#txtemail').val(data.email)
$('#txtaddress').val(data.address)
}
});
I tried to find help via the search function on here but all the answers given to similar problems were too elaborate for me to understand, i.e. the example code was too complex for me to extract the parts which could have been relevant for my problem :(
I have a html form which sends userinput on a specific row in a datatable via an ajax-request to a php file, where the input gets inserted into my sqldb.
I have no problem sending the textinput entered by a user and also transferring additional infos like the specific row they were on, or the network account of the user. But i now want to add a checkbox, so the users can choose whether their comment is private or public. However i somehow cannot transmit the value from the checkbox, there is no error but also no checkboxdata inserted into the db.
Do i have to handle checkboxes differently than textareas? I'd be very grateful for help!
My code looks as follows:
Html:
function insertTextarea() {
var boardInfo = $( "<form id='boardComment'><textarea rows='2' cols='30'>Notizen? Fragen? Kommentare?</textarea>Privat:<input type='checkbox' name='privatcheckbox' value='private'><input type='submit' value='Submit'><input type='reset' value='Cancel'></form>");
$( this ).parent().append(boardInfo);
$("tbody img").hide();
$("#boardComment").on( "submit", function( event ) {
event.preventDefault();
var change_id = {};
change_id['id'] = $(this).parent().attr("id");
change_id['comment'] = $(this).find("textarea").val();
change_id['privatecheckbox'] = $(this).find("checkbox").val();
if( $(this).find("textarea").val() ) {
$.ajax({
type: "POST",
url: "boardinfo.php",
cache: false,
data: change_id,
success: function( response2 ) {
alert("Your comment has been saved!");
$("tbody img").show();
$("#" + change_id['id']).find("form").remove();
}
});
};
});
and this is the php part:
$id = mysql_real_escape_string($_POST['id']);
$comment = mysql_real_escape_string($_POST['comment']);
$privatecheckbox = mysql_real_escape_string($_POST['privatecheckbox']);
$sql="INSERT INTO cerberus_board_info (BOARD_INFO_COMMENTS, BOARD_INFO_USER, BOARD_INFO_CHANGE_ID, BOARD_INFO_ENTRY_CHANNEL, BOARD_INFO_PRIVACY_LEVEL) VALUES ('$comment', '$ldapdata', '$id', 'Portal', '$privatecheckbox')";
The following line:
change_id['privatecheckbox'] = $(this).find("checkbox").val();
Searches for a element with the tagname checkbox. Such an element doesn't exist, I believe you are trying to search for an <input> element with a type of checkbox.
The following should work for you:
change_id['privatecheckbox'] = $(this).find("input[type=checkbox]").val();
Or even better, the :checkbox pseudo selector:
change_id['privatecheckbox'] = $(this).find(":checkbox").val();
On a final note: Why shouldn't I use mysql_* functions in PHP?
I'm currently building a system using ExpressionEngine that allows users to answer questions in exchange for points, they can then use these points to claim prizes.
I've been writing the functionality to claim a prize, it needs to do the following:
Check the prize is in stock
Check the user has enough points
If in stock and enough points submit a form which lets the admin know to send the prize out
I have the following code which I think is nearly there however I'm struggling with the last bit, the actual success/failure parts. I've used jQuery Ajax:
<script type="text/javascript">
$(function() {
$("#prizeClaim").submit(function() {
var data = "entry_id={entry_id}&member_id={logged_in_member_id}&prize_title={title}&prize_points={prize_points}";
$.ajax({
url: "/prizes/prize_validation/",
data: data,
success: function(html) {
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
</script>
This code currently just outputs the html of prize_validation in an alert, this is the code used on the validation page so far:
<?php
// All data required made into vars
$entry_id = ($_GET['entry_id']);
$member_id = ($_GET['member_id']);
$prize_title = ($_GET['prize_title']);
$prize_points = ($_GET['prize_points']);
// Select the stock column
$query = ee()->db->query("SELECT field_id_6 FROM exp_channel_data WHERE entry_id = $entry_id");
if ($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
// define stock_total
$stock_total = $row['field_id_6'];
// If stock more than 0 go ahead
if($stock_total > 0) {
//remove 1 stock item
ee()->db->query("UPDATE exp_channel_data SET field_id_6 = field_id_6 - 1 WHERE entry_id = $entry_id");
//update users points
$data = array('member_id' => $member_id, 'prize_points' => $prize_points, 'prize_id' => $entry_id);
$sql = ee()->db->insert_string('exp_rmdy_member_prize_data', $data);
ee()->db->query($sql);
}
}
}
?>
{exp:freeform:form form_id="1" return="thanks"}
<input type="hidden" name="name" value="{username}" id="freeform_name" maxlength="150">
<input type="hidden" name="email" value="{email}" id="freeform_email" maxlength="150">
<input type="hidden" name="company" value="{exp:channel:entries channel='company' dynamic='no'}{if {member_code} == {company_code}}{title}: {company_address}{/if}{/exp:channel:entries}" id="freeform_company" maxlength="200">
<input type="hidden" name="prize" value="<?php echo $prize_title ?>" id="freeform_prize" maxlength="150">
<p><input type='submit' name='submit' value='Process order'></p>
{/exp:freeform:form}
This code checks the stock and if the item is in stock it then removes the amount of points from the users total points, this works. However once this has happened I want to submit the Freeform, I'm not 100% sure if this should be within the prize_validation file or in a third location. But after lots of experimentation I'm still not sure how to go about either!
Any hints/tips much appreciated!
Pjacks answer in the above comment helped me fix this.
Do you want to use ajax to submit or a normal form submit. This should submit the form if you put $("#freeform").submit(); in your call back instead of the alert. Thats assuming the id of your form is called freeform. If you want to do ajax, it's done a bit differently.
I have a table that generates perfectly using php, ajax and the tablesorter plugin. I now would like to make a few of the input fields into dropdown boxes so the user can select an option if it needs to be changed. This all will then need to be saved to a database. Here is what I have so far:
$('#getInfo').live('click', function() {
//clear table before search
$("#inventoryUpdate tbody tr").remove();
$('#messageInv').html('Please be patient, this might take a minute');
$.ajax({
type: "POST",
async: true,
url: "getInventory.php",
dataType: "json",
data: ({skuStart: $("#startSkuRange").val(), skuEnd: $("#endSkuRange").val(), processDate: $("#processDate").val(),
source: $("#source").val()}),
success: function(data){
$('#messageInv').hide();
//console.log(data);
var myselectoptions = '';
if(data.isbn2 === null){
$("#inventoryUpdate").append('<tr><td>No Records Found</td></tr>');
}else{
for(var x=0;x<data.isbn2.length;x++)
{
$.each(data.defect2[x], function(index, val)
{
myselectoptions += '<option value="'+data.defect2[x][index].option+'">'+data.defect2[x][index].option+'</option>';
});
$("#inventoryUpdate").append('<tr><td id="tableSKU">'+data.sku[x]+'</td><td id="tableISBN">'+data.isbn2[x]+
'</td><td><input type="text" id="tableQuantity" value="'+data.quantity[x]+
'"/></td><td><select id="tableDefect">'+myselectoptions+
'"</select></td><td><input type="text" id="tableSource" value="'+data.source[x]+
'"/></td><td><input type="text" id="tableFeature" value="'+data.feature[x]+
'"/></td><td><input type="text" id="tableLocation" value="'+data.location[x]+
'"/></td><td><input type="text" id="tableProcessDate" value="'+data.processDate[x]+
'"/></td><td><input type="text" id="tableBookType" value="'+data.booktype[x]+
'"/></td><td><input type="text" id="tableCreatedBy" value="'+data.created[x]+
'"/></td><td><input type="text" id="tableModifiedBy" value="'+data.modified[x]+
'"/></td></tr>');
}
$("#inventoryUpdate").trigger("update");
} // end of else statement
} // end of success function
});// end of ajax call
}); // end of inventory update function
I would like to have the tableDefect and tableFeature inputs become drop down boxes that are populated dynamically, and default to the current info from the database. For example, if the defect from the database is "rip in dust jacket" that would be the option that is selected, but I also need the rest of the options (no defects, water damage etc.) from the database to be available if it needs to be changed. I would think that I need to change the input type to a select, but then how do I go about populating it? Would that require another call to the database for the information?
Is this even possible to do with this plug-in?
EDIT: I have pasted in the new code based on the answer below, I now am getting 19 "options" (it just says undefined not the actual value returned) for the first record, 38 for the second etc. There should only be 19 options.
If I am reading you correctly just replace <input type="text"......> with
<select id=...><option>...</option></select>
As far as populating the selects dynamically that can be handled a few different ways. With your ajax you would get the select values maybe by changing your existing
data.defect[x] into a multidimensional object so instead of it being just a string you would output an array that will get converted to JSON on your backend so your object would look like
defect[{"option":"value"},{"option":"value"},{"option":"value"},{"option":"value"}]
Where when your building your table in the succession part you would loop over that object. You would essentially do the same as you do now.. except. your select would look like
var myselectoptions = '';
$.each(data.defect[x], function(index, val)
{
myselectoptions += '<option value="'+data.source[x][index].option+'">'+data.source[x][index].option+'</option>';
});
'"/></td><td><select id="tableDefect">'+myselectoptions+'....
now this is pure concept, I haven't tested it, and its likely to need some tweaking to fit your needs specifically but this is the core concept of one of a few ways you can handle what you want done, that fits into what you are currently doing, without having to alter it too much.