Sending php generated form data via Ajax from Dialog box - javascript

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

Related

Ajax function call not working

I am trying to learn Ajax function calls in jquery. But I could not get the expected output. My code is below
The HTML and Script File is stored in the file 'addevent.php'
HTML Code:
<form id="addinfo">
Year: <div class="styled-select">
<select id="year">
<option>2017</option><option>2018</option>
<option>2019</option><option>2020</option>
</select>
</div>
Team:<div class="styled-select">
<select id="team">
<option>UG</option><option>PG</option>
</select>
</div>
<button class=btn name="add_event" id="add_event" />Add Event
<span id="result"></span>
</form>
</body>
</html>
Script Part:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: 'checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
}
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
The code in the file checkevent.php is below
header("Content-Type: application/json", true);
$db = new PDO('mysql:host=localhost;dbname=register;charset=utf8mb4', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$year =$_POST['year'];
$team =$_POST['team'];
$table=$team.$year;
try
{
if ($db->query("SHOW TABLES LIKE '" . $table . "'")->rowCount() > 0)
{
$r=array("result"=>"already stored");
echo json_encode($r);
}
else
{
$r=array("result"=>"continue");
echo json_encode($r);
}
}//end of try
catch(PDOException $e)
{
$r=array("result"=>"error");
echo json_encode($r);
}//end of catch
?>
Please Note: I have stored the file 'addevent.php' (HTML+Script) in the location 'registration/view/'
The checkevent.php file is stored in the location 'registration'
I tried to check if the button click function for add_event button is working by placing an alert inside it. But it doesn't work.
My expected output is if the table exist the span should display 'already stored' else it should say 'continue'
P.S: I am new to using these ajax call,so sorry if this seems silly. Please help to understand these concepts clearly.
Thanks in advance
You change this line :
url: 'checkevent.php',
By this :
url: '../checkevent.php',
Type F12 and inspect your ajax Call in the console to see if everything is OK
EDIT
OK got it. You missed a comma between success and error callbacks, which broke your Javascript...
Please change script to this and it should work:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: '/registration/checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
},
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
You have a <button> element inside a form. The default type of a button is type="submit" and therefore the form is submitted before the button onclick listener works. Also you need to close a button element with </button>
Try to change it from
<button class=btn name="add_event" id="add_event" />Add Event
to
<button type="button" class=btn name="add_event" id="add_event" >Add Event</button>
As for the ajax URL, if you are running it from a page located in 'registration/view' and you're calling a page located in 'registration', you need to change the url to something like: url: '/registration/checkevent.php'
because the php file isn't located in the same place as the script that's calling it.
Good luck

Updating data with Ajax loading does not work

I have an admin page which can insert, update and delete data. I want to display a simple loading gif while doing any of these operations. All of the 3 operations work perfectly, but when I try to make some Ajax with it, it stops working.
Below is my Ajax code. This code simply shows a div which has the loading gif within it, right after submitting the form, and if it's successfully accomplished, hides it again. That easy.
$("#form").submit(function(e) {
e.preventDefault();
$("#loading").show();
$.ajax({
url: "Operations.php",
dataType: "HTML",
success: function() {
$("#loading").hide();
}
});
});
Now, the Operations.php, that is executed by every form, contains the 3 database operations. It stores the name of the class sent by a hidden field, receives the value from the button of the submitted form and depending on its value, it instantiates the ServiceDatabase passing the class and perform one action.
$class = filter_input(INPUT_POST, "class");
$id = filter_input(INPUT_POST, "id");
#require_once "../../php/Connection.php";
#require_once "../../php/ServiceDatabase.php";
#require_once "../../php/" . $class . ".php";
$Operation = new ServiceDatabase($connection, new $class);
switch ($_REQUEST["submit"]) {
case "insert":
$Operation->setPostVariables();
$Operation->insert();
break;
case "update":
$Operation->setPostVariables();
$Operation->update($id);
break;
case "delete":
$Operation->delete($id);
break;
}
And finally, just the form.
<form id="form" class="center-block" action="Operations.php" method="post">
<h3>Alterar - <small><?php echo $class ?></small></h3>
<input type="hidden" value="<?php echo $class ?>" name="class"/>
<input type="hidden" value="<?php echo $id ?>" name="id"/>
<?php echo $Table->generateAdminTables($id); ?>
<button type="submit" name="submit" value="update" class="btn btn-success btn-update">Atualizar</button>
</form>
What happens is that the database operation, in this case, the update, doesn't work, like if it is not reaching the Operations.php file.
You need to set the POST data which you get from the form.
$.ajax({
url: "Operations.php",
method: "POST", // defaults to get
data: $(this).serialize(), // get the form data and send it
dataType: "HTML",
success: function() {
$("#loading").hide();
}
});
It seems $_REQUEST doesn't work with Ajax. What a surprise.
My solution is: I created a new hidden in the forms to receive via jQuery the value of the clicked button:
btnValue = "";
$("#form button").click(function() {
btnValue = $(this).attr("value");
});
Then right before the $.ajax, I set the hidden value:
$(this).find("#action").attr("value", btnValue);
In my Operations.php, a new $_POST value is received
$action = filter_input(INPUT_POST, "action");
And in the switch block, I just check $action
switch ($action) {
case "insert": ...
case "update": ...
case "delete": ...
}
Worked perfectly.
Try this one. I have not tested but it will work.
$("#form").submit(function (e) {
e.preventDefault();
$("#loading").show();
$.ajax({
url: "Operations.php",
dataType: "HTML",
success: function () {
$("#loading").hide();
},
error: function (data) {
},
complete: function (data) {
$("#loading").hide();
//A function to be called when the request finishes
// (after success and error callbacks are executed).
}
});
});

Passing result from AJAX call to PHP script

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!

Replace link with form to pass variables to javascript / ajax - single script

I'm sending a single variable to javascript/ajax via a link, but want to send via a form so I can pass user input as well. (It's for a plugin that interfaces with an Echonest Remix python script to create audio edits). The short question is how can I receive this in a WP ajax javascript:
<form id="receive_me" method="POST">
Username: <input type="text" name="user_variable">
<input type="hidden" name="generated_var" value="'.$arguments.'">
<input type="submit" value="Submit">
</form>
The JS:
function glitch_player_display(generated_var) {
jQuery.ajax({
type: 'POST',
url: ajaxglitch_playerajax.ajaxurl,
data: {
action: 'ajaxglitch_player_ajaxhandler',
mix_name: mix_name
},
success: function(data, textStatus, XMLHttpRequest) {
var showglitchplayer = '#showglitchplayer';
jQuery(showglitchplayer).html('');
jQuery(showglitchplayer).append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
This is the PHP current:
function glitch_player_show_make_mix(){
$result = "";
$generated_var = wp_create_nonce("ajaxloadpost_nonce");
$arguments = "'".$nonce."'";
$link = ' <div id="make_button"><a onclick="glitch_player_display('.$arguments.');">'. "Link Title" .'</a></div>';
$result .= '<h3>' . $link . '</h3>';
$result .= '<div id="showglitchplayer">';
$result .= '</div>';
$result .= '<div id="play_button"><a title="The Title" href="'.plugin_URL.$generated_var.'.mp3">First Mix</a></div>';
return $result;
}
add_action( 'wp_ajax_nopriv_ajaxglitch_player_ajaxhandler', 'ajaxglitch_player_ajaxhandler' );
add_action( 'wp_ajax_ajaxglitch_player_ajaxhandler', 'ajaxglitch_player_ajaxhandler' );
function ajaxglitch_player_ajaxhandler(){
$generated_var = isset( $_POST['generated_var'] )? $_POST['generated_var'] : false;
error_log( "The generated_var is $generated_var" ); // write it to the error_log too.)
But I'm not sure how to receive the POST to javascript. Something along these lines?
$('#inputForm').submit(function glitch_player_display(mix_name)
I don't need a second php script do I? I'll be grateful for a point further (or at all) in the right direction.
Thanks and stay well.
ANSWER: Based on input below, here ONE OF THE WAYS to send the variable via form:
<form id="form_id" name="form" method="post">
Field Title: <input type="text" id="user_input" size = 2>
<input type="hidden" id="mix_name" value="'.$arguments.'">
<input id="btn-submit" type="submit" onclick="glitch_player_display()" value="Submit">
</form>
And here's the JS/jQuery
function glitch_player_display() {
user_input = document.getElementById("user_input").value ? document.getElementById("user_input").value : 2;
generated_var = document.getElementById("generated_var").value ? document.getElementById("generated_var").value : "Default_Var";
$(document).on('submit', '#form_id', function(event){
event.preventDefault();
});
jQuery.ajax({
beforeSend: function() {
alert(generated_var + " in ajax user_input: " + user_input);
},
type: 'POST',
url: ajaxglitch_playerajax.ajaxurl,
data: {
action: 'ajaxglitch_player_ajaxhandler',
generated_var: generated_var,
user_input: user_input
},
success: function(data, textStatus, XMLHttpRequest) {play_button
var showglitchplayer = '#showglitchplayer';
jQuery(showglitchplayer).html('');
jQuery(showglitchplayer).append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
Note that we are not sending the variables to the js function glitch_player_display() as we were in the first case. We are picking it up within the JS function via document.getElementById("user_input").value. Also
beforeSend: function() {
alert(generated_var + " in ajax user_input: " + user_input);
},
Is just a way to test and see what the jQuery.ajax function is actually receiving. And since we're not actually calling another script via the submit button, it is necessary to invoke
$(document).on('submit', '#form_id', function(event){
event.preventDefault();
});
So jQuery (or JS?) doesn't think it should be finding another script and generate an error, which in this case replaced user_variable with [object Object]. The object could be viewed by using console_log() and I think it was a huge error object.
First to launch the ajax request you need to prevent default behavior of the form submit.
$('#inputForm').submit(function(e) {
// Prevent submitting the form normal way
e.preventDefault();
// Now call the function that handles the ajax request
glitch_player_display();
})
You need to get the value from the form. You can do it either in your .submit event handler and pass the mix_name to your glitch_player_display(mix_name) function as an argument, or just call glitch_player_display() without arguments and get your value inside this function through jquery. Than you're making ajax request to ajaxglitch_playerajax.ajaxurl .. process it on your server-side and return response from there.
Your button should call your javascript function with an onclick="" parameter and the javascript function can access the fields using documet.getElementById("fieldname").value to do what you want with it. Just give each field an ID="fieldname", replacing "fieldname" with a unique ID for each one, which you then access with document.getElementById().

confirm choice in php page using javascript

I'm trying to confirm deleting something, but I can't seem to get it to work.
When the button for 'deleteReply' I'm getting an alert message, but as far as I can tell nothing else is happening. I'm trying to simply echo the posted variable but it doesn't seem to work.
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
On my delete processing page I just have
$echo $_POST['replyID'];
Why do you have
if(isset($_POST['deleteReply'])){
?>
Before the javascript function? Did you expect to trigger the javascript code based on the $_POST['deleteReply'] var?
You have to keep in mind that php is processed server-side and outputs an HTML page. Your javascript code will only run in the client after all the php has run.
A much more elegant solution would be asking for a confirmation BEFORE sending the AJAX request.
And also, your ajax call doesn't seem to do what you're expecting. You're manually setting 2 parameters to send to your PHP which will have no use for it if you do the confirmation server-side.
A parameter should be something like the Reply ID of the reply you want to delete, and send the request to a different php file for handling.
I'd suggest you rewrite your code as Marian Zburlea is doing for you.
EDIT
Ok, if you want a simple confirm window, try this:
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('delete.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
EDIT
If you have multiple delete buttons, the best way to do this would be storing the replyID as the parameter to pass to your function. Echo your delete buttons in your php like this:
echo '<input type="button" value="Delete" onclick="deleteSomething(\'' . $replyID . '\')" />';
This way, the $replyID will be stored in the page's HTML, which will be passed to the deleteSomething(replyID) function which you now have to define (preferably in the document's head after the JQuery lib):
<script type="text/javascript">
function deleteSomething(replyID)
{
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
}
</script>
Note that I removed the ID from the buttons to don't generate dupplicate IDs and they are no longer needed, as I've added a function call in the onclick event instead of binding an anonymous function to their IDs as you were doing previously.
<input type="button" id="deleteSomething" value="Delete" />
<div id="yesno" style="display:none;">
<input type="button" id="buttonYes" value="Yes" />
<input type="button" id="buttonNo" value="No" />
</div>
<script type="text/javascript">
// Here you attach a click event to the button Yes with id buttonYes
$('#deleteSomething').click(function() {
$('#yesno').css('display', 'block');
});
$('#buttonNo').click(function() {
$('#yesno').css('display', 'none');
});
$('#buttonYes').click(function() {
$.ajax({
beforeSend: function(e) {
// Code to process before calling AJAX
},
url: "pathToPHPFile.php",
dataType: "json",
type: "POST",
data: {
parameter: 'Yes',
},
success: function (m) {
console.log(m);
alert(m.text);
},
error: function (e) {
console.log("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
// This is a separate php file named pathToPHPFile.php
if(isset($_POST['parameter']) && $_POST['parameter'] == 'Yes'){
/* here you put the code that deletes the message */
$response['text'] = 'messageDeleted'
echo json_encode($response);
}

Categories

Resources