First ajax call doesn't work - php

I'm trying ajax for the first time but it doesn't work.
This is "some.php" which handles the ajax call:
<?php
echo "success";
?>
And this is the javascript that calls it:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript">
var msg;
$.ajax({
type: "POST",
url: "some.php",
data: ({ })
success: function(msg){
alert( msg );
}
});
</script>
Can you see where the problem is?
I should state I'm working under wordpress and both files reside in \wp-content\themes\twentyten (maybe the url in the ajax call is wrong?)

First of all remove the data:({}) which is pointless. you are also missing a , behind your data statement. this is most likely the issue.
if both the files is in the same directory, then the url should be correct.
However, i urge you to use a tool like FireBug in order to debug your problem further

You should run your script when the page has loaded (more precisely, when the DOM is ready). jQuery offers an event for that.
Your code could then look something like this:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "some.php",
data: ({ })
success: function(msg){
alert( msg );
}
}
});

Two things to do:
register a .fail callback. The code as it is will just call the alert() if it succeeds, otherwise, errors are not raised. See http://api.jquery.com/jQuery.ajax.
check the web server log to see if some.php is exec'd and if so, what errors may be occurring on the server.

Related

POST PHP error via Ajax on unsuccessful login

I'm trying to get a Bootstrap Alert to be shown when a user could not be logged in.
To do this, I am using Ajax (jQuery) and POSTing the error upon redirect, to the script on my index.php
Here is the PHP on login.php:
$message = "Your Email or Password combination were incorrect. Please try again.";
echo json_encode($message);
header('Location: /');
and my jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: "message",
success: function (response) {
var message = jQuery.parseJSON(message);
$('#alert').text(message);
}
})
});
</script>
What I'm trying to achieve is:
User tries to log in (and fails)
Redirected to home page (as my login form is in the header)
Error alert is shown, with the $message content as the error text.
When I make an incorrect login (to trigger the error) I get
JSON.parse: unexpected character at line 1 column 1 of the JSON data
I'm still a beginner with jQuery, and have tried to follow other examples which is why my code probably doesn't make sense (and why it isn't working).
I'm using firebug on Firefox to debug the jQuery.
Thanks for your time
I believe your error lies in a misunderstanding of what the line: $(this).attr('action') is doing in your $.ajax call.
When I run your code the function works perfectly... except that it loads the current page! Which is exactly what you told it to do. Sending $(this).attr('action') in the url: parameter just told your ajax function to load the current page. As the current page has javascript and presumably HTML defined in it the response is not valid JSON.
What you want to do is change:
url: $(this).attr('action'),
To:
url: 'path/to/login.php',
i change type and remove comma
make a json request and chage success to done
try this
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
method: "POST",
url: $(this).attr('action'),
data: "message",
dataType: "json"}).done(function () {
var message = jQuery.parseJSON(message);
$('#alert').text(message);
})
}

AJAX not sending user-input from a form to PHP script

I've been trying to learn basic AJAX and Javascript by following various tutorials and examples online, but I've hit a wall. I'm trying to write a simple script to take user-input from a form using AJAX and submit it to a PHP script, which then just echos the input.
All I can really tell is that whatever is being entered is not going through, but I'm not at the point yet where I can say why. I've tried with both POST and GET, and with various dataTypes, with the same result. I'm certain that I'm doing something wrong or misunderstanding something, but I'm not sure what.
HTML/ AJAX
<form id="my_form">
word <input type ="text" id="word1"/><br/>
<input type="submit">
</form>
<script>
$(document).ready(function(){
$("#my_form").on(function(e){
e.preventDefault();
var verb = $("word1").val();
$.ajax({
url: "testrun.php",
data: "verb",
type: "POST",
});
});
});
</script>
PHP
if (isset($_POST['verb'])){
$x= $_POST['verb'];
echo $x;
}else {
echo "not working";
}
EDIT: I've tried a few of the suggestions thus far, copying and pasting them directly, and none of them have actually done anything that I can see. I think I'm starting to understand a bit more about how AJAX should work, based on the responses, but it's still not reaching the PHP for some reason. I've tried both with the AJAX/HTML in a separate file that calls to the testrun.php script and with putting everything into the testrun.php file and basically having it call itself with the AJAX, but neither approach has achieved anything.
If the AJAX that I've gotten from the responses is fine, then am I misunderstanding something in how the PHP should be set up in order to actually receive the POST data? I'm still rather lost.
Three changes:-
1.var verb = $ ("word1").val(); need to be var verb = $ ("#word1").val();because its id (word1)
2.data: "verb", needs to be data: {"verb":verb},
3.form submission need to be correct so code given below (missing submit):-
Correct code:-
$(document).ready(function(){
$("#my_form").on('submit',function(e){ // check here you have one missing `submit`
e.preventDefault();
var verb = $("#word1").val(); // remove space between `$` and `(`
$.ajax({
url: "testrun.php",
data: {"verb":verb},
type: "POST",
});
});
});
You can not send data as data: "verb", in ajax. you need to send your data in params.
Second, you can not get the value of word1 input as $("word1").val(); you need to use # for get input by IDs.
Example:
$(document).ready(function(){
$( "#my_form" ).submit(function( e ) { //CHANGED using submit event.
e.preventDefault();
var verb = $("#word1").val(); //CHANGED
$.ajax({
url: "testrun.php",
data: "verb="+verb, //CHANGED
type: "POST",
});
});
});
You forgot # foe id selector of word1.
.on() needs event to bind to. In your case of form submit, it's submit
Data should be passed as object. In your case, you will be able to access it with $_POST['verb']
$(document).ready(function ()
{
$("#my_form").on('submit', function (e)
{
e.preventDefault();
var verb = $("#word1").val();
$.ajax({
url: "testrun.php",
data: {verb: verb},
type: "POST"
});
});
});
you miss to give the # sign in var verb = $("word1").val();
and use a variable just as a variable to the data like data: {"your_var_name" : verb}
Try this ...
$.ajax({
type: "POST",
url: "testrun.php",
data: "paramname=value", // access in php $_POST['paramname']
success: function(data){
// if page request is success
},
error: function(data){
// if page request failes
}
});
You have to do this:
var verb = $("#word1").val(); //Don't forget to add #
$.ajax({
url: "testrun.php",
data: {"verb":verb},
type: "POST",
});
verb is a variable, no need to put in between quotation!
The correct answer is
HERE by Anant

Trying to call PHP file using jQuery Ajax

I am developing using jQuery 2.0.2 on Debian 7.0.0.
I am trying to call a PHP script from a JavaScript file using jQuery.ajax. My code is as follows.
jQuery.ajax({
type: "POST",
url: "DisplayParameters.php",
data: { LUT:lut,
Brightness: brightness,
Gamma: gamma,
Background: background}
}).done(function( result ) {
$("#msg").html( " Ajax called" );
});
At the beginning of DisplayParameters.php, I have the following.
?>
<script language="JavaScript">
alert('DisplayParameters');
</script>
<?php
but the alert box is not called. Firebug proceeds without any errors and shows the DisplayParameters.php text (with a +/- control to collapse and expand it). But the alert box is not called. I cannot get any feedback from DisplayParameters.php to trace what is happening.
What would be the best way for me to get feedback (like alert boxes or console.log) from DisplayParameters.php?
Your ajax call returns the contents of DisplayParameters.php as text, console.log(result) would show:
<script language="JavaScript">
alert('DisplayParameters');
</script>
If you want to add this extra code to the page (which I don't recommend unless you are sure you won't break the current page), you can try:
jQuery.ajax({
type: "POST",
url: "DisplayParameters.php",
data: { LUT:lut,
Brightness: brightness,
Gamma: gamma,
Background: background}
}).done(function( result ){
$("#msg").html( " Ajax called" );
$("body").append(result);
});
Another approach would be to serialize (JSON) the information you need, set the dataType: "json" option, and act based on this information.
If you will send HTML, ensure your PHP code doesn't shows any error or warning messages.
The alert() should happen inside .done() on the ajax call. Like the following:
.done(function(result) {
alert(result);
$("#msg").html( " Ajax called" );
});
And instead of alerting on DisplayParameters.php, use echo so that that will be the returned value for result. Like the following:
<script language="JavaScript">
//...some JS codes here
<?php echo 'DisplayParameters'; ?>
</script>

File path for AJAX script (in Wordpress)

I use this jquery-ajax script to send email:
$.ajax({
url: process.php,
type: "POST",
data: data,
cache: false,
...
in url I call the php file that sends email, but ajax get it only if I specify the full path:
url: "http://www.domain.com/wp-content/themes/site_theme/templates/process.php",
but I have to use a syntax like this:
url: "../../templates/process.php",
or using a variable to declare in the html header/footer
Html
<script type="text/javascript">
var urlMail = '<?php bloginfo('template_url'); ?>/templates/process.php';
</script>
Script
url: "../../templates/process.php",
but with both the above cases the browser console retrieves this error:
POST http://www.domain.com/templates/process.php 404 Not Found 1.56s
Where am I wrong?
That's not the way to implement ajax in wordpress. All ajax request should be made to admin-ajax.php.
In your template file:
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
In your js:
$.ajax({
url: ajaxurl,
type: "POST",
cache: false,
data: data + '&action=sendmail' //action defines which function to use in add_action
});
in your functions.php:
function send_my_mail(){
#do your stuff
}
add_action('wp_ajax_sendmail', 'send_my_mail');
add_action('wp_ajax_nopriv_sendmail', 'send_my_mail');
Read about Ajax in Plugins.
I would be recommended to you use system like Registry for save all "global" values in a one place.
Registry design pattern
There is my small jQuery plugin if this is may be interesting to you. GitHub rep
<script type="text/javascript">
$.Registry.set('urlMail', '<?php get_bloginfo('template_url'); ?>/templates/process.php';
</script>
And to get value from the Registry you must use $.Registry.get('urlMail');
I've solved using the code provided by RRikesh but replacing
data: data
with
data: data + '&action=sendmail'

ajax jquery call doesnt work for me

UPDATE:
I need to get the jason.. The click event doesnt work why..
update:
<script>
$(document).ready(function(){
$("#RefreshButton").click(function(){
$.ajax({
url: "/test2/ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
alert("This is my data: "+data);
$(".article").remove();
$.each(data, function(key, value){
$('articleColumn').append( '<p class="article"><font size="5"><b>'+value[0]+'</b></font><br/>'
+value[1]+' Read more...</p>');
});
},
error: function( error )
{
alert(JSON.stringify(error));
}
});
});
});
</script>
The ajax call works..but not when it is in the click event handler..why?!?
I think the solution to the problem lies in the html:
<a href="" id="RefreshButton" >Refresh</a>
may be it refreshes the page and then send the response. I think it is the problem in the way the event propogates ..hmm
Generally when making an ajax call using jQuery I use the short hand version of POST and GET methods. So in your case I would do something like this
$.get("ajax.php", function(data){
alert(data); //just to make sure it works
}, "json");
Be sure to send the response back from ajax.php as json using json_encode(array("key"=>"value","key"=>"value")); ?>)
Also since ajax cannot go across domains you don't have to specify http://localhost/ajax.php, rather you can just specify it as the relative path to where you are calling the jquery function from.

Categories