I cant get the data from my jquery to php file. I have tried multiple solutions, i dont get any errors but the data is not showing up on my database. This is the first time using ajax. I need an external php submit code, becouse if i include the php code on my index.php the values are remembered and they get submited when I refresh the page. Thanks in advance.
This is my html
<form class="form-inline" method="post" >
<div id="div_id_value" class="form-group">
<input class="numberinput form-control"
id="value" name="value"
placeholder="Value (mmol/L)"
required="True" type="number" step="any" min="0"/>
</div>
<div id="div_id_category" class="form-group">
<select id="id_category" name="category">
<option value="Breakfast">Breakfast</option>
<option value="Lunch" >Lunch</option>
<option value="Dinner">Dinner</option>
<option value="Snack">Snack</option>
<option value="Bedtime">Bedtime</option>
<option value="No Category" selected="selected">No Category</option>
</select>
</div>
<input type="submit" name="submit" value="Quick Add" id="quick">
</form>
This is my jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$("#quick").click(function() {
var sugar2 = $("#value").val();
var category2 = $("#category").val();
$.ajax({
type:'POST',
url:'quick.php',
data:{ 'sugar': sugar2, 'category':category2},
dataType:'json',
success: function(output) {
alert(output);
};
});
});
and this is my php
<?php
session_start();
include 'conn.php';
if (isset($_POST['sugar'])) {
$sugar = $_POST['sugar'];
$category = $_POST['category'];
$email= $_SESSION['email'];
$query = "INSERT INTO data (email, sugar, category)
VALUES($email, $sugar, $category )";
if(mysqli_query($link, $query)) {
header("Location: index.php");
};
};
?>
Quite a few things you could update here. First, it will be tough for anyone here to debug why the data is not in your database. That could be a connection error, setup error, etc. You will need to provide error information in order for us to help. With that being said...
First thing, I would tie into the submit event instead of the click event. The click event will not account for users pressing enter on the input field. The submit event will catch both clicking the submit button, as well as submitting the form via the enter key.
$("#quick").submit(function(evt) { ... });
//or
$("#quick").on('submit', function(evt) { ... });
Next, your AJAX call. You specify the dataType parameter. According to the documentation, this is to tell jQuery what you expect back from the server. Not what you are sending to the server. So in your case, you should be sending JSON back to your AJAX success function, which you are not. I would remove the dataType parameter, as it is not required.
Finally, the success function expects a response. In your PHP file, you are attempting to redirect the user, which will not work here. You need to return a response to the AJAX function. This would be a great opportunity to check for errors, or even simply debug your code an ensure it is working as expected. So perhaps something like this,
<?php
session_start();
include 'conn.php';
if (isset($_POST['sugar'])) {
$sugar = $_POST['sugar'];
$category = $_POST['category'];
$email= $_SESSION['email'];
$query = "INSERT INTO data (email, sugar, category)
VALUES($email, $sugar, $category )";
//save the output of the result
$result = mysqli_query($link, $query);
//according to the docs, mysqli_query() will return false on failure
//check for false
if( $result === false ) {
//the query failed
//provide a response to the AJAX success function
echo "Query failed. Check the logs to understand why, or try enabling error reporting.";
}else {
//the query worked!
echo 'All good!'; //provide a response to the AJAX success function
}
//Kill PHP. Good idea with an AJAX request.
exit;
}
Again, this may not solve your issue, but hopefully gets you moving in the right direction.
you have to return a response from you php script to the ajax, this would be in json or other format else, but i see in your code that you do not echo nothing in the php.
But your ajax part it is specting something to put in yor output variable and make an alert.
Try to make you php to
<?php
echo "my response";
?>
if you see your alert box that mean your problem is some php error, like conection or syntax .
Related
I've got an HTML form that uses jQuery serialize method and ajax to post results using PHP into a sqlite database. I've set the jQuery to run every minute to act as an autosave feature so users can return later to finish what they started. Because of the autosave, I can't force all inputs be required.
It works 99% of the time. However, in a few cases, the application sometimes posts blank data to the database even though there is data in the input fields. I've checked to make sure all the HTML input fields have name attributes. Any ideas why it works most of the time but in a few random cases, it doesn't?
I wish I had more to report why it doesn't work all the time. I haven't been able to replicate the bug myself, I'm just going on reports of users. But I know the form is posting blanks into the database because when I go into the database, it says " " instead of "null". So I know the database is receiving something, but it isn't receiving the data the user typed.
HTML
<form action="" method="post" id="evaluationForm">
<!-- this input is disabled since this user can't edit it -->
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" value="<?php echo htmlspecialchars($data['FirstName']);?>" disabled >
<label for="WorkHabitsCommentsSuper">Comments </label><br>
<textarea name="WorkHabitsCommentsSuper" placeholder="Comments are optional">
<?php echo htmlspecialchars($data['WorkHabitsCommentsSuper']);?>
</textarea>
<label for="GoalsSuper">More Comments</label>
<textarea name="GoalsSuper" required>
<?php echo htmlspecialchars($data['GoalsSuper']);?>
</textarea>
<!-- and a whole bunch more fields but you get the idea -->
</form>
JavaScript
function saveEval() {
var datastring = $("form").serialize();
$.ajax({
type: "POST",
url: "autosave-s.php",
data: datastring,
success: function(text) {
if (text == "success") {
alert('It saved. Hooray!');
} else {
alert('Oh no. Something went wrong.');
}
}
});
}
window.onload = function() {
setInterval("saveEval()", 60000)
}
PHP
$db = new PDO('sqlite:evals.sqlite');
$sql = "UPDATE table SET
WorkHabitsCommentsSuper = :WorkHabitsCommentsSuper,
GoalsSuper = :GoalsSuper";
$query = $db->prepare($sql);
$query->execute(array(
':WorkHabitsCommentsSuper' => $_POST['WorkHabitsCommentsSuper'],
':GoalsSuper' => $_POST['GoalsSuper']
));
echo "success";
if(!in_array("",$_POST)){
$db = new PDO('sqlite:evals.sqlite');
$sql = "UPDATE table SET
WorkHabitsCommentsSuper = :WorkHabitsCommentsSuper,
GoalsSuper = :GoalsSuper";
$query = $db->prepare($sql);
$query->execute(array(
':WorkHabitsCommentsSuper' => $_POST['WorkHabitsCommentsSuper'],
':GoalsSuper' => $_POST['GoalsSuper']
));
echo "success";
}else{
echo "Empty";
}
This will check if the posting data is not empty if empty any of the field it will not update and will send 'Empty' response so alert on empty data posting.
I have a form which I want to show the response in div via AJAX. Here is the form image from funds_transfer.php.
I test it with manual method=post and submit with the form and it works nicely. Here is the partial PHP code from funds_transfer_backend.php:
$index_num = $_POST['index_num'];
$to_account_num = $_POST['recipient'];
$amount = $_POST['amount'];
if ($amount == '' || $to_account_num == '' || $index_num == -1){
echo "Please complete the form!";
$response = -1;
}
else {
// other code goes here..
$display = array('response' => $response); // for ajax response later
echo json_encode($display);
PHP gave me this output:
Please complete the form!{"response":-1}
Now I want to implement it with AJAX and it's currently not working. Here is my current no working html + jQuery code:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function update() {
var two = $('#index_num').val();
var three = $('#recipient_box').val();
var five = $('#amount_box').val();
$.post("funds_transfer_backend.php", {
index_num : two,
recipient : three,
amount : five
},function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
}
</script>
//other code goes here..
<p>Transfer your funds to other account
<script type="text/javascript">
// Pre populated array of data
var myData = new Array();
<?php
$sql="SELECT * FROM `account` WHERE client_id='$id'";
$result=mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "myData.push('".$row['funds']."');";
$result_array[] = $row['id'];
}
?>
</script>
<form id="example" name="example">
Select your account<select id="selector" name="index_num" style="margin-left: 10px;">
<option value="-1">Account Number</option>
<?php //echo $result_array[0];
$num = count($result_array) - 1;
$i=0;
while($i<=$num)
{
echo "<option value=\"$i\">$result_array[$i]</option>";
$i++;
}
?>
</select>
<br />
Funds : RM <input type="text" id="populateme" name="funds" disabled/><br>
Recipient Account Number <input type="text" id="recipient_box" name="recipient" /> <br>
Amount : RM <input type="text" id="amount_box" name="amount"/><br>
<input type="button" value="Submit" onclick="update();">
<input type="reset" value="Reset">
</form>
<div id="stage" style="background-color:#FF6666; padding-left:20px; color: white;"></div>
<script type="text/javascript">
document.example.selector.onchange = updateText;
function updateText() {
var obj_sel = document.example.selector;
document.example.populateme.value = myData[obj_sel.value];
}
</script>
</p>
The SQL query above will fetch data from db and populated it in the select box and disabled text box. No problem with that it's currently works nicely.
The problem is there's no response in div id="stage after submit and validation data.response==-1 . I'm not sure what's the problem here probably the form didn't submit at all. Please help and thanks in advance.
Add id
<select id="index_num" name="index_num" style="margin-left: 10px;">
because you index_num value is not sending and you get a notice as response with your
json. Also remove from funds_transfer_backend.php this line -> echo "Please complete the form!"
Remove the comma on this line:
amount : five,
I think you should use $('form[name=YourFormName]').serialize();
....
var posted = $('form[name=YourFormName]').serialize();
$.post("funds_transfer_backend.php", posted ,function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
...
if you're using chrome, launch the Developer Tools (ctrl+shift+I), go to the Network tab, then submit your form. if the form is in fact being submitted, you'll be able to inspect both the request and response to see exactly what is being submitted to and returned from the server. if your form is not being submitted, due to a JavaScript error for example, the error will appear in the Console tab.
similar debugging tools exist for FireFox as well.
a couple other things to note:
1) your JavaScript is populating the "two" variable incorrectly. it references an element with id "index_num", however the id on that element is "selector". that being said, you should in fact just use the serialize() approach that Vu mentioned.
2) your PHP code is echoing a raw error message before later on echoing the actual JSON response. this results in invalid JSON. you should store the error into a variable and push that error onto the associative array with a proper key (e.g. "message"). then you can display that on your page like so:
$('#stage').show().html(data.message);
First you are echoing the error in the PHP and you are expecting a JSON in the response in the AJAX success. So first remove the following line in the server/PHP script, or say don't echo anything other than the JSON.
echo "Please complete the form!";
And ensure that your PHP output is as follows on the correct scenario.
{"response":-1}
Now your data variable in the AJAX success will contain json format only. Do a parseJSON before checking if (data.response==-1) as follows.
function(data){
data = $.parseJSON(data);
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
}
I'm quite new to PHP & MySQL and at the minute I have a web page with several text boxes that displays data that is in my database. I would like to know how I would go about updating the data by making changes to the textboxes so that when the user clicks 'update' these changes are then implemented in the database.
Currently I have the following code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("booking", $con);
$result = mysql_query("SELECT * FROM tblcompany");
$compDetails = mysql_fetch_array($result);
?>
And here is some of the HTML:
<div class="cp-controls-lrg left">
<p class="controls-margin">Company Name</p>
<input type="text" class="input-txt-med" value="<?php echo $compDetails['CompName'] ?>" id="txt-config-fax" value="" size="20">
</div>
<div class="cp-controls-lrg left">
<p class="controls-margin">Company URL</p>
<input type="text" class="input-txt-med button-space2" value="<?php echo $compDetails['CompURL'] ?>" id="txt-config-email" value="" size="50">
</div>
<div class="cp-button2 config-but-space right">
<button name="btn-config-done" id="btn-config-done" class="btn-sml ui-button ui-state-default ui-button-text-only ui-corner-all btn-hover-anim btn-row-wrapper right cp-btn-margin">Done</button>
<button name="btn-config-update" id="btn-config-update" class="btn-sml ui-button ui-state-default ui-button-text-only ui-corner-all btn-hover-anim btn-row-wrapper right cp-btn-margin">Update</button>
</div>
Any help would be much appreciated!
I assume from the tag that you want to use AJAX to achieve this.
I would first try to do the update by posting the form back using POST.
Put your HTML code into a form tag and try to POST data back to PHP page.
Here's just one example on how to do it (Google/Bing is your friend):
http://www.tizag.com/phpT/forms.php
http://www.freewebmasterhelp.com/tutorials/phpmysql/4
Then look up Insert and Update statements as suggested above and try to do the same with your data.
AJAX works in a similar way, there is a processor on the server side and the only difference is that the form doesn't get submitted via POST (page reload) but it's submitted using JavaScript.
I would also look into jQuery library to do the AJAX postbacks for you.
HTH
jQuery is excellent for ajax. You can use something like this in your javascript file whatever.js.
$('#btn-config-update').click(function () {
$.ajax({
type : 'POST',
url : 'http://whatever.com/handler.php',
dataType : 'json',
data: {
companyname : $('#companyFieldID').val(),
url : $('#companyURLID').val(),
},
success: function (data) {
if (data.status == "Success") {
$('#id_of_div_to_replace_markup').html(data.markup);
} else if (data.status == "Error"){
$('#optional_error_markup_container_div').html(data.markup);
} else {
$('#optional_error_markup_container_div').html("<span id=formError>Unexpected Error</span>");
}
}
});
return false;
});
Things to note here. Use id='whateverid" not class="whateverclass" inside of your input markup fields, so that you can get the data out of the input fields using the .val() statements that you see above. the # references in jQuery refer to a unique id.
Also the return false prevents the page from refreshing.
now for the PHP side.
$sql_error_markup = "<h1>An unexpected error has occured. Please try again later.</h1>";
$success_markup = "<h2><p>Database has been updated!</p></h2>";
$companyname = mysql_real_escape_string($_POST["companyname"]);
$url = mysql_real_escape_string($_POST["url"]);
//use your connection logic to get $con
$sql="INSERT INTO tablename (company_field_name, url_field_name)";
$sql.= " VALUES('$companyname','$lastname','$email')";
if (!mysql_query($sql,$con)) {
$return['markup'] = $sql_error_markup;
$return['status'] = "Error";
echo json_encode($return);
die('Error: ' . mysql_error());
}
mysql_close($con);
$return['status'] = "Success";
$return['markup'] = $success_markup;
echo json_encode($return);
?>
Things to note echo json_encode(array) will respond to the ajax call properly. This ajax example can swap out markup using the html method of anything with an id (not class in this example). mysql_real_escape_string will help prevent injection attacks. Extrememly necessary for this sort of form. Don't forget to include jquery.versionwhatever.js to use the $ references that you see above.
Good luck.
I am trying to create a kind of request where registered members see posts of other registered members. They might choose to connect with them before they can be able to comment on the post. What I want is to use jQuery to send the request to PHP which in turn inserts into the database with a status connection requested. When the member sees the request he can then choose to accept or reject that request. If he accepts it, the status will change to you are connected with this member.
Please I know that there are similar questions like this but not exactly as mine, somebody should please help.
'cont_email' is email of member sending request
'email_cont' is email receiving the request
'status' is the status of the connection
'counter' is request increment
This is my HTML part:
<input name="connect" type="button" value="Connect with <?php echo"$mem_com[name]";?>" class="intag2" onclick="connt()"/>
The PHP part is working ok. My only problem is sending the request through jQuery to PHP and back to jQuery which now displays the status of the connection based on members activity.
Updated answer:
Put this content into the file the user's will see (I assume thet the get parameters will be passed to this page when the user lands on them?):
<input id="connectButton" name="connect" type="button" value="<?php echo $status;?>" class="intag2" />
<script type="text/javascript">
var email_cont = '<?=$_GET[email_cont]?>';
var cont_email = '<?=$_GET[email]?>';
$('#connectButton').click(function() { // add a click event to the button (no need for onclick)
var counter = 0;
$.ajax({
url: 'requests.php?cont_email='+cont_email+'&email_cont='+email_cont+'&counter='+counter,
success: function( data ) {
$('#connectButton').val(data); // set the button value to the new status.
$('#connectButton').unbind('click'); //stop the user clicking the button loads of times.
}
});
});
</script>
Then put this in a file called requests.php:
<?php
$email_cont = $_GET['email_cont'];
$cont_email = $_GET['cont_email'];
$counter = $_GET['counter'];
$status = "Connection Sent!";
$insert = mysql_query("INSERT INTO request VALUES ('','$cont_email','$email_cont','$status', '$counter', NOW())");
$result = mysql_query($query);
if(!result){
//If it fails to run the SQL return an error.
echo "Connection Failed!";
}else{
//If all goes well, return the status
echo $status;
}
?>
Not tested, but should do what you are looking for.
I am having some issues returning data from on page, using jQuery, PHP and MySQL. I would like to show the query results on the index.php page. The results are fetched from the database using getResults.php.
When I manually run the getResults.php?id=123 file, all works fine. In this case i'm seeing the results I would like to. However, when I want to post the 'id' 123 in a submit form on index.php, I don't see any results returned by jQuery / getResults.php. Only thing that changed is the URL: index.php?id=123. However, I'm not seeing any results or an error message...
Any one an idea?
getResults.php file
$search = mysql_real_escape_string( isset ($_POST['id']));
if ($search) {
$friend = mysql_query( " SELECT * FROM reviews WHERE fbuserid = '$search' ORDER BY datumtijd DESC" );
if ( $friend ) {
while ($row = mysql_fetch_array ($friend) ) {
echo "Show some results...";
}
} else {
echo "No matches found";
}
} else {
echo "Query not succesfull";
}
index.php file
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#submit").click(function) {
event.preventDefault();
$.ajax({
url:"getResults.php",
type:"GET",
data: "id="+this.value,
success: function(data) {
$("#results").html(data);
}
});
}
return false;
});
</script>
<div>
<form>
<input type="text" name="id">
<input type="submit" value="submit" id="submit">
</form>
</div>
<div id="results"></div>
EDIT:
Thanks, all for your input. Nevertheless, I'm still not there... As you might notice, I'm not quite experienced with jQuery and PHP. See changes in scripts above. In short:
- I added the false statement if ($query) is not succesfull;
- Changed the $.post method into $.ajax;
- Changed the GET into POST in the PHP file;
Any other suggestions?
You are POSTing data but your script is looking for it in GET.
Edit in response to massive rewrite of the code in the question:
The first argument of $.ajax should be the URL.
You are missing the { from your settings object.
You are using a = instead of : for your type parameter.
You aren't doing anything to stop the normal submission of the form, so the form gets submitted and a new page loaded before the HTTP request sent by the Ajax returns.
In the first line:
$search = mysql_real_escape_string( isset ($_POST['id']));
Try changing $_POST to $_GET:
$search = mysql_real_escape_string( isset ($_GET['id']));
^^^^^
Its much better to use the jQuery ajax method to implement the ajax functionality in the script.
As it is more generalized rather than specific to one METHOD.
Below is the sample code to use the ajax method.
$(document).ready(function()
{
$("#submit").click(function)
{
$.ajax(
type="GET",
url:"getResults.php",
data: "id="+this.value,
success: function(msg)
{
$("#results").html(msg);
}
);
}
});
To check out more examples please refer to the JQUERY API Reference.
J
in if ($query) { is $query !== false ???