I am stil having issues with my code the file is not being processed when permalinks are set to anything other than default.
<div id="thanks" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Redeem Points</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" class="contact" name="commentform" >
<div class="form-group">
<h3>You may only redeem the maxium points of : <?php echo $maxpoints;?></h3>
<input type="hidden" name="playerid" value="<?php echo $playerId;;?>" />
<input type="number" valuemax="<?php echo $maxpoints;?>" name="points" class="form-control" placeholder="How many points do you wish to redeem." />
<label class="control-label col-md-4" for="Comments">Comments?</label>
<input type="text" name="comments" />
</div>
<div class="form-group">
<div class="col-md-6">
<button class="btn btn-success" id="submit">submit</button>
Close
</div>
</div>
</form>
</div><!-- End of Modal body -->
</div><!-- End of Modal content -->
</div><!-- End of Modal dialog -->
</div><!-- End of Modal -->
I thought the inital issue was the but when i turn permalinks off it appears to work ok I really dont no what the issue is here thanks. The html above is in the file /wp-content/themes/gogreensoccer5/kids-dashbaord.php as well as the jquery below i am at a loss.
type: "POST",
url: "/bin/sendredeempoints.php",
<script>
$('#thanks').modal('show').on('shown.bs.modal', function () {
//Ajax Method Call starts here
var points = $("#points").val();
$("#send_btn").click(function () {
var dataString = 'points=' + points;
alert(dataString);//Remove this
return false;//Remove this
$.ajax({
type: "POST",
url: "/bin/sendredeempoints.php",
data: $('form.contact').serialize(),
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
//Ajax Method Ends
}); //Click Function ends
}); //Modal event Ends
</script>
Stop with the downvoting whoever it is.
Edit
Got A bit further
added this to my functions but its still saying file not found :-(
function load_these_scripts() {
wp_register_script( 'your_script', get_bloginfo('template_directory').'js/redeempoints.js', false, false, true );
wp_localize_script( 'my_ajax_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action("wp_ajax_php_function_name", "redeempoints");
add_action("wp_ajax_nopriv_php_function_name", "redeempoints");
function redeempoints() {
// Some stuff here
global $wpdb;
// $result = $wpdb->get_results( /* SQL code goes here */ );
// Do something with $result
}
You may only redeem the maxium points of :
" />
" name="points" class="form-control" placeholder="How many points do you wish to redeem." />
Comments?
</div>
<div class="form-group">
<div class="col-md-6">
<button class="btn btn-success" id="submit">submit</button>
Close
</div>
</div>
</form>
my js file
var formdata = $('form.contact').serialize();
var allData = {
action: 'redeempoints',
data: formdata
}
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : allData,
success: function(response) {
if(response.type == "success") {
// Do something
}
else {
// Do something else
}
}
});
You need to change the way you use AJAX alongside WordPress :)
First up, in your functions.php (or plugin file), you'll have to localize admin-ajax.php and register a JS file where you'll make the AJAX calls - looks like this:
add_action( 'wp_enqueue_scripts', 'load_these_scripts' );
function load_these_scripts() {
wp_register_script( 'your_script', 'URI_OF_JS_THAT_MAKES_THE_AJAX_CALLS/scripts.js', false, false, true );
wp_localize_script( 'my_ajax_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
Then in your scripts.js you need to make the AJAX calls like this:
Use this instead of the "data :"
$("#send_btn").click(function () {
var formdata = $('form.contact').serialize();
var allData = {
action: 'php_function_name',
data: formdata
}
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : allData,
success: function(response) {
if(response.type == "success") {
// Do something
}
else {
// Do something else
}
}
});
});
The action: "php_function_name" actually tells WP which function to call but you also need register that well. Do it like this, back in your functions.php (or plugin file):
add_action("wp_ajax_php_function_name", "php_function_name");
add_action("wp_ajax_nopriv_php_function_name", "php_function_name");
function php_function_name() {
// Some stuff here
global $wpdb;
$result = $wpdb->get_results( /* SQL code goes here */ );
// Do something with $result
}
Make sure you register the function with both "wp_ajax" & "wp_ajax_norpiv" otherwise it will only work for logged in users.
Cheers
First. This is an ajax post. Using jquery post its a bit different http://api.jquery.com/jquery.post/
Your question is about posting in jquery, not ajax. So lets modify your code a little:
<script>
$('#thanks').modal('show').on('shown.bs.modal', function () {
var points = $("#points").val();
$("#send_btn").click(function () {
var dataString = 'points=' + points;
alert(dataString);//Remove this
return false;//Remove this
var url = "/bin/sendredeempoints.php";
var data = $('form.contact').serialize(),
$.post( url, { data: data })
.done(function() {
$("#thanks").html(msg)
$("#form-content").modal('hide');
}).fail({
alert("failure");
});
});//Click Function ends
}); //Modal event Ends
</script>
Posting with ajax is a pain in the ass. Since there is Jquery .post() its very easy. Modify if it's not correct. Let me know if it helped.
I see you use alert(). Use console.log() instead. No annoying popups. you can see the data in developer tools console.
EDIT2
The error you get, means your url isn't correct. You are trying to post to a file instead to an url.
I suppose you have an index file or a file that includes other files.
Enter some php code to the file that includes this script.
The php script checks in the url for data and if its true.
<?php
if(isset($_POST['data']) AND $_GET['data'] == 'true'){
//Go to your php file. or include it.
//EXAMPLE
include "/bin/sendredeempoints.php";
//On the sendredeempoints you can do whatever you want with the post.
}
?>
Change your var url to this:
var url = "YOURWEBSITE.com?data=true"; // or the easy one
var url = window.location.href + "?data=true";
Related
This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 9 months ago.
I am trying to pass data to my php page:
<?php
var_dump($_POST);
if (isset($_POST['goal']) && isset($_POST['amount'])){
$goal = $_POST['goal'];
$amount = $_POST['amount'];
$array = array(
"goal" => $goal,
"amount" => $amount
);
echo json_encode($array);
}
However as a result of var_dump $_POST I keep getting an empty array, for some reason my ajax doesn't pass the neccessary data. I tried console.logging the value of fields that I am using and their value is correct it's just that data doesn't pass on the php page.
ajax:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
let amount = $("#amount").val();
let goal = $("#goal_name").val();
$.ajax({
method: "post",
url: "target-modal-code.php",
data:JSON.stringify( {
amount: amount,
goal: goal
}),
contentType:"application/json",
success: function (response){
$("#response").text(response);
console.log(amount);
console.log(goal);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
And my form is inside a modal :
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="enrollLabel">Change your goal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="target-modal-code.php" name="target-form" id="target-form">
<div class="modal-body">
<form action="">
<div class="mb-3 input-control">
<label for="amount">Cost</label>
<input type="number" class="form-control" id="amount" name="amount"
placeholder="Amount">
<small class="message" id="message-password"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="goal_name">Goal</label>
<input type="text" class="form-control" id="goal_name" name="goal_name"
placeholder="Goal">
<small class="message" id="message-password"></small>
<br>
</div>
</form>
</div>
<p class="response" id="response"></p>
<div class="modal-footer">
<div class="response">
</div>
<button type="button" id="goalBTN" class="btn btn-warning">Save changes</button>
</div>
</form>
</div>
</div>
Updated answer after some live testing with Network tab in firefox web dev tools
The problem is that the current ajax code is not sending any of the elements because of wrong content-type. Let it detect content-type automatically. For jq ajax, default seems to be contentType: application/x-www-form-urlencoded even if you don't provide it specifically.
So, this worked:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
// let amount = $("#amount").val();
// let goal = $("#goal_name").val();
var formData = {
amount: $("#amount").val(),
goal_name: $("#goal_name").val(),
};
$.ajax({
method: "post",
url: "target-modal-code.php",
// datatype:"json",
//data:JSON.stringify(formData),
data: formData,
//contentType:"application/json",
//encode: true,
success: function (response){
$("#response").text(response);
// console.log(amount);
// console.log(goal);
console.log(formData);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
After little bit of fiddling, I noticed that it works if you DON'T provide it contentType at all. Otherwise, AJAX won't send GET or POST params to the server.... dont know why. I know it's weird but that's how it is in jquery ajax.
I have intentionally kept the comments for you to see what all I have tried.
So to summarize,
Don't stringify the form data,
Don't provide contentType to ajax
request.
Cheers.!
format send ajax:
$.ajax({
...
data : {
foo : 'bar',
bar : 'foo'
},
...
});
in your case: change data send format like:
data: {
amount: amount,
goal: goal
}
I have a page with some bootstrap cards. Information showing inside the card is retrieved from MySQL database.
What I need
I need these cards to be updated every 3 seconds without reloading the page. I know that Ajax is the way to do this (Update content without refreshing page). I am not familiar with Ajax. However, I tried as below
<script>
setInterval(
(function x() {
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
return x;
})(), 3000);
</script>
Also I gave the following div with id inputFieldDisplay as below
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
My Issue
When I redirect to the mentioned page vTagInfoCall.php with all my php codes and contents, it is not loading anything to the div with id inputFieldDisplay. Did anyone know what am I doing wrong here?
Edit 1
Following is my vTagInfoCall.php file contents
<?php ob_start();?>
<?php include "db.php"; ?>
<?php
$tagQuery = "SELECT * FROM vtagdetails WHERE status = 0";
$tagQueryExecute = mysqli_query($conn, $tagQuery);
$openItems = mysqli_num_rows($tagQueryExecute);
while($tagQueryRows = mysqli_fetch_array($tagQueryExecute)){
$srNumber = $tagQueryRows['srNumber'];
$Name = $tagQueryRows['Name'];
$Code = $tagQueryRows['Code'];
$customerName = $tagQueryRows['customers'];
$Type = $tagQueryRows['Type'];
session_start();
echo '<form method="post"> <div class="card cardBodyStyle">
<div class="card-body" >
<div class="row">
<input type="text" name= "srNum" value = "'.$srNumber.'" hidden>
<input type="text" name= "tpCode" value = "'.$Code.'" hidden>
<div class="col-sm"><i class="fab fa-500px"></i> '.$Name.'</div>
<div class="col-sm"><i class="fas fa-atom"></i> '.$Type.'</div>
<div class="col-sm"><i class="fas fa-globe fa-spin"></i> '.$customerName.'</div>
</div>
</div></div></form><br>';
}
?>
Edit 2
It is showing the following error in console. Can someone help why is the error?
I found two issues in code:
First in your script, please use below code:
<script>
setInterval(x, 3000);
function x() {
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
})
}
</script>
Second one is remove # from your id of div because # is just use to indicate id of element in jquery and .(dot) for class name of element. Please update your code with below code:
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
You can use directly in setInterval function
setInterval(function()
{
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
}, 3000);//time in milliseconds
And the problem is in Html div also as showed by madhuri and haisen.
Whenever you used attributes(name,id,class whatever) you dont need to put dot,# or other symbols in the div or input.
So please fix it. I think it will work definitely.
<div id="#inputFieldDisplay"></div> // Wrong because of #
<div id="inputFieldDisplay"></div> //Right
you html code with some incorrect in id="#inputFieldDisplay"
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
After many trials and methods, found out that I was using CDN of slim version of jQuery which caused this problem. Somehow there is some issue with Ajax in the slim version
I solved it by using the uncompressed version of jQuery CDN from here and that is it!!
I apologize for the ease of this question for you.
But I looked at your beautiful site for an answer to my problem, but I was not lucky.
I'm trying to build my own,form-wizard for student registration, in easy steps as a graduate project for university.
I use PHP, JQuery and AJAX to send data .
My problem:
I have a single form and to button ,
The first three input are searched in the database via the submit button and it is worked good ,
then automatically form-wizard moves to the next fieldset and then displays the inpust field to
student to enter his information .
finally thir is button to save data to database
by AJAX and this button is my problem .
the php say undefined index .
this is code for html wizard-form
$('form').on('submit', function(e) {
var $formInput = $(this).find('.fi');
$formInput.each(function(i) {
if (!$(this).val()) {
e.preventDefault();
$(this).addClass('input-error');
return false;
} else {
if ($formInput.length === i + 1) {
var id_high_school = $('[name="id_high_school"]').val();
var SEC_SCHOOL_YEAR = $('[name="SEC_SCHOOL_YEAR"]').val().toString();
var sum_high_school = $('[name="sum_high_school"]').val();
alert(SEC_SCHOOL_YEAR);
$.ajax({
url: "select_for_modal_serch.php",
method: "post",
data: {
id_high_school: id_high_school,
SEC_SCHOOL_YEAR: SEC_SCHOOL_YEAR,
sum_high_school: sum_high_school
}
}).done(function(datas) {
$('#studint_detail').html(datas);
$('#dataModal').modal("show");
}).fail(function() {
alert('fail..');
});
}
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form name="mainForm" action=" <?php echo $_SERVER['PHP_SELF'] . '#form1' ?> " id="form1" method="POST" enctype="multipart/form-data">
<!-- condetion for regster -->
<fieldset>
<iframe src="license.html"></iframe>
<input class="form-check-input" id="check_qury" type="checkbox" value="yes">
<div class="wizard-buttons">
<button type="button" class="btn btn-next">التالي</button>
</div>
</fieldset>
<fieldset>
<!-- 3 <input type = text > to search for data from mysql -->
<!--her is the submit button and is get data by ajax -->
<input type="submit" class="form-control btn btn-primary view-data" id="submit_high_school" value="بحث" name="submit_high_school" />
<!-- by ajax is work and then is go to the next filedset -->
</fieldset>
<fieldset>
<!-- mor data <input type = text > to search for data from mysql -->
<button type="button" id="sava_data_to_tables" name="sava_data_to_tables" class="btn btn-next">
<!-- this is the button of my problem cant send this form data to mysql -->
</fieldset>
I doing this code to solve the problem but nothing work :
$('#sava_data_to_tables').on('click', function (event) {
var form_data = $(this).parents('form').serialize();
var colage = $('[name="colage"]').val();
var spichelest = $('[name="spichelest"]').val();
// and rest of input type
$.ajax({
url: "insert_into_info_contact.php",
method: "POST",
data: form_data,
success: function (data) {
alert(data);
}, cache: false,
contentType: false,
processData: false
});
});
and my PHP :
<?php
// isset($_POST['sava_data_to_tables'])
//$_SERVER['REQUEST_METHOD']==='POST'
// !empty($_POST)
if ($_SERVER['REQUEST_METHOD']==='post')
{ echo "you submit data"
;}
else {
echo "its not work" ; }
?>
I found some help from a friend ..
He just change this :
var form_data = $(this).closest('form').serialize();
to this :
var form_data = new FormData($(this).closest('#form1').get(0));
He solved my problem.
I honestly did not understand what the problem was, but he told me I had sent a different kind of data >> Thanks every One . :)
i searched a lot about this problem, but I didn't find a solution, yet.
At first a short description about my setup to make my problem clearer.
Settings.php Page with a Menu, where you can select different settings categories
By clicking on one menu point the corresponding loads by ajax and is displayed.
$('#content').load("http://"+ document.domain + "/domainhere/settings/menupoint1.php");
On the menupont1.php page I got a list with mysql data.
I implemented a "edit" button for each row - while clicking on the edit button, a boostrap modal appears with a form and the corresponding data filled in and ready to edit.
When i now click on "Save changes", the POST-Request is always empty.
To realize the form submit, I already tried several codes:
e.g.:
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
or
$(function(){
$('#editform').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#editform').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
At the moment:
while($xy= $xysql->fetch_assoc()) {
<div class="modal fade" id="edit-<?php echo $xy["id"] ?>" [..]>
<button id="submit>" class="btn btn-default">Save</button>
</div>
<script>
$(function() {
$('button#submit').click(function(){
$.ajax({
type: 'POST',
url: './test2.php',
data: $('form#modal-form').serialize(),
success: function(msg){
$('#test').html(msg)
$('#form-content').modal('hide');
},
error: function(){
alert('failure');
}
});
});
});
</script>
Maybe someone here could help me out with this problem?
thank you very much :)
I've set up a minimal example of how this would work:
example html of two modals, which are produced in a loop in your case.
I've now done it without a unique id, but with selecting via class.
<div class="modal">
<!-- // this classname is new and important -->
<form class="editform">
<input name="test" value="value1">
<button class="btn btn-default">Save</button>
</form>
</div>
<div class="modal">
<form class="editform">
<input name="test" value="value2">
<button class="btn btn-default">Save</button>
</form>
</div>
Your javascript would be something like this:
$(function() {
var formsAll = $('.editform');
// changed this to onSubmit, because it's easier to implement the preventDefault!
formsAll.on('submit',function(e){
e.preventDefault();
var formData = $(this).serialize();
console.log(formData);
// add your ajax call here.
// note, that we already have the formData, it would be "data: formData," in ajax.
});
});
Note, that I don't have your real html structure, so details might vary. But you get the idea.
also available here:
https://jsfiddle.net/a0qhgmsb/16/
I'm facing a problem using the FancyBox plugin. I'm trying to submit a form with Ajax and just print a nice little success message, no validation just yet, trying to get it to work. I can submit with jQuery and display the value of any input within the FancyBox. However when I try to execute Ajax it just closes the FancyBox down. I'm not an expert...
The FancyBox's content is generated using Ajax because it requires data from a database.
Here are the important code parts: (Texts are German...)
The file loaded into the FancyBox using Ajax
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
alert('Richtig.');
}
else
{
alert('Falsche Benutzername/Passwort Kombination.');
}
}
});
});
</script>
<div class="login">
<div class="widget_header">
<h4 class="widget_header_title wwIcon i_16_wysiwyg">Benutzer Bearbeiten</h4>
</div>
<div class="widget_contents lgNoPadding">
<form method="post" id="form-edit">
<p id="errormessagehere"></p>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Benutzername</span></div>
<div class="g_9 g_9M">
<input type="text" name="login" id="login" value="<?php echo getusername($_GET['u']) ?>" class="simple_field tooltip" placeholder="Benutzername" autocomplete="off"></div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Passwort</span></div>
<div class="g_9 g_9M">
********
</div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_6">Abschicken
</div>
<div class="clear"></div>
</div>
</form>
</div>
</div>
Here's how I call the Fancy box
$(document).ready(function() {
$(".fancybox").fancybox({
'scrolling' : 'no',
'padding' : 0,
'titleShow' : false
});
});
handleuseredit.php just echoes "ok" to fullfill the data variable requirement.
You can test something like this with the version 2 of fancybox (http://fancyapps.com/fancybox/):
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
$.fancybox( '<h1>Richtig.</h1>' );
}
else
{
$.fancybox( '<h1>Falsche Benutzername/Passwort Kombination.</h1>' );
}
}
});
});
</script>