php to jquery on form submit - php

i have this code which ask user to input value and submit.
html
<form id="myForm" method="post" action="saving.php">
<p><label for="input1">Input 1:</label>
<input type="text" size="10" name="input1" id="input1" />
</p>
<input id="save" name="save" type="submit" value="save" />
</form>
<p><span id="thevalue"></span><span id="existornot"></span></p>
js
$("#myForm").submit(function(event) {
event.preventDefault();
$("#myForm").validate(
{ rules: {input1: "required",},
messages: {input1: "message error input"},
});
if( $("#myForm").valid()){
var $form = $("#myForm" ),
url = $form.attr( "action" ),
insertedVal=$("#input1").val();
$.post(url,{input1:insertedVal},
function(){
//displaying value condition
$("#thevalue").html(insertedVal);
// ... msg from php to be inserted to #existornot
});
}
});
saving.php
<?php
if(!empty($_POST['input1']))
{
$inputone= mysql_real_escape_string(trim($_POST['input1']));
$result = mysql_query("SELECT COUNT(*) FROM `test_table` WHERE `name` = '$inputone' ");
if (mysql_result($result, 0, 0) > 0)
{
echo "is duplicate data" ;
}
else
{
mysql_query("INSERT INTO `test_table`(name) VALUES ('$inputone')") ;
echo "is updated to db" ;
}
}
else
{
echo "could not be empty" ;
}
?>
How to pass those message of 'is duplicate data' or ' is updated to db' from the php to the javasript, to tell user that the submit process is fail or success ?
Thanks in advance for any advice.

Change the function call after the jQuery post to accept the data variable and process the results:
$.post(url,{input1:insertedVal},
function(data){
//displaying value condition
$("#thevalue").html(insertedVal);
// ... msg from php to be inserted to #existornot
if (data != 'is updated to db') {
alert(data);
}
});
}
(Data will contain what has been echoed in your save function)

The response from php file is in the ajax callback function. so you should add a parameter to your function like this:
$.post(url,{input1:insertedVal},function(resp)
{
// resp is the callback from php.
console.log(resp);
$("#thevalue").html(insertedVal);
});
For more information that how ajax works, you can follow this link: 5 Ways to Make Ajax Calls with jQuery
hope to help.

Like this:
$.post(url,{input1:insertedVal},
function(data){
//displaying value condition
$("#thevalue").html(insertedVal);
// ... msg from php to be inserted to #existornot
$("#existornot").html(data);
});
}
By adding the "data" variable to the callback function(), that "data" variable will be updated with whatever php echo's as output. You can then insert that "data" into #existornot in the callback function.
Please see the API here: http://api.jquery.com/jQuery.post/

If you want to print the value returned from php please check the jquery $.post
$.post(url,{input1:insertedVal},
function(data){
//displaying value condition
$("#somediv_id").html(data);
$("#thevalue").html();
// ... msg from php to be inserted to #existornot
});

The $.post callback function will be passed a argument containing the server response. So your $.post request should look like
$.post(url, {input1: insertedVal}, function(response) {
console.log(response); // should output the server message echoed.
});
It's also usually best to use JSON as a server response.

Related

how to get values from database phpmyadmin and show

i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?
this is my index.php
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<form>
<h1>Insert Data Into mySQL Database</h1>
Name <input name="name" type="text" id="name"> <br><br>
Lastname <input name="lastname" type="text" id="lastname"><br><br>
Email <input name="email" type="text" id="email"><br><br>
<input type="button" name="Submit" value="Submit" onclick="insertData()">
</form>
<button type="button">get values</button>
<div id="jcontent"></div>
<script type="text/javascript">
/* * Checking the Login - * */
function insertData(){
var data_get = {
'name_form': $('#name').val().trim(),
'lastname_form': $('#lastname').val().trim(),
'email_form': $('#email').val().trim()
};
$.ajax({
url : 'insert_ac.php',
type : 'POST',
data : data_get,
timeout : 30000,
success : function(response_data, text, xhrobject) {
console.log(text);
if(text == "success"){
$('#jcontent').html('Data Inserted');
}
else if(text == "ERROR"){
$('#jcontent').html('data not inserted');
}
}
});
}
</script>
/*******************************************************/
this is my insert.php
<?php
mysql_connect('localhost','root','');
mysql_select_db('loginthree');
$table_name = "test_three";
$name_form=$_POST['name_form'];
$lastname_form=$_POST['lastname_form'];
$email_form=$_POST['email_form'];
$sql="INSERT INTO $table_name(name, lastname, email)VALUES('$name_form', '$lastname_form', '$email_form')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Success";
} else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?
Well firstly, insert a:
return false;
at the end of your insertData() function, in that way you prevent the refresh of the page so that the ajax call can load its data.
Second you are returning Success and you are trying to read success, it's case sensitive and your code will not reach that if.
Resolve these issues and get back to me
Make a PHP script (lets name it getvalues.php) to return the values from the database into JSON, such as:
$result = mysql_query("SELECT * FROM $you_table"); //mod query to match what you need to fetch
$array = mysql_fetch_row($result);
echo json_encode($array);
Then in your script above include jQuery and use something along the lines of the following to retrieve the data:
$(function ()
{
$.ajax({
url: 'getvalues.php',
data: "",
dataType: 'json',
success: function ( values )
{
var value1 = values[0]; //value1, value2, etc should represent the field names in your database
var value2 = values[1];
//and so on and so forth. each field in you DB should be one index in your values array
$('#output').html("<b>Value 1: </b>"+value1+"<b> Value 2: </b>"+value2);
}
});
});

php - codeigniter ajax form validation

Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.
I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.
Here's my code so far:
my view
// If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy ?>
<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<p>
<label for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</p>
...
my controller
public function add($id){
// set validation rules in CI native
$rules = $this->product_model->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === true) {
// get post data and store them in db
$data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
$this->product_model->save($data, $id);
// no errors - data stored - inform the user with display success-div
} else {
// validation failed - inform the user by showing the errors
}
//load the view
$this->load->view('admin/products/add', $data);
}
and here’s the js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
// console.log(value);
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response); // how to output success or the errors instead??
}
});
return false; //disable refresh
});
});
How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view??
From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).
EDIT I did some changes to my application, here's the code so far:
the controller
public function manage($id = NULL){
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create(initialize inputs empty) a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model_model->make_new();
}
if (isset($_POST['general_settings'])) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
$this->product_model->save($data, $id);
$status = true;
} else {
// validation failed
$status = validation_errors();
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
redirect('admin/product');
}
//if (isset($_POST['attributes_settings'])) { the same thing here }
// load the view
$this->load->view('admin/products/manage', $data);
}
and the js
success: function(response) {
//console.log(response);
if (data.status === true) {
$('#ajaxResults').addClass('alert alert-success').html(response);
} else {
$('#ajaxResults').addClass('alert alert-error').html(response);
};
}
But I'm having some issues
Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.
2.how should I return the success message too? eg. a message saying "Saves were done!".
Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???
HTML:
<div id="ajaxResults"></div>
Javascript ajax:
success: function(response) {
$('#ajaxResults').text(response);
}
this script you've wrote is only if the validation succeeds, right?
Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.
You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.
So your PHP will looks like:
return "0 " . $errorMessage;
and
return "1 " . $successMessage;
and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.
Use this way i hope this will work for you
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function ajax_call()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"expense/home/get_expense",
data: "userid=" + ids,
success: function(result){
$("#your_div_id").html(result);
}
});
}
</script>

isset causing getjson to return undefined

I'm having a problem with my code. I want to validate my form by creating an array to contain a variable when the form is valid. But to do this I need to use the isset method to know that the information has been posted. Here's a simple example
http://richbaird.net/clregister
<?PHP
if(isset($_POST['username'])) {
$helloworld = array ("hello"=>"world","name"=>"bob");
print json_encode($helloworld);
};
if(!isset($_POST['username'])) {
echo json_encode(array('error' => true, 'message' => 'No username specified'));
?>
Simple enough if username has been posted create array helloworld.
I'm using the following method to get the json
<script>
//document ready
$(document).ready(function(){
var php = "helloworld.php";
//submit form
$("#loginform").ajaxForm
(
//on successful submission
function() {
//getjson
$.getJSON("helloworld.php",function(data) {
alert(data.message)
}) //close get json
.error(function(error) { alert(error.responsetext); })
.complete(function() { alert("complete"); });
} // close success
) // close submit
});
//end document ready
</script>
I'm using the jquery forms plugin to submit the form.
and my form looks like this
<form id="loginform" name="loginform" method="post" action="helloworld.php">
<label for="username">username</label>
<input type="text" name="username" id="username" />
<br />
<label for="password">password</label>
<input name="password" type="password" />
<br />
<input name="submit" type="submit" value="Login" id="subtn" />
</form>
the network console shows the method POST returns {hello:world name:bob} but the GET returns the no username specified which is what I get in my alert. It looks like jquery is trying to get the code before it has a chance to process entirely, how can I prevent this?
You're missing the quotes. Should be:
if(isset($_POST['username']))
You should check your console to see whether username is actually getting posted, as if it's not, you're not returning any data. You could instead consider returning an error if(!isset($_POST['username'])), perhaps something like:
echo json_encode(array('error' => true, 'message' => 'No username specified'));
EDIT
Also, remember it's $_POST, not $_post
Second Edit
Your code will be far more intuitive and readable written like this:
$return = array();
if(isset($_POST['username'])) {
$return = array("hello"=>"world","name"=>"bob");
} else {
$return = array('error' => true, 'message' => 'No username specified');
}
echo json_encode($return);
After a few hours of thinking and a lot of help from juco I realized, I'm making 2 seperate calls in this function. First I'm posting the data which works, then on a successful post I'm trying to make a seperate call, a GET request, that request contains the callback which is supposed to alert me of the result, however because it makes a 2nd call and it sends a GET request the variable POST is never set and therefore there is nothing to get back. I revised my code to only use the post method like so.
<script>
//document ready
$(document).ready(function(){
// bind form using ajaxForm
$('#loginform').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'json',
// success identifies the function to invoke when the server response
// has been received
success: processJson
}
);
function processJson(data) {
alert(data.hello);
}
});
//end document ready

JQuery .load() or .ajax() or .post() for form data to php function

Trying to implement AJAX using one of JQuery’s functions. I’ve been trying .load(), .ajax() or .post() in various ways, by using some of the examples on Stack Overflow without success.
I have a form, which queries the oracle DB, and returns another form and a results table. I have it working in the traditional way with separate PHP files (reload an entire new page). Now I want to just load the content without the page refresh.
Start Form PHP (checkin_start.php): Enter a barcode and submit…
<div class="content" id="bodyContent">
<form id="usualValidate" class="mainForm" method="post" action="">
<label>Barcode:<span>*</span></label>
<input type="text" class="required" name="startBarcode" id="startBarcode"/>
<input type="submit" value="submit" class="blueBtn" id="startBtn" />
</form>
</div>
Process PHP (checkin_process.php): a new form and the query results from the php function are loaded into id="bodyContent"…
<form id="checkinProcess" class="mainForm" method="post" action="">
<label>Barcode:<span>*</span></label>
<input type="text" class="required" name="processBarocdes" id="processBarcodes"/>
<input type="submit" value="submit" class="blueBtn" id="submitBtn" />
</form>
<!-- Shipment List Table -->
<?php
// Accept a parameter from #usualValidate form and run query.
$barcode = $_POST['startbarcode'];
search_shipped_barcode($barcode);
?>
Functions PHP (functions.php): returns results table…
<?php
function search_shipped_barcode($barcode){
<--! DB connection & query -->
echo "<table>";
<--! echo table results -->
echo "</table>";
}
?>
I think I probably have the same problem no matter which one I choose, so here's my .post() attempt. I don't quite understand how to pass the form data to my php function and return the data back...
$(document).ready(function() {
$("#usualValidate").submit(function(sevt) {
sevt.preventDefault();
var startBC = $("#startBarcode").val();
$.post("checkin_process.php",
{"startBarcode" : "startBC"},
function(data) {$("#bodyContent").html(data)},
"html");
});
});
Thanks for any insight....
When you use $.post, the values should not be quoted unless they are literals.
Try this:
$(document).ready(function() {
$("#usualValidate").submit(function(sevt) {
sevt.preventDefault();
var startBC = $("#startBarcode").val();
$.post("checkin_process.php",
{startBarcode : startBC},
function(data) {
$("#bodyContent").html(data);
// log the returned data to console for debug
console.log(data);
});
});
});
In your javascript file you can use the post method or you can use ajax like in the example below to send your data:
$.ajax({
type : 'post',
url : 'currentphpfile.php',
//Here is where the data is put
data : {
"ajax" : "1",
"otherData" : "abc"
},
success : function(data, textStatus, jqXHR) {
//Do something with the data here like insert it into the document
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//Do something to fix the error
},
dataType : 'text' //Or automatically parse a json response with 'json'
});
For this to work, you would need something in your php file that could handle the request like this:
if (!empty($_POST['ajax']) && $_POST['ajax']==1){
//Do stuff with the other post data
//Here's how to return the data to your script:
//If you chose a text response above:
echo $importantData;
exit;
//If you chose json
echo json_encode(array("title" => $title, "text" => $text /*, etc... */));
}
I haven't tested this code for bugs, but you probably get the idea.

PHP: How to excute query without form postback?

I have a form in which i want to do the validations. But there is a field which i want to validate writing a query. I dont want the form to postback because after postback all the values filled in the form are lost. Is there any way i can write a query without postback or if i have to postback how to retain the values ? Please help
If you use AJAX (jQuery), you can post an XML Request without refreshing the browser, if this is what you need.
For this, just create a form with some textfields and a submit button, give everything an ID and add an click-Listener for the button:
$('#submit-button').click(function() {
var name = $('#username').val();
$.ajax({
type: 'POST',
url: 'php_file_to_execute.php',
data: {username: name},
success: function(data) {
if(data == "1") {
document.write("Success");
} else {
document.write("Something went wrong");
}
}
});
});
If the user clicks on the button with the "submit-button"-ID, this function is called. Then you send the value of the textfield using POST to the php_file_to_execute.php. Inside this .php-File, you can validate the username and output theresult:
if($_POST['username'] != "Neha Raje") {
echo "0";
} else {
echo "1";
}
I hope that I could help you! :)
You might want to rephrase what you wrote, its a bit unclear. FYI I do it like this;
<form method="post">
Text 1: <input type="text" name="form[text1]" value="<?=$form["text1"]?>" size="5" /><br />
Text 2: <input type="text" name="form[text2]" value="<?=$form["text2"]?>" size="5" /><br />
<input type="submit" name="submit" value="Post Data" />
</form>
And when I am processing the data, it's like this;
<?php
if ($_POST["submit"]) {
$i = $_POST["form"];
if ($i["text1"] or ..... ) { $error = "Something is wrong."; }
if ($i["text2"] and ..... ) { $error = "Maybe right."; }
if (!$error) {
/*
* We should do something here, but if you don't want to return to the same
* form, you should definitely post a header() or something like that here.
*/
header ("Location: /"); exit;
}
//
}
if (!$_POST["form"] and !$_GET["id"]) {
} else {
$form = $_POST["form"];
}
?>
By this method, the values are not lost unless you set them to get lost.
Use jQuery's $.post() method as:
$('#my_submit_button').click(function(event){
event.preventDefault();
var username = $('#username').val();
$.post('validate.php', {username: username, my_submit_button: 1}, function(response){
console.log(response); //response contain either "true" or "false" bool value
});
});
In validate.php get the username from your form asynchronously as like this:
if(isset($_POST['my_submit_button']) && $_POST['my_submit_button'] == 1 && isset($_POST['username']) && $_POST['username'] != "") {
// now here you can check your validations with $_POST['username']
// after checking validations, return or echo appropriate boolean value like:
// if(some-condition) echo true;
// else echo false;
}
Note: Please consider knowing security-related vulnerabilities and other issues before using AJAX for executing database-altering scripts.

Categories