I am using a custom options framework which is working in all browsers except for Internet Explorer (what a surprise!). The submit form is configured like this;
<form action="<?php echo site_url() .'/wp-admin/admin-ajax.php'; ?>" method="post" id="mobeus-form">
In all other browsers, when the form is submitted, the changes are saved as expected. But, in Internet Explorer, it seems to be accessing the PHP file directly, as it has this in the url bar;
http://mydomain.com/wp-admin/admin-ajax.php
The page itself has a line of text;
{"error":false,"message":"Settings Successfully Saved!","type":""}
Nothing else happens, the settings are not saved, and I am left baffled. If anyone could help I'd appreciate it!
admin-ajax.php file is meant for ajax process, so instead of trying it in form action attribute try with jquery stuff to pass the data to admin-ajax and retrieve the value, or try something like below to use the same form with jquery submission.
var data = jQuery("#myForm :input").serializeArray();
jQuery.post(jQuery("#myForm").attr("action"),data, function(info) {
// success code ;
});
Related
I am complete php/js newbie and i got stuck on something that i cant figure out.
I have page at www.test.com/page with a search form that calls www.test.com/results like this:
<form method="post" action="https://www.test.com/results">
<input type="text" placeholder="Enter URL:" required="">
<button>Search</button>
</form>
Form gets URL that the user typed in, passes it to /results, the line ($url = $_POST['url'];) is where it is analyzed and results are displayed.
But, i would want the search results to open in (bootstrap) modal instead of new page. I know this can be done with AJAX but i am complete newbie and am looking for most dirty simple solution that would make it work.
Again, sorry if this is too "newbie" type of question, i am still learning.
Yes, you can use jQuery and AJAX to control the form submit. So something akin to the code example below should do the trick:
$('#myForm').on('submit', function(event) {
$.post('https://www.test.com/results', { URL: "some_url.com" }, function(data) {
// Render the results onto your modal anyway you want with data
// retrieved from server here
$("#my-modal-object").html(data);
}).error(function() {
// Handle the event when the call to "/results" fails
alert("Yikes! Call to /results failed!");
});
// Prevents default browser behaviour which submits the form
// then routes to another page, if specified
event.preventDefault();
});
Short explanation:
We attached a "submit" event listener to your form object and performed a POST AJAX request to your server endpoint /results. Server passes back the processed search results into the callback function of $.post and renders it onto your modal object. You may also change the 2nd argument of $.post, i.e. { URL: "some_url.com" } to whatever data object you want to pass to your server.
This should help you get started with rendering your search results onto your modal element instead of navigating to a new page.
I hope I am missing something simple here. I have a CakePHP web site I am using jQuery mobile with. I think CakePHP might have something to do with it, but I am not sure.
Anyway, I have a form I've created on my view page for adding comments. The Ajax call is working as expected on the first page that loads, but navigating to any other page prevents the data from being submitted. The console still logs 'data' each time I press the button (after using 'pagebeforeshow' as recommended somewhere else), however it seems to be the data from the original loaded page (I know this because I am currently debugging $this->request->data on the Form action page).
Clearly, I must need to "reset" the form somehow when moving across pages, but I am not sure if this is possible without refreshing the page. I do know about "data-ajax"="false" and "rel"="external" which can be used as a last resort, but I want to avoid refreshing the page if I can.
Any suggestions? Thank you.
Here is the JS I am using for the Ajax call
//<![CDATA[
$(document).on('pagebeforeshow', function(){
$(document).off('click', '#comment_add').on('click', '#comment_add',function(e) {
$.ajax({
async:true,
data:$("#sCommentViewForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
//$('#comments').remove();
//$('<div id="comments"></div>').appendTo('#comments_container');
$("#comments").html(data).trigger('create');
//$('#comments_box').remove();
//$('<div id="comments_box"></div>').appendTo('#comments_container');
console.log(data);
},
type:"POST",
url:"commentsUsers/comment_add/<? echo $template['Template']['id']; ?>"});
return false;
});
});
//]]>
</script>
It was my basic lack of understanding. After lots of searching this simple post was most helpful:
Jquery Mobile Javascript not working on ajax load
Basically, I was using IDs for everything - when I switched to class names it was smooth sailing.
I have a one page website in the works that has a contact form where its contact error and contact thank you messages are placed further down the page as hidden divs.
The contact form calls an external php file that calls the anchor links of the error and thank you message divs in the index.html file.
www.photograsurfer.com/test/index.html
www.photograsurfer.com/test/code/contact-panel.php
Everything works successfully as long as the divs are not hidden. So now I need to use the following javascript to get the hidden divs to display when needed.
<script type="text/javascript">
function showContactPanelError() {
document.getElementById('contact-panel-error').style.display = "block";
}
</script>
My problem, besides being a complete PHP beginner, is that I don't know how to get the PHP file to reference the Javascript code to display the hidden divs properly on the main page.
Any help is appreciated.
Thanks.
Use jQuery forms (http://malsup.com/jquery/form/) to submit your form via AJAX, then show/hide divs depending on values you return from PHP scripts.
you could assign php variable to javascript as
var error="<?php echo $_GET['error']; ?>";
the $error is the data passed along with the url like wwww.example.com/test.php?error=1
Now you could check var error and call your function showContactPanelError().
I ended up going with a mixture of the 2 methods on these pages.
http://trevordavis.net/blog/ajax-forms-with-jquery
https://spruce.it/noise/simple-ajax-contact-form/#contact
Ditched the div idea since the Ajax method allowed me to not reload the page and enter error and thank you messages within the contact form itself. Seemed like an easier approach.
Thanks for all of the suggestions, as I never would have looked at using Ajax otherwise.
You can add a onclick event on submit button. On clicking it will create an ajax call send data to the required external PHP file and then on success will display the hidden division properly on the main page.
here's a sample code just for an explanation
**
* Description : Function that will trigger the AJAX request.
* #param none
*/
function CategorySubscriber_Unsubscribe(){
var data = {
'data-1': data-1,
'data-2': data-2,
// as per your need you can put any number of data
};
var url = // your url
jQuery.post(url, data, function(response){
jQuery.show("#your-div-id");
});
}
function(response) will be executed when ajax call will be in success status.
You can learn it from these links
http://www.w3schools.com/jquery/ajax_post.asp
http://api.jquery.com/jQuery.post/
This question may seem completely stupid, but say i have a PHP page with some form processing at the top in php and a html form underneath with the action of submitting to same page and method of post. How do i get the result via ajax, ie. send form to self without refreshing the page, if that makes sense? Thanks
It sounds like you're asking about Ajax basics, right? I suggest using jQuery to handle the Ajax part.
Put jQuery in your page, and then do something like
$(document).ready(function(){
$('#submit_button').click(function(){
var something='value to send to PHP';
$.post('name_of_page.php',{"a_var":something},function(data){ /* do something with the data you received back*/ },'json');
});
});
Then in your PHP page, set up to handle a post or normal HTML output.
<?php
if($_POST['a_var']){
$result=do_something($_POST['a_var']);
echo json_encode($result);
exit;
}
//if there was no POST value, it continues to here
<html>
This is the rest of your page.
You'd have the form and the above javascript and so on here.
</html>
In your page, check if the page has POST parameters. If it does, process them and return a confirmation. If it doesn't, display the form.
I am using php/ajax to submit a form without page refresh. Here are my files-
coupon.js
jQuery(document).ready(function(){
jQuery(".appnitro").submit( function(e) {
$.ajax({
url : "sms.php",
type : "post",
dataType: "json",
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false or
e.preventDefault();
});
});
sms.php
<?php
//process form
$res = "Message successfully delivered";
$arr = array( 'mess' => $res );
echo json_encode( $arr );//end sms processing
unset ($_POST);
?>
and here is code for my html page -
<form id="smsform" class="appnitro" action="sms.php" method="post">
...
</form>
<div id="mess" style="background:green;"></div>
Now instead of submitting form through ajax without page refreshing what is happening is that page gets redirected to
baseurl/sms.php and the only thing visible on page is
{"mess":"Message successfully delivered"}
My guess is that php script is not returning back successfully to the jquery and hence the echo in last part of sms.php is getting displayed. How should i make the php script return successfully?
ANY IDEAS HOW TO DEBUG THIS.I HAVE TRIED USING return false at the end of coupon.js but no results.
When i click on submit firebug gives following results -
POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
404 Not Found 1.29s `jquery.min.js (line 130)`
Response
Firebug needs to POST to the server to get this information for url:
http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
This second POST can interfere with some sites. If you want to send the POST again, open a new tab in Firefox, use URL 'about:config', set boolean value 'extensions.firebug.allowDoublePost' to true
This value is reset every time you restart Firefox This problem will disappear when https://bugzilla.mozilla.org/show_bug.cgi?id=430155 is shipped
#Fanis It's irrelevant whether he uses '$' or 'jQuery', they are synonyms.
#Ayush
As Fanis says, you should try Firebug if you don't use it already.
I've checked the example at my server, works OK, and I don't know
what's the problem at Your side.
You can use onsubmit="return false" to disable form submission:
<form id="..." class="..." ... onsubmit="return false">
Also check if javascript is enabled, for example do "alert('something')"
at $(document).ready
Edit:
// instead of
url: "sms.php"
// try
url: "/~kunal17/devbuzzr/wp-content/themes/street/sms.php"
// although I don't really know if it will help
If you're being redirected to sms.php instead of doing an ajax call, it probably means that there's something wrong with your jQuery code, probably the event binding itself.
I'm not sure without testing it, but shouldn't that code be:
$(document).ready(function(){
$(".appnitro").submit( function(e) {
$.ajax({
...
?
Check the javascript console, either in Firefox/Firebug or Chrome-IE/Developer Tools. Does it show any errors in those lines?
Fanis and Michal Kluczka are probably right about the issue with event binding , I tried your code myself as well, and it works for me.
Put an alert('X') as the first statements in your jQuery(document).ready() and jQuery(".appnitro").submit() functions and see if both are displayed (first one upon document load, second one upon form submission).
One more thing: I suggest you include a
header('Content-Type: application/json');
into your sms.php file before printing your JSON data to protect against cross-site-scripting (XSS) attacks. See also Don’t serve JSON as text/html for details.