I am using the following code to post form data to a php file..
jQuery("#form-submit").click(function(data){
var url = "save-data.php";
jQuery.ajax({
type: "POST",
data: jQuery('#my-form').serialize(),
url: url,
cache : "false",
success: function(data){
jQuery("#dl-message").html(data);
jQuery("#dl-message").css('background-color', '#0C3');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
},
error: function ( jqXHR, textStatus, errorThrown){
jQuery("#dl-message").html('There was an error saving your form: ' + errorThrown);
jQuery("#dl-message").css('background-color', '#F33');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
}
});
return false;
});
and then in my php file I am simply looking for $_POST['field-name'] to see if the contents of the form were posted. The ajax call returns successful, however no data from the form seems to be posted to the PHP file. When I call...
$name = $_POST['name'];
echo "Your name is: " . $name;
I get nothing.... Does anyone see anything wrong with my ajax call at all?
Thanks so much for your time...
So it seems the post was empty at the first place (btw you can include your last three posts inside the question by editing it). Are you sure your form's id is 'my-form'?
Related
Every one am new to php and ajax.
Am writing a code to fetch data from mysql database
and display them in textboxes but is not working.
Here is my code.
I need your help please.
Thanks in advance
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
}
});
});
<input type="text" id="input-box1">
<input type="text" id="input-box2">
<button type="button" id="btn_get">Click</button>
//get data from db here
$textbox1 = 'foo';
$textbox2 = 'deen';
echo $textbox1;
echo $textbox2;
Here are some approaches, maybe them can help you:
The first approach would be to check your console to make sure that the jQuery version allows you to use the $.ajax() resource. Some jQuery versions like the "slim" doesn't provide ajax calls.
Once you have checked that put the property error within your ajax call:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});
If you have a error response you will be able to identify it checking your browser's console tool (F12).
Check your /path/to/php/file to make sure that your file really exists.
Remember that the success callback gets your echo command as a string. So probably your return will be something like this:
foodeen
A good approach would be to return a json response:
$textbox1 = 'foo';
$textbox2 = 'deen';
echo json_encode(array($textbox1 ,"textBox1"));
Finally when your response is executed in the success callback you'll be able to convert it from plain string to a json format:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
var response = JSON.stringify(data);
$('#input-box1').val(response[0]);
$('#input-box2').val(response[1]);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});
i need help because i'm stuck and don't know what's wrong ,i try to send user clicked button "id" to php to get related data from database in the same page
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
console.log(res, data);
},
error: function(err) {
alert(err);
}
});
});
the ajax print success in console log ,here is php code to get the value if clicked id
<?php
if(isset($_POST['ToEditId'])){
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
}
but nothing happen in php file !!
Which is the expected behaviour.
PHP is not dynamic. It doesn't "update".
PHP only runs once. This means that once your page is rendered, you cannot use PHP to change it again. You actually would have to use javascript to change the page, like so;
PHP side:
<?php
if(isset($_POST['ToEditId'])){
echo $_POST['ToEditId'];
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
die(); // prevent entire page from re-rendering again.
}
JS side:
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
//Add your PHP file's response to the body through javascript.
$('body').append(res);
},
error: function(err) {
alert(err);
}
});
});
As #IncredibleHat mentioned, you should make sure your page doesn't render any of its usual HTML, so it won't return the entire page back to your ajax call. So put the PHP all the way above your html!
Updated Question to better reflect the communities support
Based on community support I have changed the Ajax function to be as such:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The resulting PHP Class is as such:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET['element_name'])){
$this->_element_name = $_GET['element_name'];
echo $this->_element_name;
}
}
}
The network tab shows that I have some out put from activating the Jquery which I have shown below:
The Console is spitting out no errors, yet not echoing the element name. I have read up on the Jquery Ajax API and everything I have been doing, thus far, seems to be correct. Yet I am not getting the desired out put.
Note: The response tab is empty.... In other words I am not getting a response back.
You're not passing in the event to your click handler.
Use.
$('a').click(function(e){
// Your code
});
$.ajax({
url : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(result) {
console.log(result)
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
Simplify the situation. Just for a moment, change your AJAX processor file (UncheckPackageThemeHelper.php) to read like this:
UncheckPackageThemeHelper.php
<?php
$test = $_POST['element_name'];
$r = 'PHP received: [' .$test. ']';
echo $r;
die();
Also, change your AJAX success function to read like this:
success: function(result) {
alert(result);
},
At least, this will show you that your AJAX is getting through.
Then, start adding things back into your AJAX processor file (one or two at a time) and keep echoing something out so that you can discover where the error is happening.
So I was doing a lot of things wrong. But this is the only way it works, for me - please post your comments if you have better solution.
In the class, I have to do this:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET["element_name"])){
$this->_element_name = $_GET["element_name"];
echo json_encode($this->_element_name);
}
}
}
new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();
The class cannot be instantiated in the .phtml file with the resulting Ajax or the request is never sent back. Also notice the json_encode You cannot pass regular variables back to Ajax - when in a class (I think) - How ever when not in a class it seems to work - clarification is needed.
The Ajax then looks like this:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The Data that comes back is what I expect: "aisis_options[package_RelatedPosts]"
There ar a couple of issues with this answer - One I dont understand why I have to instantiate the class inside the file its written in, and two not sure why I have to encode the response in a class, but not when its just a "script kiddy" file.
I have a javascript function which I'm using to change the action field of a form and then submit it. Here's the function
function printmulti(){
form=document.forms['form2'];
form.action="http://localhost/output_sample1.php/";
form.target = "_blank"; // Open in a new window
form.submit();
form.action="http://localhost/output_sample2.php/";
form.target = "_blank";
form.submit();
return true; }
But somehow only output_sample2.php is being shown. Why isn't the first part of the code being executed?
you cant submit to multiple forms like that, you need to use something like ajax and make the requests that way. Currently you are starting the submit for the first and then starting the second right after so the second one stops the first one from submitting.
Ajax Tutorial
Use ajax like this:
$.ajax({
type: 'POST',
url: 'http://localhost/output_sample1.php/',
data: 'var1='+var1+'&var2=var2', //your variables sent as post at output_sample1.php
success: function( data ) {
//do success stuff
},
error: function(xhr, status, error) {
alert(status); //if any error
},
dataType: 'text'
});
$.ajax({
type: 'POST',
url: 'http://localhost/output_sample2.php/',
data: 'var1='+var1+'&var2=var2', //your variables sent as post at output_sample2.php
success: function( data ) {
//do success stuff
},
error: function(xhr, status, error) {
alert(status); //if any error
},
dataType: 'text'
});
Hope will give you some idea to start your work. For more info visit this link ajax example
I have been trying for hours to make this work but I am not getting anything back when doing the ajax call. I am new to Ajax and it could probably be something you will see but that I am unable to. I would appreciate you help. Here is my code.
HTML
<script>
$("#submitlogin").click(function() {
inputs = {
"logInUsername" : $('input[name=logInUsername]').val(),
"logInPassword" : $('input[name=logInPassword]').val()
};
// since this is a username and password combo you will probably want to use $.post
$.ajax ({
type: "POST",
url: "loggnow.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
}
});
});
</script>
loggnow.php
<?php
extract($_POST);
if($_POST)
{
echo 'Yes the ajax posted';
}
?>
Try this :
$(document).ready(function(){
$("#submitlogin").click(function() {
inputs = {
"logInUsername" : $('input[name=logInUsername]').val(),
"logInPassword" : $('input[name=logInPassword]').val()
};
// since this is a username and password combo you will probably want to use $.post
$.ajax ({
type: "POST",
url: "loggnow.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
},
error : function(jqXHR, textStatus, errorThrown){
alert("error " + textStatus + ": " + errorThrown);
}
});
});
});
This will give you an alert if an error occurs in AJAX with details
EDIT:
As Leo pointed it out, your code might be executing too fast, try the modified code above so that you make sure it runs after all the page has loaded
Try to put your function inside
$(function(){
//attach the button click here
});
this way your code will only run after the body loaded (so you are sure that you button exists) - look here
you just need a web server host looks like this:http://127.0.0.1:8084/xxx