ajax post method in php - php

I am trying to send ajax post javascript variable to php. My code php will only be executed if I press submit in another form.
My code is in one index.php file.
The console shows that this value has been sent, but my php code does not want to pick it up and does not execute the query. Why?
<?php
if (isset($_POST['imie2'])) {
...
if(isset($_POST['item_id']) && !empty($_POST['item_id'])){
$value = $_POST['item_id'];
if ($polaczenie->query("INSERT INTO zamowienia VALUES ('$value')")) {
...
?>
<form method="post">
<input type="text" name="imie2">
...
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
var value = localStorage.getItem('sumalist');
console.log(value);
$.ajax({
url:"index.php",
method:"POST",
data:{
item_id: value,
},
success:function(response) {
console.log('ok'); // console shows ok
},
error:function(){
alert("error");
}
});
});
</script>

You said:
if (isset($_POST['imie2'])) {
but your data looks like this:
data:{
item_id: value,
},
There's no imie2 field so your test will always fail.

Related

Insert data with jQuery

I am trying to make a form to insert data to database with jQuery, but there's no action happen and want to know where the problem is.
Here's the code I wrote, and I hope someone will help me find where the mistake is, and why there's no action on it.
index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="insert.js"></script>
</head>
<body>
<form id="form-search" method="post" action="index.html">
<input name="gov" id="gov" type="text" class="textinput required" maxlength="80" required><br>
<input name="area" id="area" type="text" class="textinput required" maxlength="80" required><br>
<button id="submit" type="button">insert</button>
</form>
</body>
</html>
insert.js code
$(document).ready(function(e) {
$('#submit').click(function() {
var gov =$('#gov').val() ;
var area =$('#area').val() ;
$.ajex({
type :'post' ,
data :{gov:gov,area:area},
url :"insert.php",
success :function(result) {
alert(result);
}
})
});
});
insert.php code
<?php
$con = mysqli_connect('localhost','user','pass','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
if($_REQUEST['gov']) {
$gov=$_REQUEST['gov'];
$area=$_REQUEST['area'];
$q="inser into gov values ('','$gov','$area')";
$query=mysqli_query($con,$q);
if($query){
echo "data insert " ;
}
}
?>
Look at the Networks' tab using the Developer Tools. Check if there's something happening when you press the submit button. Check for a status code.
This script (with your html) will submit the data (with console logs to the browser) to 'insert.php'. Please read the comments for explanations. If it still doesn't work, the problem probably lies in your PHP code (I don't work with PHP). The ajax is sending the data to 'insert.php', which should be coded to accept the data variables and return a json response back to the ajax function in the script.
// Remove the 'e' from .ready and place in the 'click' function - this is the 'event'
$(document).ready(function () {
$('#submit').click(function (e) {
// Stops the form from being submitted 'normally' (to index.html)
e.preventDefault();
// Check console in your browser (this can be removed when it works)
console.log('submit clicked');
// Define the data to be submitted with the ajax form
var submitData = { gov: $('#gov').val(), area: $('#area').val() };
$.ajax({
// Make sure your path to insert.php is complete - check console in browser to see if there is an error
url: 'insert.php',
// Make sure 'insert.php' accepts 'post' transactions
type: 'POST',
// This could be changed (when it works) to - data: { gov: $('#gov').val(), area: $('#area').val() },
data: submitData,
// Make sure 'insert.php' returns a json result
dataType: 'json',
success: function (result) {
// This can be removed when it works
console.log('ajax success');
},
beforeSend: function () {
// This can be removed when it works
console.log('ajax beforeSend');
// This can be removed when it works - this lists out the data submitted with the form
$.each(submitData, function (index, value) {
console.log('index: ' + index + ' value: ' + value);
});
},
complete: function () {
// This can be removed when it works
console.log('ajax complete');
},
error: function () {
// This can be removed when it works
console.log('ajax error');
}
});
});
});

AJAX seems to be sending entire web page script rather than data

I am having real trouble with my AJAX request and I am not sure why. The following code seems to send to the entire web page script (as seen in both my alert box and in the console) rather than my checkbox values. Can anyone explain to me what I am doing wrong?
Here is my PHP checkbox, which has values generated by SQL, and has no submit button so the code is set up to run on change from the user:
<form id="numberOrderForm" action="testdatabase.php" method="post">
<div class="wrappers" id="multi-select1Wrapper">
<h2>Area Code</h2>
<select class="dropDownMenus" id="multi-select1" name="multi_select1[]" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
?>
</select>
</div>
</form>
And here is my jQuery AJAX code:
<script>
$('#multi-select1').on("change", function(){
var areaCode = $(this).val();
$.ajax({
type:"POST",
url: "testdatabase.php", //my PHP database
data: "areacode=" + areaCode,
success: function(response){
//do stuff after the AJAX calls successfully completes
alert (response);
console.log(response);
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
</script>
your data is incorrect for one.
replace:
data: "areacode=" + areaCode,
with:
data: {"areacode": areaCode},
you should also add: enctype='multipart/form-data' to your form element
Please add following line on jquery ajax call
dataType: 'json'
contentType: "application/json",
After add above code your code is like below
<script>
$('#multi-select1').on("change", function(){
var areaCode = $(this).val();
$.ajax({
type:"POST",
url: "testdatabase.php", //my PHP database
data: "areacode=" + areaCode,
dataType: 'json',
contentType: "application/json",
success: function(response){
//do stuff after the AJAX calls successfully completes
alert (response);
console.log(response);
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
</script>

AJAX / PHP error handling and global variable

this is my first time writing an ajax below is my structure
submitted.php
<?php $a = $_POST['a']; // an input submitted from index.php ?>
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php
<?php echo $a; // will this work? ?>
ajax return blank... no error, my error_reporting is on.
No, there are a few things wrong with this:
You are posting a key - value pair where the key is key, so you would need $_POST['key'] in your php script;
You should use .preventDefault() if you need to prevent an event like a form submit that is caused by your button. If that is the case, you need to get the event variable from your event handler: $('button').on('click', function(event) {.If there is no event to prevent, you can simply remove that line;
If you do have a form (it seems so from your comment), you can easily send all key - value pairs using: data: $('form').serialize().
form.php
<button>bind to jquery ajax</button> <!-- ajax trigger -->
<span></span> <!-- return ajax result here -->
<script>
// NOTE: added event into function argument
$('button').on('click', function(event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function(msg) {
$('span').html(msg);
});
});
</script>
process.php
<?php
echo (isset($_POST['key'])) ? $_POST['key'] : 'No data provided.';
?>
This is the way to do it:
ubmitted.php
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
// no need to prevent default here (there's no default)
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php
<?php
if (isset($_POST['key'])
echo $_POST['key'];
else echo 'no data was sent.';
?>

Forms/PHP/Ajax load?

I'm currently learning PHP. I've made a simple script # http://hash.techho.me, only thing is, I want the form to submit then load the results via AJAX, without the user leaving the page. Possible?
post the form using ajax
$.ajax({
url:'yoururl',
data:$("form").serialize(),
type:'POST',
success:function(data){
alert("success");
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
jQuery.ajax() – jQuery API
Posting to the same page should do the trick. No need to use ajax for that
> <?php
>
> //do stuff with $_POST
> ?>
>
> <html> <body> <form method="post">
>
> <?php echo $result ?>
>
> </form>
> </body>
Fike
use ajax for this, lets suppose try this one for your practice
var string = $("#string").val();
var dataString = 'string=' + string ;
if(string==''){
alert('enter any string');
}
else{
$.ajax({
type: "POST",
url: "path of php file",
data: dataString,
suceess: function(){
//do something
},
error: function(){
//do something
}
});
}
You can use jQuery or Prototype JS libraries to make an easy AJAX call. Example using jQuery would be:
$.ajax({
url:'hashed.php',
data:$("form").serialize(),
type:'POST',
success: function(data){
$('hashmd5').html(data.md5);
$('hashsha1').html(data.sha1);
},
error: function(jxhr){
alert(jxhr.responseText);
}
});
Don't use the same id value in HTML, never ever. They must be unique to correct perform JavaScript functions on elements.
yes it is possible. Write a javascript function that would trigger on submit, disable the submit button so user couldn't press it again, and finally request the server via ajax. on successful response update the content. Something like following in Jquery
$('.form-submit').click(function(event)) {
event.preventDefault();
if(form is valid and not empty) {
$.ajax({
type: "POST",
url: "path to script that will handle insetion",
data: "data from form", //like ({username : $('#username').val()}),
suceess: function(data){
//update the content or what. data is the response got from server. you can also do like this to show feedback etc...
$('.feedback').html("Data has been saved successfully");
},
error: function(){
$('.feedback').html("Data couldn't be saved");
}
});
}
}

Posting a sub-form with jQuery

I'll start off by saying I'm new to jQuery but I am really enjoying it. I'm also new to stackoverflow and really loving it!!
The problem:
I've created a sub-form with jQuery so that a user may add, then select this information from a dropdown list if it is not already available. I'm unable to POST this data with .ajax(), so that the user can continue to fill out other information on the main form without having to start over.
Sub-Form:
$(function() {
$("#add").live('click', function(event) {
$(this).addClass("selected").parent().append('<div class="messagepop"><p id="close"><img src="img/close.png"></p></img><form id="addgroup" method="POST" action="add_group.php"><p><label for="group">New Group Description:</label><input type="text" size="30" name="grouping" id="grouping" /></p><p><label for="asset_type">Asset Type:</label><select name="asset" id="asset" ><option>Building</option><option>Equipment</option></select></p><p><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></form><div id="result"></div></div>');
$(".messagepop").show()
$("#group").focus();
return false;
});
$("#close").live('click', function() {
$(".messagepop").hide();
$("#add").removeClass("selected");
return false;
});
});
And here is where I'm attempting to process it:
$(function () {
$('#addgroup').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
I've even attempted to create a simple alert instead of processing the information and this also does not work. Instead the form sumbits and refreshes the page as normal. Can anyone help me understand what I am missing or doing wrong? Thank you!
New attempt:
$("#add").live('click', function(event) {
var form = $("<form>").html("<input type='submit' value='Submit'/>").submit(function(){
$.post("add_group.php", {grouping: "Building, asset: "STUFF"});
$(".newgroup").append(form);
return false;
});
Final code
$(function() {
var id = 1
$("#add").live('click', function(event){
if($(".addgroup,").length == 0){
$("#test").append('<div class="addgroup"><label for="newGroup">New Group:</label><input type="text" class="newgroup" id="' + ++id + '" /><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></div>');
$("#add").attr("src","img/add_close.png");
}else{
$("#add").attr("src","img/add.png");
$(".addgroup").remove();}
return false;
});
});
$(function(){
$(".group_submit").live('click',function(event){
$.ajax({
type: "POST",
url: "add_group.php",
data: {new_group: $(".newgroup").val(), asset: $("#group option:selected").text()},
success: function(){}
});
$(".addgroup").remove();
$('#subgroup').load('group.php', {'asset': $("#group option:selected").text()});
return false;
});
});
If the form is submitting and refreshing as normal, the jquery isn't kicking in (the refresh means it's posting the form normally).
I for some reason (maybe others haven't) found that $(document).ready(function() { works much better than $(function() { ...
Also, the groups that you're adding should have a definitive id:
on #add click, count up a counter (form++) and add that to the id (#addGroup_+form) and then target that straight away in the function that added it:
$("#group").focus();
$("#addGroup_"+form).submit(function() {
try using .live()
$(function () {
$('#addgroup').live('submit',function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
and make sure addgroup has no duplicate id... you may use it as class if it has to be duplicated...

Categories