Passing result from AJAX call to PHP script - javascript

I'm working on my first HTML form that performs an AJAX HTTP POST using jQuery. When a user makes a change to an input text field and tabs out of the field it triggers the AJAX script which in turn calls a PHP script which performs a database update.
The AJAX call can be successful but the database update could be unsuccessful (e.g. database related error) - I would like to insert the result of the PHP script into an alert. I can echo out any errors in in my PHP script, but I'm not sure how to get that into the appropriate alert.
Here's my Javascript:
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){
var storeManager = $("#storeManager").val();
$.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
$("#managerRow").addClass("success");
}).fail(function () {
// no data available in this context
$("#managerRow").addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
});
</script>
Here's the HTML table that contains the input field that triggers the AJAX call:
<table class="table table-striped table-bordered table-hover">
<tbody>
<tr>
<td>Store</td>
<td>Acme Widgets Inc</td>
</tr>
<tr>
<td>Retailer</td>
<td>Acme Corp</td>
</tr>
<tr>
<td>Store ID</td>
<td>9876543</td>
</tr>
<tr>
<td>State</td>
<td>NSW</td>
</tr>
<tr class="" id="managerRow">
<td>Manager</td>
<td>
<input type="text" class="form-control" id="storeManager" name="storeManager" value="Peter Johns">
</td>
</tr>
<tr>
<td>Phone</td>
<td>9222 3456</td>
</tr>
</tbody>
</table>
<div class="" id="ajaxAlert" role="alert"></div>
What I would like to do is, if there is any error from the editProject.php script that it stores in a $error variable and can echo out, to then insert this into the ajaxAlert and add a class: alert:
<div class="alert alert-danger" id="ajaxAlert" role="alert">The error from the database update from the php script appears here</div>
I'm new to jQuery and AJAX and everything I've tried hasn't updated the alert with the new class and alert text and I can't seem to find a similar to example that demonstrates this.

You can use the append() in jquery. Try using
fail(function () {
// no data available in this context
$("#managerRow").addClass("danger");
//append error to the div using its ID
$('#ajaxAlert').append('error from database');
});

Try this: instead of .fail();
var storeManager = $("#storeManager").val();
$.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
alert(data);
},function (xhr, data, jx) {
// the error function should be mentioned like this with comma after success fucntion
console.log(xhr);//for console logging the error...
alert(xhr);//NOW you will get data and alert will show...
});

index.php
----php start---------
if(isset($_POST['name'])){
$dbc = mysqli_connect('','','','');
$sql = "UPDATE accounts set name='".$_POST['name']." WHERE email='".$_POST['mail']."' LIMIT 1";
if(mysqli_query($dbc, $sql) === true)){
echo 'success'; exit();
}else{
echo 'connection error'; exit();
}
}
----php end ---------
<script>
function test(){
var formDATA = {
'name': $('#input_name').val(),
'mail': $('#input_mail').val()
};
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
if(response == 'success'){
$('#result').html('Your Update Was Complete');
}else{
$('#result').html();
}
}
});
}
</script>
<input id="input_mail" type="text" value="">
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code. Also don't forget to include your jquery resources.
WARNING: DO NOT DO QUERIES LIKE THE EXAMPLE, THIS IS A HUGE SECURITY RISK!

Related

Ajax post not working codeigniter

I am using codeigniter 3.1
Ajax post not working and i am getting 403 (Forbidden) in console.
[POST http://localhost/test/post 403 (Forbidden)]
HTML
<div class="post">
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
</div>
<button id="post">Submit</button>
JAVASCRIPT
$('#post').on('click', function () {
var value1=$("#data1").val();
var value2=$("#data2").val();
$.ajax({
url: window.location.href+'/post',
type: "POST",
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
});
CONTROLLERS
public function post()
{
$data1 = $this->common->nohtml($this->input->post("data1", true));
$data2 = $this->common->nohtml($this->input->post("data2", true));
$this->data_models->update($this->data->INFO, array(
"data1" => $data1,
"data2" => $data2,
)
);
}
If you want CSRF protection on (a good idea) then you must pass the CSRF token when posting form data - via AJAX or not. Consider this approach.
The easiest way to put the token in your form is to use Codeigniter's "Form Helper" (Documented here) You can load the function your controller or use autoloading. This view code assumes you have the helper loaded.
HTML
<div class="post">
<?= form_open('controller_name/post'); //makes form opening HTML tag ?>
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
<?php
echo form_submit('submit','Submit', ['id'=>'post']); //makes standard "submit" button html
echo form_close(); // outputs </form>
?>
</div>
The form_open() function also automatically adds a hidden field containing the CSRF token to the HTML.
Javascript
$('#post').submit(function( event ) {
//the next line will capture your form's fields to a format
//perfect for posting to the server
var postingData = $( this ).serializeArray();
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
data: postingData,
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
controller
By the time $_POST gets to your controller the CSRF token has been striped away so you don't have to worry about it "polluting" your incoming data.
public function post()
{
//get all the posted data in one gulp and NO, you do not want to use xss_clean
$posted = $this->input->post();
//With the above the var $posted has this value (showing made up values)
// array("data1" => "whatever was in the field", "data2" => "whatever was in the field");
//sanitize the field data (?)
//just stick the clean data back where it came from
$posted['data1'] = $this->common->nohtml($posted["data1"]);
$posted['data2'] = $this->common->nohtml($posted["data2"]);
$this->data_models->update($this->data->INFO, $posted);
//you must respond to the ajax in some fashion
//this could be one way to indicate success
$response['status'] = 'success';
echo json_encode($response);
}
You could also send back some other status if, for instance, the model function reported a problem. You then need to react to that status in you javascript. But if you don't respond it will likely result in problems down the road.

Ajax using GET to PHP

I have seen many posts close to this but not this specifically so I will still ask it. I have a simple webpage that I am using to pass a value from to a server and then based on the value pass a response to the original webpage. Right now for testing purposes I am just using an alert for the final value.
My client side code is as follows submitAjax.php:
<!DOCTYPE html>
<html>
<head>
<script src="./jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#thisForm").submit(function () {
processData();
});
function processData() {
$.get('ajaxSubmit.php', function(data) {
alert(data);
});
}
});
</script>
</head>
<body>
<form method="get" id="thisForm">
<tr>
<td><input type=text name=box ></td>
<td><input type=submit value=Add></td>
</tr>
</form>
</body>
</html>
Server side ajaxSubmit.php:
<?php
$value=$_GET["box"];
if ($value==2){
echo "This is the returned text.".$value;
}else{
echo "not sent";
}
?>
As you can see from the code, I am trying to print the text "This is the returned text.2" as the output but when I enter "2" into the textbox my failure case of "not sent" is returned.
Any help would be great. I am very very new to all things javascript so please point out anything else I am doing incorrectly as well.
You're not passing anything when you're requesting ajaxSubmit.php.
$.get('ajaxSubmit.php?box=' + $("[name='box']").val(), function(data) {
alert(data);
});
So you want to request, ajaxSubmit.php?box=value, where value is the value of the html element named box.

How To Pass Dynamically Added Table Rows Form Values to Javascript Using Post to Send Database

I am using Laravel.
I have dynamic rows and each row has own form with individual values.
I am trying to pass each row form with values when submit the button to Javascript.
To retrieve data in Server.I don't want to refresh page because I am using Modal.
Here is my Code
<table id="selectedWagesTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Worker</th>
<th>Balance</th>
<th>Confirm</th>
</tr>
</thead>
<tbody>
#foreach($items as $item)
<tr>
<td class="standartTable2">
<?php echo $item['worker_id'] ?>
</td>
<td class="standartTable2">
£ <?php echo $item['balance'] ?>
</td>
<td class="standartTable2">
{{ Form::open(['id'=>item['workerId'],'name' => item['workerId']]) }}
{{ Form::hidden('workerId', $item['workerId'],['id' => $item['workerId'])}}
{{ Form::hidden('balance', $item['balance'],['id' => $item['balance']])}}
{{ Form::submit('Click To Confirm',
array(
'class'=>'btn btn-sm btn-success',
'id'=>'submitButton',
'oncontextmenu'=>'return false',
)) }}
{{ Form::close() }}
</td>
</tr>
#endforeach
</tbody>
Script
<script type="text/javascript">
$(document).ready(function(){
$("#submitButton").click(function(e){
e.preventDefault();
$.get('hpoAccounts',function(data){
console.log(data);
});
});
$("#submitButton").click(function(e) {
e.preventDefault();
var workerId = $('#workerId').val();
var balance = $('#balance').val();
$.post('hpoAccounts',{
workerId:workerId,
balance:balance
},
function(response,status){
console.log(response);
});
});
});
What you want to achieve could be done using jQuery library
Since you have several forms, you need to add a submit listener to all of them ( $("form").submit ).
To prevent the REFRESH we need to send the data using ajax ( $.ajax ) and prevent default SUBMIT behavior ( e.preventDefault() ).
Note also that we add the listeners to the forms after all the HTML document is ready ( $(document).ready ).
Below code should work after you provide the POST URL.
$(document).ready(function() {
$("form").submit(function(e){
var formData = $(this).serializeArray();
$.ajax({
url : 'your post resource', // put here the URL resoruce where you want POST the data
type: "POST",
data : formData,
success:function(data, textStatus, jqXHR)
{
alert('Do something after data sent!');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('There was an error!');
}
});
e.preventDefault(); //prevent default action which will prevent also the REFRESH
});
});
I have solved my problem using Javascript.
I removed form and simply added one button to last column.With Javascript when I clicked the button I can pull the values from each row.
<td class="standartTable2">
<button type="button" class="btn btn-success hit">Confirm Payment</button>
</td>
Script
<script type="text/javascript">
$(document).ready(function(){
$(".hit").click(function(){
this.disabled = true;
// nth-child(2) first-child last-child
var hpos_id=$(this).parent().siblings(":first").text();
var balance=$(this).parent().siblings(":nth-child(3)").text();
var dataArray = {hpos_id: hpos_id, balance: balance};
$.ajax({
url : '/confirmPayment', // put here the URL resoruce where you want POST the data
type: "POST",
data : dataArray,
success:function(data, textStatus, jqXHR)
{
//All good
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('There was an error!');
}
});
});
});

Sending php generated form data via Ajax from Dialog box

Hi Guys any help on this? I have a dialog box triggered by a button click that calls my php script to generate a form which needs to be filled and submitted. I want to do the sending and conformation via Ajax. I have been recoding and researching for a few days but nothing on StackExchange or other websites help me with it.
Here's the code:
Dialog box snippet;
$k('#CreateTable').click(function(e){
e.preventDefault();
var Call = $k('#CreateTable').attr('value');//.attr('id');
var util = $k(this).attr('id');//.attr('id');
$k('#dialog').dialog({
autoOpen: false,
title: 'Running Utility for: '+Call,
modal: true,
width: 450,
close: function(event, ui) {
$k("#dialog").dialog('destroy');//event.target
}//END CLOSE
}).dialog('open');
var utility = { 'utility' : util };
$k.ajax({
type: "post",
url: "inc/runUtilities.php",
dataType: "html",
data: utility,
success: function(data) {
$k('#DlgTxt').html(data).fadeIn('slow');
}
});
//return false;
});//END DIALOG
The PHP snippet;
$show .= "<form id='cContact' name='cContact' method='post'>";
// action='".$_SERVER['REQUEST_URI']."'
$show .= '<table align="center" width="425" border="0">
';
$query = "SHOW COLUMNS FROM `".$_SESSION['WorkTable']."`";
if($output = mysqli_query($this->MySQLCxn->MySQLCxn, $query))
{
$columns = array();
while($row = mysqli_fetch_assoc($output))
{
if($row['Field'] == 'id') {}
else
$show .= '
<tr>
<td width="175"><div align="right">'.#$row['Field'].':</div></td>
<td width="155">
<input type="text" name="'.#$row['Field'].'" placeholder="'.#$row['Field'].'" />
</td>
<td width="115"> </td>
</tr>
';
}
}
$show .= '
<tr>
<td>Submit </td><td>
<button type="button" id="cContactSbmt" onclick="doSubmitForm(this); return false;" name="cContactSbmt" value="cContactSbmt">Create contact</button>
<!-- <input type="submit" class="button" value="Save" name="submit"> -->
</td> <td> </td>
</tr>
</table></form>
<div id="thanks">
</div>
';
And the JQuery that i am currently using trying to have it call my php to process the form being sent.
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function() {
$j("#cContactSbmt").click(function(e){//'click',
e.preventDefault();
alert('cContactSbmt clicked...');
$j.ajax ({
type:"POST",
url:"inc/runUtilities.php",
data: $j(this).serialize(),
success: function(msg){
$j("#thanks").html(msg)
$j(this).modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
})($j);
For some reason its not working nothing showing up in the console as well.
again: i have a dialog box that gets populated via Ajax with a php generated from that needs to get submitted to another php script that is to process it and reply to the dialogs.
Any suggestions?
your php ist not outputting ("echoing") anything. you need to echo whatever you want to return to your ajax-call.
update: plus for debugging try to log the returned data in every success callback, for example:
success: function(data) {
console.log(data);
}
You may need to add an echo to the end of your php snippet..
echo $show;
This echoed html will then be available in your ajax function in the success callback function... as the variable "data"
success: function(data) {
$k('#DlgTxt').html(data).fadeIn('slow');
}
Also you may need to use jQuery .on() in your click function..to submit the form..
http://api.jquery.com/on/
$j("body").on("click", "#cContactSbmt", function(){
});
Hope this helps....
Hi Guys so I got it working with the following changes:
On the form;
<button id="cContactSbmt" onClick="doContactsCreate(\'#cContact\')" type="button" class="form-submit" name="cContactSbmt" value="cContactSbmt">Create contact</button>
I added the onclick method with a callback to a function doContactsCreate(\'#cContact\'), which has the id of the form passed to it.
function doContactsCreate(obj)
{
alert(obj+': cContactSbmt clicked...');
/* */
var frmData = $k(obj).serialize();
$k.ajax ({
type:"POST",
url:"inc/runUtilities.php",
data: frmData,
success: function(data){
$k("#thanks").html(data);
console.log(data);
$k(obj).modal('hide');
},
error: function(){
alert("failure");
}
});
}
I've just enclosed the JQuery code in this function definition and placed it outside the
(function($k){
$k(document).ready(function() {
//rest of JQuery code
})($k);
Don't know why but i think that was the main problem

unable to show success message after submitting a form using ajax

I am sending email using ajax after when ajax form is submitted.
Here is my php controller code:
If i keep the email sending code inside this function then the SUCCESS message is not showing on the html page. But if i remove the Email sending code from that function then SUCCESS message is showing.
public function sendedits()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('menu_name', 'Title', 'trim|required|min_length[2]|max_length[255]|xss_clean');
//user is logged in proceed the next work
if (!$this->form_validation->run())
{ //False
$this->_status['status'] = "error";
$this->_status['message'] = $this->load->view('commonfiles/ajax_error_display_1', '', TRUE);
}
else if ($this->form_validation->run() && $this->input->post('myId')=='')//myId=just for checking robot or human
{ //TRUE block
$fname=$this->input->post('menu_name');
$sendersemail=$this->input->post('changes_made');
$intrested_message=$this->input->post('content');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = 'asdsdsd#gmail.com';
$config['smtp_pass'] = 'sdsfsdfsdfsdfsds';
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
//$this->email->from($sendersemail, $fname);
$this->email->to('ssdd#myemil.com');
$this->email->subject('User Edited article of : '.$fname);
$message = '<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;width:98%;background-color:whitesmoke" border="1">
<tbody>
<tr>
<td colspan=2><h2> '.$fname.'</h2></td>
</tr>
<tr>
<td width=50%>First Name </td>
<td width=50%>'.$fname.'</td>
</tr>
<tr>
<td width=50%>Email </td>
<td width=50%>'.$sendersemail.'</td>
</tr>
<tr>
<td width=50%>Message </td>
<td width=50%>'.$intrested_message.'</td>
</tr> </tbody> <table> </body></html> ';
$this->email->message($message);
$this->email->send();
$this->_status['message'] = 'Thankyou for your edits. We will review it before publishing.';
$this->_status['status'] = "success";
}
echo json_encode($this->_status);
}
Ajax function for submitting the form
<script type='text/javascript'>
$(document).ready(function() {
var _status = $('#status');
$('#sub2').click(function(e) {
_status.html('');
var postData = $('#form_id').serializeArray();
var formURL = $('#form_id').attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
dataType: "json",
success: function(dat) {
if (dat.status === 'success') {
_status.html('<span class="success">' + dat.message + '</span>');
}
else if (dat.status === 'fail') {
}
else
{
_status.html('<span class="err">' + dat.message + '</span>');
}
},
error: function(e) {
alert("Ooops! Try again later or else sends us message regarding this issue. Thankyou!");
}
});
});
});
</script>
So Im guessing this is using the phpmailer library, do you have that installed (it might come as default depending on your platform)
The first thing that I can see is that $sendersemail is not defined. Try inserting a string instead of the variable. The phpmailer library is terrible for cactching errors, I can never figure out how to tell where the errors are either!
If that doesnt work, try outputting to the console after the line you think is giving you the error. If you use:
echo("email sent");
Then you should see it in the browser console as the code is being processed. Hopefully you can see where the error is coming from then.

Categories

Resources