prevent page reload when calling php with ajax - javascript

I have a php function that I call using ajax and then handle the response with ajax. However, I want to prevent the page from reloading.
I have index.php containing a call to function1(), and it includes ajaxcall.js and jquery
Then my functions.php:
function function1(){
echo '
<form id="myform" action="" method="post" enctype="multipart/form-data">
<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this)" placeholder="type an anime name" title="Type in a name">
</form>
<div id="table_recentanime" class="hscroll">
<table dir="ltr" id="myTable">';
// echo some table rows
}
if (isset($_POST['callyoukai_search'])) {
//echo "!!!" . $_POST['callyoukai_search'] . "the post value in php!!!!!!";
//echo
youkai_search($_POST['callyoukai_search']);
}
function youkai_search ($search_word){
// use $search_word to do a database query
return $result;
}
my ajaxcall.js
function searchfiltersajax(search_word){
if(event.key === 'Enter') {
console.log("yes");
console.log(search_word.value);
document.getElementById("myform").addEventListener("Keypress", function(event){
event.preventDefault()
});
jQuery.ajax({
url: '../wp-content/plugins/youkai_plugin/youkai_plugin.php',
type: 'post',
data: { "callyoukai_search": "1"},
success: function(response) { var container = document.getElementById("myTable");
container.innerHTML = response;
console.log('php gave javascript '); console.log(response); console.log('php gave javascript '); }
});
console.log ("done");
}
}
My ajax call works fine. It calls the php function with the desired search_word, and the search results replaces the div content just like I want. However, right after this, the page reloads.
How do I prevent the reload? I tried preventDefault(), but the way I used it didn't work.
Thanks in advance

Inlining event handlers is a bad practice. But if you need it at least add the event keyword. Change from:
to:
<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this, event)"
Moreover, don't add the same event handler (i.e.: Keypress) inside another: in this way you are adding more and more times the same event handler. Instead, use the event parameter.
I'd suggest to use the addEventListener() or .on():
$('#myInput').on('keydown', function(e) {
searchfiltersajax(this, e);
});
The snippet:
function searchfiltersajax(search_word, e) {
if (event.key === 'Enter') {
e.preventDefault();
console.log("yes");
console.log(search_word.value);
jQuery.ajax({
url: '../wp-content/plugins/youkai_plugin/youkai_plugin.php',
type: 'post',
data: {"callyoukai_search": "1"},
success: function (response) {
var container = document.getElementById("myTable");
container.innerHTML = response;
console.log('php gave javascript ');
console.log(response);
console.log('php gave javascript ');
}
});
console.log("done");
}
}
<form id="myform" action="google.com" method="post" enctype="multipart/form-data">
<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this, event)"
placeholder="type an anime name" title="Type in a name">
</form>
<div id="table_recentanime" class="hscroll">
<table dir="ltr" id="myTable">
<tbody>
</tbody>
</table>
</div>

The function searchfiltersajax takes one parameter named search_word. The first if-statement then checks an event-variable. This variable is declared nowhere in your code, so the code inside the if-statement will never get executed.
To verify this I would recommend to add debugger; as first statement inside the searchfiltersajax function. Then open the debugging console in the browser and reload the page. Do not forget to remove the debugger; statement once you are finished. If you know how to set breakpoints in the javascript debugger, you should not use debugger; statements at all.
As far as I understand you try to prevent a form to be submitted to the server but send an ajax call instead. There are several answers on StackOverflow for this topic, e.g. Prevent users from submitting a form by hitting Enter . You could use a code like this to achieve your goals (taken from the link):
$(document).on("keypress", "form", function(event) {
return event.keyCode != 13;
});
Last but not least, I would suggest not to include raw HTML sent by any server (even your own) to your page:
container.innerHTML = response;
Instead try to send a JSON object containing the information you wish to present and transform this object into HTML elements via JavaScript. This way you have a cleaner interface for data exchange and have to change on piece of code to change styling or other presentation aspects.

Related

Add a dynamic form field after pressing a button

I have a form with a simple button $builder->add('language_switcher', ButtonType::class); which should simply, if pressed, add another field. To do that, I used Symfony's cookbook http://symfony.com/doc/current/form/dynamic_form_modification.html
$builder
->get('language_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function () use ($builder, $options) {
$preparedOptions = $this->prepareOptions($options['data']['productCustomizations']);
$builder->add('lang_switcher'), ChoiceType::class, $preparedOptions);
}
);
When now submitting it via AJAX
<script>
var $button = $('#xyz');
$button.click(function() {
var $form = $(this).closest('form');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
success: function(html) {
console.log(html);
$('#xyz').replaceWith($(html).find('#lang_switcher'));
}
});
});
</script>
I'm getting the error Buttons do not support event listeners. So I tried it out with a hidden field. I added the hidden field to the Form, set the EventListener to it, and added this data to my AJAX request
data[$('#id_of_hidden_field').attr('name')] = 1;
However this did nothing. The example in the cockbook is after submitting a choice field so I don't know how to adapt it to my needs. I couldn't use a SubmitType, because then it would submit the form, right? I just want to have it with a simple button.
The problem is, that, when I do a console.log(html) I don't see the new html element, so it seems like I'm not getting to the EventListener which is weird, because if I dump contents inside the listener I'm getting some data. It just seems like I'm not getting it inside the response
Ok, got it. The problem was that I used the builder inside the POST_SUBMIT event but I had to use a FormInterface. Since I couldn't add it AFTER submit I had to buy the same callback function as in Symfony's cookbook
$formModifier = function (FormInterface $form, $preparedOptions) {
$form->add($this->childIdentifier, ChoiceType::class, $preparedOptions);
};
And then the listener is built like this
$builder
->get('lang_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier, $options) {
$preparedOptions = $this->prepareOptions($options);
$formModifier($event->getForm()->getParent(), $preparedOptions);
}
);
<script type="text/javascript">
function inputBtn(){
var input=document.createElement('input');
input.type="file";
input.name="img[]";
input.multiple="multiple";
//without this next line, you'll get nuthin' on the display
document.getElementById('target_div').appendChild(input);
}
</script>
<button id="ifile" onclick="inputBtn();">create</button>
<form action="test.php" method="post" enctype="multipart/form-data">
<div id="target_div"></div>
<input type="submit">
</form>

jquery form plugin and show content of div

I use jquery form plugin and i try show the result when i submit my form in one div but no get result
<script>
jQuery(document).ready(function()
{
jQuery('#base64').ajaxForm(
{
dataType:'json',
success:edit64,
target: '#htmloutput'
});
});
function edit64(datasend64)
{
if (datasend64.edit_result64=="ok")
{
jQuery('#htmloutput').fadeIn('slow');
}
}
</script>
I donñt know if i put all well or no , i try mant times and no get the result of form inside div , only show nothing
<div id="htmloutput" style="display:none;"></div>
<form action="admin_db_edit.php" name="base64" id="base64" method="post">
<input type="text" name="value_base64" value="" class="db_edit_fields" />
<input type="hidden" name="send64" value="ok" />
<input type="submit" name="send" value="send" class="db_edit_submit" />
</form>
Thank´s for the help , regards
First... you have no url specified for the form. second, try adding a function to handle the error case. This can help you understand if the issue is happening on the client or the server.
jQuery(document).ready(function() {
jQuery('#base64').ajaxForm({
url: ????
dataType: 'json',
success: edit64,
error: onError,
target: '#htmloutput'
});
});
function edit64(datasend64) {
if (datasend64.edit_result64 == "ok") {
jQuery('#htmloutput').fadeIn('slow');
}
}
function onError(response, error, reqObj){
alert(response);
}
if you are trying to send the data somewhere, you are probably missing the url attribute(as shown in the offical docs: http://malsup.com/jquery/form/#options-object)
however, trying to log the datasend64 value will help to determind if the function have been called or not. so... in your code:
function edit64(datasend64)
{
console.log(datasend64);
if (datasend64.edit_result64=="ok")
{
jQuery('#htmloutput').fadeIn('slow');
}
}
if a result is shown in the developer console - you can watch the object and seek for your values (if there are any at all). if you don't see anything - the success event havn't occoured (again, i think you are missing the url parameter)

AJAX returns data twice on submit

Instead of redirecting the user to a new page, I want to add an overlay over the form. Somehow, the following code returns the overlay twice.
AJAX
$(document).ready(function ()
{
$('#form_informations').submit(function ()
{
$.get('php/formulaires.php', $(this).serialize(), function (data)
{
$('#form_informations').append('<div id="conf_informations" class="confirm"><p><img src="img/check.png" /><br /><?=FORMULAIRE_SAUVEGARDE;?></p></div>');
});
return false;
});
});
The id #form_informations is only used once.
For now, the second overlay is not created in php/formulaires.php because the file is empty as I have not started parsing the data.
Why is this happening? I don't see where this second overlay is coming from.
This is the HTML form:
HTML Form
<form id="form_informations" method="post" enctype="multipart/form-data">
<!-- form here -->
<input type="submit" name="submit_general" value="Save" />
</form>
May be you can add some code like this in the submit function
if(!$("#conf_informations").size()) {
$.get... //your get request here
}
Final solution
if(!$("#conf_informations").length()) {
$.get... //your get request here
}

How to call ajax and output its result inside div and textarea?

I am trying to make load more button. My goal is to call ajax and put the response inside div and textarea.how to place the response inside div and textarea? Currently the response only shows in messagebox but i want to append the result into div.
*Note:*Response is html hyperlinks produced by process.php and i want those hyperlinks placed inside the div
<html>
<head>
<script>
//initialize page number to 1 default
var pagenumber=1;
//pass pagenumber to function to fetch correct page records
function getResult(pagenumber){
alert('me here'+pagenumber);
$.ajax(
{
type: 'GET',
url: './process.php?ID=1234&type=1&moviePath=1234/1212/Love&title=Love&page='+pagenumber,
data: $("#myform").serialize(),
data: {
},
success: function (good)
{
//handle success
alert(good)
},
failure: function (bad)
{
//handle any errors
alert(bad)
}
});
//after every call increment page number value
pagenumber++;
}// end of getResult Function
function addMoreItems()
{
pagenumber++;
getResult(pagenumber);
}
</script>
</head>
<body>
<div id="myDiv"></div>
<div class="MoreButtonSection">
<div class="RedButton">
<span class="LeftEnd"></span>
<span class="Centre">see more</span>
<span class="RightEnd"></span>
</div>
</div>
<br>
<br>
<form id="myform" name="myform" action="./2.php?Id=&title=" method="post">
<td>
<textarea rows="7" cols="15" name="outputtext" style="width: 99%;"></textarea>
</td>
</form>
</html>
You say your result is only showing in the message box, instead of alerting it, simply append. Assuming the below div is what you want to append to:
<div id="myDiv"></div>
You can modify your success function:
success: function (good)
{
//handle success
$("#myDiv").append(good);
},
Also, get rid of that second data: {}, -- it's doing nothing.
There are a number of issues.
There is no indication that you've included jQuery.
You've declared data: twice.
As Dmitry pointed out, you should probably be posting this.
And finally, where are you actually calling getResult()? It doesn't look like it's being called.
In addition, it is worth noting that from jQuery 1.8 and higher, .success() and .failure() are now deprecated and have been replaced with .done() and .fail().
http://api.jquery.com/jQuery.ajax/
I tend to use jQuery in these situations to make life a little easier, and work with the $('#yourDiv').append() function. For instance you can create variables i.e. var mug; and once it is filled with your data append mug to the document through $('#yourDiv').append("<p>"+mug+"</p>);
An example - Ajax Twitter API call that returns tweets to specific lists within a div (page source)
Hope that helps!
I think I get what you are trying to do but that code is a mess. As #David L has stated, you need jQuery. But then you do not need all the code you have written. It can be done in a few simple lines. Please replace the actual element selectors with your correct ones.
function addMoreItems() {
pagenumber++;
// get form values
var params = $('#myform').serializeArray();
// add predefined values
params.push({name: 'ID', value: '1234'});
params.push({name: 'type', value: '1'});
params.push({name: 'moviePath', value: '1234/1212/Love'});
params.push({name: 'title', value: 'Love'});
params.push({name: 'page', value: pagenumber});
// do request and insert response from server in div with id='divresults'
$.get('process.php', params, function(data) {
$('#divResults').append(data);
});
}

Delete Record Confirmation Message

I wonder whether someone may be able to help me please.
Firstly, my apologies because I'm really very new to this, so please forgive me what some may seem a very basic question/error.
The extract of code below, successfully creates a table of records pertinent to the current user.
Working Solution - Baylor Rae' worked tirelessly with me over the last 3-4 days to find a solution. All Baylor Rae' was unable to provide a fully successful script, they certainly helped considerably in moving this on . However the full working script below is Courtesy of jazzman1 # PHP Freaks
Main Script
<script type="text/javascript">
$(document).ready(function(){
$('form.delete').submit(function(e){
console.log('submit'); return false;
})
})
</script>
<script type="text/javascript">
$(document).ready(function(){
$('form.delete').submit(function(e){
e.preventDefault();
var elem = $(this).closest('.delete');
var lid = $(this).serialize();
$.confirm({
'title' : 'Delete Confirmation',
'message' : 'You are about to delete this Location. <br />It cannot be restored at a later time! Do you wish to continue?',
'buttons' : {
'Yes' : {
'class' : 'blue',
'action': function(){
//elem.slideUp();
$.ajax({
url: 'deletelocation.php',
type: 'POST',
data: lid,
success: function(response) {
console.log('success', response);
},
error: function() {
console.log('error')
}
});
}
},
'No' : {
'class' : 'gray',
'action': function(){} // Nothing to do in this case. You can as well omit the action property.
}
}
});
});
})
</script>
jqueryconfim.js
(function($){
$.confirm = function(params){
if($('#confirmOverlay').length){
// A confirm is already shown on the page:
return false;
}
var buttonHTML = '';
$.each(params.buttons,function(name,obj){
// Generating the markup for the buttons:
buttonHTML += ''+name+'<span></span>';
if(!obj.action){
obj.action = function(){};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<h1>',params.title,'</h1>',
'<p>',params.message,'</p>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons,function(name,obj){
buttons.eq(i++).click(function(){
// Calling the action attribute when a
// click occurs, and hiding the confirm.
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function(){
$('#confirmOverlay').fadeOut(function(){
$(this).remove();
});
}
})(jQuery);
Form In Main Script
<form name="delete" id="delete" class="delete">
<input type="hidden" name="lid" id="lid" value="<?php echo $theID ?>" />
<input type="submit" value="Delete Record"/>
</form>
deletelocation.php
<?php
$lid = intval($_POST['lid']);
$query = mysql_query("DELETE FROM table WHERE locationid='".$lid."'");
?>
You'll see that the end of the table are four buttons, which, through the locationsaction.php script navigate the user to four different screens all linked back to the main table record via the lid value. This script is shown below.
I'm now trying to implement a confirmation message for the Delete function. The source code for this can be found here.
This is where I've become a little unsure about what to do next. I've tried to link the button on click event with the name of the Delete function, but rather than the confirmation message, the user is taken to a blank screen and the record is deleted.
I've run the JavaScript Console and there are no errors created, so I'm a little unsure about how to continue.
I just wondered whether someone could possibly take a look at this please and let me know where I'm going wrong.
Many thanks and kind regards
Prevent the Redirection
It looks like you're getting the redirection because the form is still submitting. You need to prevent the form from submitting by adding the following line at the beginning of your click event.
$('#btn-delete').click(function(e) {
e.preventDefault();
var elem = $(this).closest('.item');
Calling e.preventDefault() will prevent the browser's default action from occuring, in this case submitting the form.
Changing the way buttons are handled
As far as I can tell locationsaction.php redirects to a page based on the value of the button.
A better way to do this would be to create a link to each page and pass the lid as a parameter. This is the standard way of linking pages while providing some context for the next page.
Note: You will need to change each page to use $_GET['lid'] instead of $_SESSION['lid'].
Note 2: It is perfectly valid to "close" and "open" PHP tags in the middle of a page. In the code I provided below I closed PHP so I could write HTML, and reopened PHP when I was done.
<?php // this line is for syntax highlighting
/* display row for each user */
$theID = $row['locationid'];
?>
<tr>
<td style="text-align: center"><?php echo $row['locationname'] ?></td>
<td>Images</td>
<td>Add Finds</td>
<td>View Finds</td>
<td>
<form method="post" action="deletelocation.php" class="delete-record">
<input type="hidden" name="lid" value="<?php echo $theID ?>" />
<input type="submit" value="Delete Record" />
</form>
</td>
</tr>
<?php
The only time I didn't use a link was when I linked to the deletelocation.php file. This is because you should never use a GET request when modifying a database.
Using a POST request is an easy way to prevent Cross-site Request Forgery.
Rename your table column names
I noticed that your column names for locationid and locationname didn't have any type of separation. I would recommend renaming these to location_id and location_name.
This applies to your file names as well. You can include an underscore or dash to separate the words in your filename. I usually use an underscore because I think it reads better, but it's your choice.
POST directly to the delete page
Because you're using AJAX, you can specify the deletelocation.php url directly. With the changes I've suggested above, there isn't a reason to keep locationsaction.php.
$.ajax({
url: 'deletelocation.php',
type: 'post',
data: $(this).parent().serialize(),
success: function () {
img.parent().fadeOut('slow');
}
});
I also changed how the data was passed. .serialize() will automatically grab the location id from input[name=lid] and create a query string like lid=1.
Edit #1
If possible, I'd like to keep the locationsaction script. A lot of my pages further down the line rely on a SESSION id, and using a Get isn't an option without re-writing a lot of code.
The way you're using locationsaction.php and sessions isn't the way I'd do it. But it's your application structure and you can build it however you like.
Could I change the button type to button rather than submit, keeping the id the same so the JS code will pick this up?
You can change the type to button, but when javascript is disabled it won't submit the form. In general, you write your page to work without JS, and then write the JS to modify the browser's default behavior.
Could you also confirm for me whether your AJAX just replaces the top section of my code?
No, I only changed the way you set the lid. You still need to include all the JS wrapped around it, I just didn't want to paste the whole block of code.
Observation 1:
function delete(){
$(document).ready(function(){
Is that really the order of the lines in your code? The jQuery ready hook lies INSIDE of your function definition? Or have you, by mistake, posted them here in the wrong order here.
If it's the former case, then please, fix this first before anything else. Otherwise, read on:
Why $('.item .delete')? I don't see any markup with class .item? Where is it? Are you sure that this selector matches some elements in the first place? Also, you should use #delete for referencing elements through their id attributes, not .delete, as that looks for elements with the class delete.
Your id:delete button and the other buttons are submit type buttons, which means that their click handlers simply will not block the submission flow. You can change all the button types to button, instead of having them as submit. Code example below.
Why the declarative onClick on the delete button? Get rid of it.
(Also, you really don't need a form in this case, unless you want to deserialize the form, which doesn't seem like a requirement or intent given your markup).
<td><input type='button' name='type' id='details' value='Details'/></td>
<td><input type='button' name='type' id='images' value='Images'/></td>
<td><input type='button' name='type' id='addFinds' value='Add Finds'/></td>
<td><input type='button' name='type' id='viewFinds' value='View Finds'/></td>
<td><input type='button' name='type' id='delete' value='Delete' /></td>
And your JS:
//please, be careful with the selector.
//it could be that it is not matched at all,
//hence jQuery will not bind to anything
//and nothing will ever fire!
//note the #delete for Id! .delete is for a class!!!!!!
$('.item #delete').click(function () {
var elem = $(this).closest('.item');
$.confirm({
'title': 'Delete Confirmation',
'message': 'Delete?',
'buttons': {
'Yes': {
'class': 'blue',
'action': function () {
//elem.slideUp();
$.ajax({
url: 'locationsaction.php',
type: 'post',
data: {
lid: "VALUE",
type: 'Delete' //you need to add the type here!
},
success: function () {
img.parent().fadeOut('slow');
}
});
}
},
'No': {
'class': 'gray',
'action': function () {} // Nothing to do in this case. You can as well omit the action property.
}
}
});
Also, you can redudantly add a false return to your form's onsubmit event.
Actually I don't find any button of id btn-delete on your form.If your using delete button present in form then change this
<input type="submit" value="Delete Record" />
to
<input type="button" id="btn-delete" value="Delete Record" />
Or your using any other input then make sure that it type is not submit for example
<input type="submit" value="Your button" />
should be
<input type="button" value="Your button" />
u can use jquery ui dialog for confirmation :
<script type="text/javascript">
$('#btn-delete').click(function (e) {
e.preventDefault();
var elem = $(this).closest('.item'), formSerialize = $(this).parent().serialize(), objParent = $(this).parent();
$('<div></div>').appendTo('body')
.html('<div><h6>Delete?</h6></div>')
.dialog({
modal: true, title: 'Delete Confirmation', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
$.ajax({
url: 'deletelocation.php',
type: 'post',
data: formSerialize//,
//success: function (data) {
// objParent.slideUp('slow').remove();
//}
});
//Or
objParent.slideUp('slow').remove();
$(this).dialog("close");
},
No: function () {
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
});
</script>
The problem isn't anything to do with JavaScript.
The fundamental problem seems to be that your form's action is to delete the record (regardless of what you've coded in JavaScript). Change the form's action to "." and onsubmit="return false" (which stops the form from doing anything on its own). Now attaching your $.confirm to the appropriate button should work.
Stepping back from this -- you don't need a form at all (or a submit button). Then you wouldn't have to fight the default behavior of a form.
Try to use e.stopPropagation();
$('#btn-delete').click(function(e) {
e.preventDefault();
e.stopPropagation();

Categories

Resources