Button click, run a php function with ajax - php

I want to run my php function when I click on this button, This works fine on Chrome and Firefox, But not on Safari, I don't know why :( Please help me...
My PHP Function is : complete_automate_xml();
My Button is : <button id="btn" onclick="alertWithoutNotice();" class="deletebtn button button-next">Verstuur E-mails</button>
My Code is :
<script>
jQuery(document).ready(function($) {
$('#btn').click(function(){
$.ajax({
type: "POST",
url: '../wp-admin/admin.php?page=spd_xml_importer',
data: {action: 'call_this'},
success: function (html) {
alert(html);
}
});
});
});
</script>
<div class="email-bt">
<script>function alertWithoutNotice(message) {
setTimeout(function () {
alert('E-mails zijn verzonden');
}, 300);
}</script>
<button id="btn" onclick="alertWithoutNotice();" class="deletebtn button button-next">Verstuur E-mails</button>
</div>
<?php
if ($_POST['action'] == 'call_this') {
complete_automate_xml();
}

i was thinking more like this - but I'm not 100% sure this is the issue with Safari I just wondered whether there was confusion in the browser as to which function to invoke.
<script>
jQuery(document).ready(function($) {
$('#btn').click(function(){
setTimeout(function() {
alert('E-mails zijn verzonden');
}, 300);
$.ajax({
type: "POST",
url: '../wp-admin/admin.php?page=spd_xml_importer',
data: { action: 'call_this' },
success: function (html) {
alert(html);
}
});
});
});
</script>
<div class="email-bt">
<button id="btn" class="deletebtn button button-next">Verstuur E-mails</button>
</div>

Related

Ajax not picking up php post from dymanically created form

I have created some ajax that uploads an image and loads it into the page.
It creates an images with an X button on the top corner, I am trying to get it so when this button is clicked I then run another peice of php code with will delete the correct image and reload the images.
I cant get my ajax code to pick up the php code and I am not sure why.
Any pointed would be very helpful.
I have found out that dymanically created elemets will not be picked up so had to change my ajax code to
$("body").on("click", "#deleteform button", function(e){
so I am hitting this point but but it sill is not picking up my php code and I dont know why.
Any pointers would be very helpful
AJAX JS:
$(document).ready(function(){
$("#uploadForm").on('submit',function(e) {
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_add_image.inc.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
});
});
$(document).ready(function(){
$('button.deleteimage').on('click', function(){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer"+image_id).html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="include_advert/advert_js/advert_gun_load_save_images.js"></script>
<div class="bgColor">
<form id="uploadForm" action="include_advert/advert_new_gun_add_image.inc.php" method="post" class="login-form" enctype="multipart/form-data">
<div id="targetLayer" class=col> </div>
<div id="uploadFormLayer">
<input name="file" type="file" class="inputFile" /><br/>
<div class="text-center">
<input type="submit" name="submit" value="UPLOAD" class="btn btn-common log-btn">
</div>
</form>
advert_new_gun_add_image.inc.php:
<?php
$imagecount = 0;
echo ('<div class=row sm>');
foreach ($getadvertimages as $getadvertimages_row) {
echo ( '<div class="image-area" >
<form id="deleteform'.$getadvertimages_row['image_id'].'" method = "POST" action ="include_advert/advert_new_gun_delete_image.php" >
<img src="'. $getadvertimages_row['image_src'] . '" alt="Preview">
<button onclick = "" name="deleteimage" id="deleteimage" value="'. $getadvertimages_row['image_id'] . '" class="remove-image" style="display: inline;" >X</button>
</form>
</div>');
}
echo ('</div>');
advert_new_gun_delete_image.php:
<?php
if (isset($_POST['deleteimage']) ){
echo('hello');
}?>
I am expecting when I click the button on the image it will run the advert_new_gun_delete_image.php file without reloading the complete page
The Above Answer was almost there but I had to change the $('button.delete-button').on('click', function(){ to $("body").on("click", "#deleteimage", function(e){
And I also removed:contentType: false, cache: false,processData:false,
Thanks Ghulam for the push in the right direction
$(document).ready(function(){
$("body").on("click", "#deleteimage", function(e){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id },
success: function(data)
{
$('#imageareadiv').hide();
$("#targetLayer").html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
$(document).ready(function(){
$('button.delete-button').on('click', function(){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer"+image_id).html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
include 'advert_new_gun_save_image_script.inc.php';
include 'advert_new_dropdown_populate/advert_new_gun_image_populate.php';
$imagecount = 0;
echo ('<div class=row sm>');
foreach ($getadvertimages as $getadvertimages_row) {
echo ( '<div class="image-area" >
<form id="deleteform'.$getadvertimages_row['image_id'].'" method = "POST" action ="include_advert/advert_new_gun_delete_image.php" >
<img src="'. $getadvertimages_row['image_src'] . '" alt="Preview">
<button type="button" name="deleteimage" value="" class="remove-image delete-button" style="display: inline;" >X</button>
</form>
</div>');
}
echo ('</div>');
Similarly you can make "targetLayer" dynamic with image_id value just like I did with form's attribute id deleteform.
$(document).delegate('#deleteform button', 'click', function (e) {
instead of
$("body").on("click", "#deleteform button", function(e){

Javascript Ajax Post not sending special characters

So I've been running into some problems when trying to send special characters though an ajax call.
<textarea id="area" cols="70" rows="30"></textarea>
<button id="submit">Submit</button>
<script>
$('#submit').click(function (e) {
e.preventDefault();
var info = $('#area').val();
$.ajax({
type: "POST",
url: 'pages/assignments/response.php',
data: {area: info},
success: function (response) {
console.log(response);
}
});
});
</script>
response.php:
if (!empty($_POST['area'])) {
$data = $_POST['area'];
echo $data;
};

Ajax not loading without refreshing the page

This following ajax code not working without refresh can anyone tell me what I am doing wrong, thanks
$(document).ready(function() {
fetch_data();
function fetch_data(){
var action = "fetch";
$.ajax({
url:"action.php",
method:"POST",
data:{action:action},
success:function(data) {
$('#image_data').html(data);
}
})
Place function outside $(document).ready(function), because function must be loaded before all page load
You can run function while click on "Run Function" button
<button id="run_function">Run function</button>
$(document).ready(function(){
fetch_data();
/* Script for run function on button click */
$('#run_function').click(function() { fetch_data(); return false; });
});
function fetch_data()
{
var action = "fetch";
$.ajax({
url:"action.php",
method:"POST",
data:{action:action},
success:function(data)
{
$('#image_data').html(data);
}
});
}
Your code will only run once per page load unless you call it via some other method. Here is a script that will run it each time you press the button. Also, make sure you have jquery installed.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" onClick="fetch_data()" value="Run Function">
<script>
function fetch_data(){
var action = "fetch";
$.ajax({
url:"action.php",
method:"POST",
data:{action:action},
success:function(data)
{
$('#image_data').html(data);
}
});
$(document).ready(function(){
fetch_data();
});
</script>

Ajax POST and php query

Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});

Hide Loading Data, Once Page has loaded

Been asking a lot of jquery questions lately, I'm trying my best to learn a lot about it.
Anyway, I am sending an Ajax HTTP request to a PHP page in order to make a login form without requiring a page refresh. Now since it may take some time to connect the database and get the login information etc..
Now I do have loading as a .html but how can I hide the loading data once data has loaded?
Tried to use a few functions but didn't seem to work.
Thanks so far, this site has helped me a lot through the learning process.
Here's the JavaScript:
$(document).ready(function() {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
user_login: $('#user_login').val(),
pass_login: $('#pass_login').val()
}
}
function loading(e) {
$('#content').html('Loading Data');
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function(e) {
if (e.keyCode == 13) {
var username = $('#user_login').val();
loading(e);
check(e);
}
});
$('#submit').click(function(e) {
if (e.keyCode != 13) {
loading(e);
check(e);
}
});
});
Here is the HTML:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="js/login.js"></script>
<div id="content"> Loading...</div>
<div id="field">
<input type='text' name='user_login' id='user_login' placeholder='eg: Mark#gmail.com'> <br>
<input type='password' name='pass_login' id='pass_login'> <br>
<input type="submit" name="submit" id="submit" value="Login">
</div>
function check(){
$.ajax({
url: 'ajax/check.php',
type: 'post',
error: function(){
alert('An error has occured.');
},
beforeSend: function(){
$('#content').show('slow').html('Loading');
//loading(e);
},
data: {user_login: $('#user_login').val(),pass_login: $('#pass_login').val()}, // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
}
$('#submit').click(function(){
check();
});
$('#field, #field input').keyup(function(e){
var username = $('#user_login').val();
if (e.keyCode == 13) {
check();
}
});
Markup
<div id="field">
<input type='text' name='user_login' id='user_login' placeholder='eg:Mark#gmail.com'> <br>
<input type='password' name='pass_login' id='pass_login'> <br>
<input type="button" name="submit" id="submit" value="Login">
</div>
Good luck!!!
First of all, i'm not sure if your code will return a success. This code will help you find out if the response is not successfully. If you get a browser alert. It means you have a server side error. Its either the url path is wrong or your server response statuscode is 500 (Internal error).
$.ajax({
url: 'ajax/check.php',
type: 'post',
error: function(){
alert('An error has occured.');
},
beforeSend: function(){
$('#content').show('slow').html('Loading');
//loading(e);
},
data: getData(), // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
Refactoring your code entirely will look like this. Choose first or second:
$.ajax({
url: 'ajax/check.php',
type: 'post',
error: function(){
alert('An error has occured.');
},
beforeSend: function(){
$('#content').show('slow').html('Loading');
//loading(e);
},
data: {user_login: $('#user_login').val(),pass_login: $('#pass_login').val()}, // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});

Categories