I am facing some issues. I am trying to insert array in MYSQL using AJAX and PHP but its not working following is my code:
HTML:
<input type="text" class="form-control" name="invoice" id="invoice" placeholder="piece">
<input type="text" class="form-control" name="pieces[]" id="pieces" placeholder="Qty">
I want to pass fields from ajax to php. I am using following code in ajax.
var inv = $("#invoice").val();
var pieces = $("#pieces").val();
$.ajax({
type: "POST",
url: "query.php",
data: "piece="+pieces+"&inv="+inv,
success: function(data){
$("#result").html(data);
}
});
following is the PHP code:
<?php
$piece = $_POST[piece];
foreach ($piece as $key => $value) {
$query = mysql_query(insert into items values('$value', '$_POST[inv]');
}
?>
Try this code
jQuery
var inv = $("#invoice").val();
var pieces = $("#pieces").val();
$.ajax({
type: "POST",
url: "query.php",
data: {'in':inv,'pi':pieces},
success: function(data){
$("#result").html(data);
}
});
php
<?php
$pieces = $_POST[piece];
foreach($pieces as $piece){
{
$query = mysql_query(insert into items values ('$piece','$_POST[inv]');
}
?>
Try this:
JQuery:
var inv = $("#invoice").val();
var pieces = $("#pieces").val();
$.ajax({
type: "POST",
url: "query.php",
data: {'in':inv,'pi':pieces},
success: function(data){
$("#result").html(data);
}
});
Php code :
<?php
$inv = $_POST['in'];
$piece = $_POST['pi'];
$query = mysql_query(insert into items values '$piece','$_POST[inv]');
?>
This is the simple example, please use mysql encapsulation to get value for preventing sql injection.
Related
I'm doing a project on WordPress and I'm having some trouble with the auto-complete field on my form. No input is shown and no error in console. I created a small database on one of the WordPress database. I'm not very familiar with AJAX so please be kind :)
jQuery(document).ready(function($) {
jQuery('#dish').autoComplete({
source: function(name, response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
});
This is my jQuery code and I added the admin-ajax in the same folder as I was thinking it didn't find it (it's my_serach.js)
function ajax_listings() {
global $wpdb; //get access to the WordPress database object variable
//get names of all businesse
$name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$sql = "select name
from $wpdb->global
where name like %s
and post_type='portfolio' and post_status='publish'";
$sql = $wpdb->prepare($sql, $name);
$results = $wpdb->get_results($sql);
//copy the business titles to a simple array
$titles = array();
foreach( $results as $r )
$titles[] = addslashes($r->name );
echo json_encode($titles); //encode into JSON format and output
die(); //stop "0" from being output
i add this code on the functions.php on the theme i'm working on
<form method = "POST">
<div id = "container">
<div><label class="plate_label">Dish:</label><input type="text" name="dish_name[]" id="dish" class="dish" placeholder="Enter plate name" />
<label class="quantity_label">Quantity:</label><input type="text" name="dish_quantity[]" class="quantity" placeholder="Enter gram or pieces/slices" /></div>
</div>
and last the form where it should show the suggestions from the database.
Try this code.
jQuery(document).ready(function($) {
jQuery('#dish').autoComplete({
source: function(name, response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'http://caloriless.com/wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
});
change ajax url url: 'wp-admin/admin-ajax.php', or url: 'http://caloriless.com/wp-admin/admin-ajax.php',
Hi I have a select box that when it is changed I want the value in a database to be updated via Ajax. Using the console I can see that my saveedit2.php file is not being called.
Select Box
<form><select id="workingpattern">
<?php
if(isset($workingpatterns) && !empty($workingpatterns)){
foreach($workingpatterns as $k4=>$v4) {
?>
<option value="<?php echo $workingpatterns[$k4]["workingpatternid"]; ?>">
<?php echo $workingpatterns[$k4]["text"]; ?></option>
<?php }}?>
</select></form>
Ajax:
<script>
$(document).ready(function(){
$('#workingpattern').change(function(){
var e = document.getElementById("workingpattern");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "saveedit2.php",
type: "post",
data: value,
success: function(data) {
console.log(data);
}});
});
</script>
SaveEdit2.php
<?php
require_once("connect_db.php");
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
?>
There are a few issues that I see. First, I would use 'this' to get the element and use jQuery to get the value since you are using it already. Secondly, you need a name for the value in the data set:
$('#workingpattern').change(function(){
var value = $(this).val();
$.ajax({
url: "saveedit2.php",
type: "post",
data: 'value='+value,
success: function(data) {
console.log(data);
}
});
});
Try
Ajax
$('#workingpattern').change(function(){
var value = $("#workingpattern").val();
$.ajax({
dataType: "json",
url: "./saveedit2.php",
data: {'value':value},
success: function(data){
if(data['result']=="ok")
alert("Done");
else
alert("Error");
}
});
SaveEdit2.php
<?php
require_once("connect_db.php");
$ajax_result = "error";
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
if($result)
$ajax_result = "ok";
echo json_encode(array('result'=>$ajax_result));
?>
I read similar answer here in this question: How to insert into MYSQL row from multiple $_POST arrays and How to insert into MYSQL row from multiple $_POST arrays but the problem is these answers do not work in my code. Is it because im using an ajax? and i only get the value of the first array.
If i also place the variable declaration inside the for loop it is not working too.
Here is my ajax:
var name = [];
$('input[name="name[]"]').map(function(){ name.push($(this).val()); }); var studid = [];
$('input[name="studid[]"]').map(function(){ studid.push($(this).val()); }); var nameStr = name != '' ? '&name='+ name : '';
var studStr = studid != '' ? '&studid='+ studid : '';
var dataString = 'subject='+ subject + '§ion=' + section + studStr + nameStr;
$.ajax({ type: "POST", url: 'save.php', data: dataString, dataType: "html",
success: function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); }); },
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); } });
return false;
});
Here is my php:
if(isset($_POST['studid']) || isset($_POST['name'])){
$studid = array_map(mysql_real_escape_string, explode(",",$_POST['studid']));
$name = array_map(mysql_real_escape_string, explode(",",$_POST['name']));
for ($i=0; $i<count($studid); $i++){
$sql_1 = "INSERT INTO tbl_student(StudentID, StudentName, SubjectID) VALUES ('".$studid[$i]."', '".$name[$i]."', LAST_INSERT_ID())";
mysqli_query($con,$sql_1);
}
}
use mysql_insert_id();
instead of LAST_INSERT_ID()
You're not sending data correctly from the jQuery and its seems you'r mixing arrays and string together.
This is a simple request that posts studid-array from jQuery
var saveData = $.ajax({
type: 'POST',
data: {studid: studid},
url: 'save.php',
dataType: 'html'
});
saveData.done(function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); });
});
saveData.fail(function(ts) {
alert(ts.responseText);
});
When save.php is called, $_POST['studid'] would be set (if there are anything in the array)
If you instead do like this:
var saveData = $.ajax({
type: 'POST',
url: 'save.php?studid=' + studid,
dataType: 'html'
});
When save.php is called, $_GET['studid'] would be set (if there are anything in the array). The best way though is to use data-option in the ajax-function call (in my first case). If you choose to use this option you would have to serialize the stuid-array before putting it in as a part of an url.
UPDATE
If you want to pass multiple arrays you would have to do something like this:
var saveData = $.ajax({
type: 'POST',
data: {studid: studid, name_arr2: data_arr2},
url: 'save.php',
dataType: 'html'
});
My problem is that I can't retrieve the result of the mysql result via ajax, please help
ajax code:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data:{user_id:user_id}, dataType:'json',
success:function(msg) {
alert ('asdasd')
// $("#quiz_form,#demo1").addClass("hide");
// $('#result').show();
$('p').html(msg);
}
});
PHP code:
$final=array();
$sql_courses=mysql_query("SELECT course_id, course_name FROM course") or die (mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
$result=$row_courses['course_name'];
//array_push($final,$result);
//print_r($result);
echo json_encode($result);
Change PHP Code as below
$final = array();
$sql_courses = mysql_query("SELECT course_id, course_name FROM course") or die(mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
echo json_encode($row_courses);
change php code as below:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data: {
user_id: user_id
},
dataType: 'json',
success: function (msg) {
$('p').html(msg.course_name);
}
});
Its better to send it with a key value like this:
And its better to use console.log(variable); to check variable's content
ajax code:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data:{user_id:user_id}, dataType:'json',
success:function(msg) {
alert ('asdasd');
console.log(msg);//You should check output of this in browser console
// $("#quiz_form,#demo1").addClass("hide");
// $('#result').show();
$('p').html(msg.cname);
}
});
PHP code:
$final=array();
$sql_courses=mysql_query("SELECT course_id, course_name FROM course") or die (mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
$result=$row_courses['course_name']; // this will have first_coures_name (an string)
$final['cname']=$result;
//print_r($result);
echo json_encode($final); //the output should be this {'cname':'first_course_name'}
I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call