I am trying to add data to a database and for some reason it does not always work. I'd say 80% of the time it will work and I'll see the result in the database but sometimes its like the script won't run.
here is the ajax :
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('.error').hide();
$("#success").hide();
$(".button").click(function () {
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: $("input#name"),
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
});
});
});
});
</script>
here is the html:
<div id = "contact_form">
<form name ="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="send" />
</fieldset>
<span id="success"> the name has been updated successfully!</span>
</form>
</div>
<div id ="upd"></div>
and here is the proccess.php file:
<?php
$va = $_POST["name"];
$dbconnection = mysql_connect('adatabase','someuser','somepw');
if(!mysql_select_db('some_database', $dbconnection)) {
echo mysql_error();
}
else
{
echo 'connection success';
}
$sql = "INSERT INTO some_db(text) VALUES ('$va')";
$result = mysql_query($sql) or die('erreur sql!'.mysql_error());
if(!$result) {
echo "not working";
}
else {
echo "working";
}
?>
so how come it does not always insert into the database?
and is there a way to get the result from the php if(!$result) to show in the success part of the ajax?
You're actually passing a jQuery-Object to your PHP-File.
$.post("class/proccess.php", {
name: $("input#name").val() //Pass val() not the whole jQuery-Object!
}, function() {
/* success */
});
While you're debugging, make sure MySQL errors are enabled.
In your Javascript for the Ajax success handler, show an alert with the text returned from the call. That way if there's an error with MySQL you'll see it.
Another thing is, could the "text" field be set in the database as UNIQUE? Trying to insert a new record with a duplicate string would fail in that case.
And... the name of the field isn't really 'text' is it? I would recommend avoiding field names that are the same as the basic data types for MySQL. Just to avoid confusion if no other reason.
If it is not working sometimes, you need to check the returned string for errors. The right way to do this using AJAX is as follows.
You can include a parameter in your success callback which will fetch the page-result from the PHP.
Instead of
success: function () {
...
}
use
success: function (data) {
alert(data);
}
Change your ajax call to:
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: {name : $("input#name").val()},
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
So that $_POST['name'] is set to the value of your input box.
Also, as suggested, you should change your mysql functions to mysqli functions to help protect against sql injections.
Related
I have simple, form which works with Jquery Ajax, but I don't know how can I get my Errors from php.
My Form
<form action="customer.php" method="post" class="addForm">
<input name="username" type="text" placeholder="username"> <br>
<input name="name" type="text" placeholder="name"> <br>
<button type="submit" name="btnAdd">Add New Customer</button>
</form>
My Script
<script>
$(document).ready(function() {
$("form.addForm").submit(function(e) {
e.preventDefault();
// form's url and method
var addForm_URL = $("form.addForm").attr("action");
var addForm_Method = $("form.addForm").attr("method");
var username_Val = $("input[name='username']").val();
var name_Val = $("input[name='name']").val();
var btnAdd_Val = $("button[name='btnAdd']").val();
$.ajax({
url: addForm_URL,
method: addForm_Method,
data: {
username_Post: username_Val,
name_Post: name_Val,
btnAdd_Post: btnAdd_Val
},
success: function(data) {
if (data) {
console.log(data);
$("input[name='username']").val("");
$("input[name='name']").val("");
} else {
console.log(data); // here should be my errors
}
}
});
});
});
</script>
My php
if (isset($_POST['btnAdd_Post']) && empty($_POST['username_Post'])) {
//some stuff
echo 'Error 1';
}
if (isset($_POST['btnAdd_Post']) && $_POST['name_Post'] == "my1") {
//some stuff
echo 'Error 2';
}
if (isset($_POST['btnAdd_Post']) && !empty($_POST['name_Post'])) {
//some stuff
echo 'Error 3';
}
As I use e.preventDefault(), I can't use any exit() or headers in my php.
How can I get my echo Error 1,2,3 from php put in my Ajax and priant some stuff or redirect ?
Thanks
The problem is that you dont allow the post so the you cant get the $_POST info, so ether you have to let it go through with the post and catch the errors with php or log the errors with jQuery.
As far as I'm aware the you do the ajax call to prevent to reload the page and thus not accessing the PHP, but this means you'll have to catch the errors with jQuery as well.
I'm trying to update a simple string to the database with PHP and AJAX.
Here is the code:
HTML
<form id="phoneNumberForm" class="form-inline" method="post" enctype="multipart/form-data">
<div class="form-group mx-sm-3 mb-2 align-content-center">
<label for="phoneNumber" class="sr-only">Phone</label>
<input type="text" class="form-control" name="phoneNumber" id="phoneNumber" placeholder="Phone">
</div>
<button type="submit" name="phoneNumber_submit" id="phoneNumber_submit" class="btn btn-primary mb-2">Save</button>
<div id="phoneSuccess"></div>
</form>
PHP
if (isset($_POST['phoneNumber_submit'])) {
$phoneNumber = $_POST['phoneNumber'];
$profileEditAdmin = $db->query('UPDATE users SET user_phone = ? WHERE user_name = ?', $phoneNumber, $_SESSION['user_name']);
}
AJAX
$('#phoneNumberForm').submit(function(e) {
e.preventDefault();
let phoneNumber = $('#phoneNumber').val();
let $body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
$.ajax({
type: "POST",
data: {
phoneNumber:phoneNumber,
},
success: function() {
$('#phoneSuccess').html('<p>Saved.</p>');
setTimeout(function() {
$('#phoneSuccess').fadeOut();
}, 2000)
}
});
});
When I remove preventDefault() I get the entry in the database, but page is reloaded.
My goal is to have an entry in the database and to avoid page refreshing.
Here your PHP looks for a variable called phoneNumber_submit:
if (isset($_POST['phoneNumber_submit'])) {
But here your AJAX sends only a variable called phoneNumber:
data: {
phoneNumber:phoneNumber,
}
Clearly these two names do not match, so the if statement will never be true and the query will never run. It works when you submit the form without AJAX because you have name="phoneNumber_submit" on your submit button, so this value is sent to the server.
So you can either:
1) hard-code this value into your data parameter:
data: {
"phoneNumber": phoneNumber,
"phoneNumber_submit": true
}
OR
2) just let jQuery do the work for you and use the serialize function to get all the values and names you've already defined in your HTML and send them directly to the server, without you needing to specify each one again:
data: $(this).serialize()
Note: this in the above code will be your <form> element since you're handling the form's "submit" event.
<form role="form" method="post" action="test.php">
<label for="contact">Mobile No:</label><br>
<input type="tel" class="form-control" name="contact" title="Mobile number should not contain alphabets. Maxlength 10" placeholder="Enter your phone no" maxlength="15" required id='contact_no'>
<br><br>
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
<button type="reset" class="btn btn-default" id='reset'>Reset</button>
</form>
Ajax and Javascript Code
script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dialcode = $(".country-list .active").data().dialCode;
var contact = $("#contact_no").val().replace(" ","");
var countrycode = $('.country-list .active').data().countryCode;
var cn;
var cc;
var dc;
$.ajax({
url: "test.php",
type: "POST",
data: {'cc' : contact},
success: function(data)
{
alert("success");
}
});
});
});
</script>
The variables show the values if displayed by alert message but are not passed on to the test.php page. It shows undefined index error at the following statement
test.php is as follows
<?php
if(isset($_POST['submit'])){
$contact = $_POST['cc']; //it shows the error here
}
echo $contact;
I had referred to many websites which show the same thing. It dosent work for me. I think the syntz of ajax is correct and have tried all possibilities but still dosent work. Please help
You're posting {cc: contact}, but you're checking for $_POST['submit'] which isn't being sent. The callback also doesn't stop the event, so you might want to return false (stops default and propagation). Something like this should do the trick:
$('#submit').on('click', function()
{
//do stuff
$.ajax({
data: {cc: contact},
method: 'post',
success: function()
{
//handle response here
}
});
return false;
});
Then, in PHP:
if (isset($_POST['cc']))
{
//ajax request with cc data
}
Also not that this:
$("#contact_no").val().replace(" ","");
Will only replace 1 space, not all of them, for that you'll need to use a regex with a g (for global) flag:
$("#contact_no").val().replace(/\s+/g,"");
You are using ajax to form submit
and you use $_POST['submit'] to check it would be $_POST['cc']
test.php
<?php
if(isset($_POST['cc'])){// change submit to cc
$contact = $_POST['cc'];//it shows the error here
}
echo $contact;
#Saty answer worked for me, but my code on ajax was a bit different. I had multiple form data wrapped up into a form variable, that was passed to the php page.
const form = new FormData();
form.append('keywords', keywords);
form.append('timescale', timescale);
form.append('pricing_entered', pricing_entered);
$.ajax({
url: "../config/save_status.php",
data: form,
method: "POST",
datatype: "text",
success: function (response, data) {
}
Then my php was:
if (isset($_POST['data'])) {
// all code about database uploading
}
is there a common problem that would cause my textarea to break the update query if it has more text than a single sentence in it?
The update query runs fine when I only input a single sentence, but anything more than a sentence breaks the query.
Here is the form code:
<form id="cp_files_admin_form" method="post" enctype="multipart/form-data">
<label>File Manager Login Text</label>
<input id="login_text" type="text" name="login_text" value="File Manager Login">
<hr>
<label>File Manager Login Logo</label>
<input id="login_logo" type="file" name="login_logo">
<hr>
<label>Main Left Logo</label>
<input id="main_left_logo" type="file" name="main_left_logo">
<hr>
<img class="form-img" src="" alt="">
<label>Main Center Logo</label>
<input id="main_center_logo" type="file" name="main_center_logo">
<hr>
<label>File Manager Instructions Text</label>
<textarea id="instructions_text" name="instructions_text" style="width:630px;height:150px;"></textarea>
<input id="submit" type="submit" value="Submit">
</form>
Here is the jQuery code:
$(document).ready(function() {
// Update CMS
$(document).on('click', '#submit', function() { // catch the form's submit event
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
// fetch the data for the form
var data = $('#cp_files_admin_form').serialize();
console.log('Form Data Before Sent: '+data);
$.ajax({
url: 'update.php',
data: data,
type: 'GET',
async: 'true',
dataType: 'json',
success: function (result) {
if(result.status) {
alert('CMS Update Successful!');
getCMS();
} else {
alert('CMS Update unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
return false; // cancel original event to prevent form submitting
});
});
Here is the update.php code:
<?php
header("Access-Control-Allow-Origin: *");
require_once("debug/chromephp.php");
$formData = $_GET;
ChromePhp::log('$_GET Data: '.$formData['instructions_text']);
require_once("config.php");
$login_text = $formData['login_text'];
//$login_logo = $formData['login_logo'];
//$main_left_logo = $formData['main_left_logo'];
//$main_center_logo = $formData['main_center_logo'];
$instructions_text = $formData['instructions_text'];
$sql="UPDATE cp_cms SET login_text='$login_text', instructions_text='$instructions_text' WHERE id = 1";
$result = mysql_query($sql);
if($result) {
// Success
$output = array('status' => true, 'massage' => 'Success!');
echo json_encode($output);
} else {
// Failed
$output = array('status' => false, 'massage' => 'Failed!');
echo json_encode($output);
}
?>
Screenshot of table structure:
Any help is much appreciated.
try this, it prevents entries in the form from breaking your sql queries. Which is also called SQL-Injection Attack ...
$sql="UPDATE cp_cms SET login_text='".
mysql_real_escape_string($login_text)."', instructions_text='".
mysql_real_escape_string($instructions_text)."' WHERE id = 1";
but please have a look at PDO it is so much safer and easier ...
Edit: I dug some PDO example up:
http://www.phpeveryday.com/articles/PDO-Prepared-Statement-P552.html
I'm new to jQuery / AJAX.
I'm trying to send single input with jquery/ajax/php.
LIVE EXAMPLE
But, after pressing submit nothing is happening, where is my error?
Any help much appreciated.
HTML:
<form action="submit.php">
<input id="number" name="number" type="text" />
<input id="submit" name="submit" type="submit" />
</form>
JQUERY / AJAX:
$(document).ready(function(e) {
$('input#submit').click(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
PHP:
<?php
$mailTo = 'email#gmail.com';
$mailFrom = 'email#gmail.com';
$subject = 'Call Back';
$number = ($_GET['number']) ? $_GET['number'] : $_POST['number'];
mail($mailTo, $subject, $number, "From: ".$mailFrom);
?>
HTML:
<form id=submit action="">
<input id="number" name="number" type="text" />
<input name="submit" type="submit" />
</form>
The action URL is irrelevant as you want to submit your data via AJAX. Add the submit id to the form and override the default submit behavior, instead of overriding the onclick handler of the submit button. I'll explain in the JS section.
JS:
var number = $('input[name="number"]');
Quotes were missing.
$(document).ready(function(e) {
$('#submit').submit(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
I don't really understand your success callback, why do you expect that html should be equal to 1?
Atleast I got 404 error when pressed your submit button:
Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
When you get it to work, remember to add mysql_real_escape_string function to avoid SQL injections http://php.net/manual/en/function.mysql-real-escape-string.php
Since you are also using ID for number, you could just use: var data = 'number=' + $('#number').val()
Also if you add ID to your form, you can use:
$('#formId').submit(function(){
});
instead of that click. This function will launch when that form is submitted. This is better way because users can submit the form with other ways aswell than just clicking the submit button (enter).
var number = $('input[name=number]');
is wrong. It's
var number = $('input[name="number"]');