I have OOP php file and I would like to call one of the function by AJAX, i have read a lot about this (mostly stackoverflow), but for some reason, it just doesnt work.
I know that ajax function is called (I tried to add some alert into success function and that alert appeared after clicking the button), but somehow it ignores everything from file ajax.php (i even tried to add some echo at the top of ajax.php file, but nothing happened)
also note that I need button, not input (although that would be much easier)
this is my button:
<button class='formular-button' type='button' onclick='prihlasPA()'> vypiš přihlaš </button>
this is my script for button:
<script>
function prihlasPA() {
$.ajax({
type: "POST",
url: "ajax.php",
data: {action: 'prihlasP'},
success: function(){},
error: function(){
alert("chyba");
}
});
}
</script>
and this is inside ajax.php, which is called by AJAX:
include( 'navstevnik.php' );
echo "aaa";
if(isset($_POST['action']) ) {
$navstevnik = new navstevnik; //navstevnik is name of my class btw
$navstevnik->vypisPrihlas();
}
I dont think it matters, but in my function vypisPrihlas() is this code:
public function vypisPrihlas(){
$this->index=1;
echo '
<fieldset class="formular">
<div class="pure-control-group stred" >
<input id="nick" type="text" name="nickP" placeholder="Nickname">
</div>
<div class="pure-control-group stred">
<input id="password" type="password" name="hesloP" placeholder="Heslo">
</div>
<input class="pure-button pure-button-primary stred" style=width:188px; type="submit" name="buttonP" value="přihlásit" />
</fieldset>';
}
I don't see any issues with the above code.
When the function vypisPrihlas echos the HTML, you won't see it on your main page. Instead, you need to load it in from your success function and append the HTML somewhere on your page.
$.ajax({
type: "POST",
url: "ajax.php",
data: {action: 'prihlasP'},
success: function(data){
$( ".your_favorite_div" ).append(data);
},
error: function(){
alert("chyba");
}
});
By what you said, the ajax function is fine, right?
I think your problem is the path for PHP, since it is not called. try change this line
url: "ajax.php",
for the complete path, like \var\www\path_to_code\ajax.php. Maybe it helps.
Related
I am attempting to create an upload document which will upload a profile picture. I am having trouble capturing the data from the changePicture form which only has an input for the images and a submit. I have never used the FormData object to date, so I am still learning around this. Any guidance would be useful.
See my HTML
<form id="changePicture" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Update Your Profile Picture</label>
<input type="file" id="profilePic" class="form-control" name="profilePic">
<input type="hidden" value="<?php echo $id; ?>" name="id">
</div>
<button type="submit" id="updateProfileBtn" class="btn btn-success float-right">Upload Image</button>
</form>
Here is my AJAX code:
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(result){
$("#spinner").hide();
$("#changePicture").append(result);
setTimeout(function(){
$("#changePicture").slideDown();
}, 1500);
}
});
}, 3000);
});
}
The PHP file at this moment only echos out "Working" to see it accesses the page alright, which it does. However, when I attempt to locate the file through a variable nothing has been sent and returns undefined index.
this will be undefined because it's inside ajax's scope
Try:
me = this;
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(me),
...
As, for me, when using ajax I always prefer to base64encode the image and pass it as a JSON to PHP but i guess that's a personal preference...
Why are you wrapping your AJAX call in a
setTimeout(function() {..})
?
By doing this, you cannot simply write new FormData(this), because the this context does not refer to the form that you are looking for.
Try executing the code without the timeout, or try storing the form data in a global variable
Edit: Example added:
var myFormData;
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
myFormData = new FormData(this);
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: myFormData,
....
<form role="form" method="post" action="test.php">
<label for="contact">Mobile No:</label><br>
<input type="tel" class="form-control" name="contact" title="Mobile number should not contain alphabets. Maxlength 10" placeholder="Enter your phone no" maxlength="15" required id='contact_no'>
<br><br>
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
<button type="reset" class="btn btn-default" id='reset'>Reset</button>
</form>
Ajax and Javascript Code
script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dialcode = $(".country-list .active").data().dialCode;
var contact = $("#contact_no").val().replace(" ","");
var countrycode = $('.country-list .active').data().countryCode;
var cn;
var cc;
var dc;
$.ajax({
url: "test.php",
type: "POST",
data: {'cc' : contact},
success: function(data)
{
alert("success");
}
});
});
});
</script>
The variables show the values if displayed by alert message but are not passed on to the test.php page. It shows undefined index error at the following statement
test.php is as follows
<?php
if(isset($_POST['submit'])){
$contact = $_POST['cc']; //it shows the error here
}
echo $contact;
I had referred to many websites which show the same thing. It dosent work for me. I think the syntz of ajax is correct and have tried all possibilities but still dosent work. Please help
You're posting {cc: contact}, but you're checking for $_POST['submit'] which isn't being sent. The callback also doesn't stop the event, so you might want to return false (stops default and propagation). Something like this should do the trick:
$('#submit').on('click', function()
{
//do stuff
$.ajax({
data: {cc: contact},
method: 'post',
success: function()
{
//handle response here
}
});
return false;
});
Then, in PHP:
if (isset($_POST['cc']))
{
//ajax request with cc data
}
Also not that this:
$("#contact_no").val().replace(" ","");
Will only replace 1 space, not all of them, for that you'll need to use a regex with a g (for global) flag:
$("#contact_no").val().replace(/\s+/g,"");
You are using ajax to form submit
and you use $_POST['submit'] to check it would be $_POST['cc']
test.php
<?php
if(isset($_POST['cc'])){// change submit to cc
$contact = $_POST['cc'];//it shows the error here
}
echo $contact;
#Saty answer worked for me, but my code on ajax was a bit different. I had multiple form data wrapped up into a form variable, that was passed to the php page.
const form = new FormData();
form.append('keywords', keywords);
form.append('timescale', timescale);
form.append('pricing_entered', pricing_entered);
$.ajax({
url: "../config/save_status.php",
data: form,
method: "POST",
datatype: "text",
success: function (response, data) {
}
Then my php was:
if (isset($_POST['data'])) {
// all code about database uploading
}
I have no idea how to implement this, let me try to explain
I have a form that open inside a bootstrap modal frame in my layout, in this form i have 2 fields
<input type="file" name="photoimg" id="photoimg" value="" />
<input type="hidden" name="consulta" value="5">
I need to submit this to my url with the value 5 for 'consulta' so the script can read and do the proper things with the file,
BUT
I need to do this without refreshing the opened modal, in other words, using ajax to submit the file (for further cropping)
i have this script that do the submit, what i'm doing wrong here?
<script type="text/javascript">
function enviaimagem(){
$.ajax({
type: "POST",
data: { consulta:5 },
dataType: 'html',
url: "<?=JURI::ROOT()?>ajax.html",
//dataType: "html",
success: function(result){
$("#corpo_modal").html('');
$("#corpo_modal").html(result);
},
beforeSend: function(){
$("#corpo_modal").html('');
$("#corpo_modal").css({display:"none"});
$('#ajaxloadergeneric').css({display:"block"});
},
complete: function(msg){
$('#ajaxloadergeneric').css({display:"none"});
$("#corpo_modal").css({display:"block"});
}
});
}
</script>
File upload through AJAX is supported through FormData object:
https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
, however it is not supported by all/old browsers( especially IE < 10)
I am writing a plugin for a wordpress, where I use jquery for AJAX.
Following code doesn't work. I expect to show the content in results div when I type in input box.
Here is the code I use for ajax request. It is located on my theme header file.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
//alert("sjsjs");
$("#se").keypress(function(e){
// e.preventDefault();
var search_val=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_string:search_val
},
success:function(data){
$('#results').append(response);
}
});
});
});
</script>
html content in template file
<form name="nn" action="" method="post"></br></br>
<input id ="se" type="text" name="test" width="20" />
<input type="submit" id="clicksubmit" value="Submit" />
</form>
<div id="results">val is:
</div>
Here is the code in plugin file
function wpay_search() {
//global $wpdb; // this is how you get access to the database
$whatever = $_POST['search_val'];
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
add_action('wp_ajax_wpay_search', 'wpay_search');
add_action('wp_ajax_nopriv_wpay_search', 'wpay_search');
I am new to wordpress plugin writing. Can anybody tell that where I have done the mistake?
Well one thing that obviously jumps out to me is this...
success:function(data){
$('#results').append(response);
}
Should be...
success:function(data){
$('#results').append(data);
}
Because you have no variable called response, you passed the function data as a variable, so you have to use that.
Also, you're passing search_string as a paremeter, when infact in your php file, the $_POST is looking for search_val.
So you need to send search_val as parameter and give your JavaScript search_val variable another variable name in the JavaScript, just for less confusion. In this case I made it search.
action:'wpay_search',
search_val:search
So overall it should look something like this...
$("#se").keypress(function(e){
e.preventDefault();
var search=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_val:search
},
success:function(data){
$('#results').append(data);
}
});
});
First let me say I'm new to Ajax. I've been reading articles from jquery.com and some tutorials but I didn't figured it out yet how this works on what I'm trying to achieve.
I am trying to get the weather for a searched city using Google's Weather API XML, without page refresh.
I managed to retrieve the Weather XML and parse the data but everytime I search for a different place, the page reloads since my weather widget is under a tab.
This is what I have in my HTML:
<script type="text/javascript">
$(document).ready(function(){
// FOR THE TAB
$('.tab_btn').live('click', function (e) {
$('.tab_content').fadeIn();
});
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
aysnc:false,
success:function(result){
$(".wedata").html(result);
}});
});
});
</script>
<style>.tab_content{display:none;}</style>
</head><body>
<input type="button" value="Show Content" class="tab_btn">
<div class="tab_content">
<h2>Weather</h2>
<form id="searchform" onKeyPress="return submitenter(this,event)" method="get"/>
<input type="search" placeholder="City" name="city">
<input type="hidden" placeholder="Language" name="lang">
<input type="submit" value="search" class="submit" style="width:100px">
</form>
<div id="weather" class="wedata">
</div>
</div>
And here is the actual demo I'm working on: http://downloadlive.org.
Now, if I add action="weather.php" on the search form I get the results, but I get redirected to weather.php which is logical. Without the action="weather.php", everytime I search my index which I'm on, adds up /?city=CITY+NAME which shouldn't. This should be added to weather.php, get the results and then retrieve them back into my index, if that makes sense?
This is my php code for weather.php: http://pastebin.com/aidXCeQg
which can be viewed here: http://downloadlive.org/weather.php
Can someone please help me out with this please?
Thanks alot
You just need to return false; from the click event handler. This will prevent the default action from occuring - in this case, submitting the form. Also, remove the async: false setting. You almost never want synchronous ajax requests.
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});
Alternately you can pass a parameter name to the callback and then use event.preventDefault() to accomplish the same result as above:
$(".submit").click(function(e){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
e.preventDefault();
});
You need to send the form data with the POST. It's super-easy to do this using .serialize().
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
data: $(this.form).serialize(),
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});