jQuery ajax post dynamic url insertion - php

$.ajax({ type: "POST", url: "OMFG.php", data: info, success: function(){ }});
is what I'm using atm as a test and it works fine.
I need to get the url from the link I'm clicking, so I do:
var url = $(this).attr("href");
which works fine if I alert it out(the link includes http://samedomain.com/etc.php), but the ajax function doesn't post if I insert it into the ajax code:
$.ajax({ type: "POST", url: url, data: info, success: function(){ }});
Please help, as I'm screwed without this working.

You are using the id attribute. For getting the link you need to fetch the href attribute:
var url = $(this).attr('href');
EDIT: See you just changed to href - if that still does not work try debugging by using
alert($(this).attr('href'));
and see if it alerts an url and if it is correct.
EDIT 2: Well, check in firebug in FF or Javascript Console in Chrome for errors or what url the script really is trying to post to. Depending on the rest of the code your url-variable might be out of scope if it is defined within some function or something.

Related

AJAX - PHP how to return a variable to the original AJAX script and alter an input value

I am protecting my forms with a captcha code to prevent using bots submitting loads and loads of forms.
This form works with AJAX and won't refresh the page like it usually does.
I have everything set now and it is working. but..
So this is the form im talking about to help understand.
When you click on request a new password, i need the code to change on the input field.
I do change the code after requesting a password like this in newpass.php
$_SESSION['capcode3'] = $capcode3;
This is my javascript code:
<script>
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
document.getElementById("captcha").value = "<?php echo $_SESSION['capcode3']; ?>";
});
</script>
So by using document.getElementById it would change the input value but, instead of setting the new value, it sets the old value.
So if the code is ABC123 and the new code is DEF456 it wont change to DEF456
Is there a better way to send the new code back to the input field?
Note: I have tested if $_SESSION['capcode3'] will change it's value with a positive result.
You did not specify a success handler in your ajax. Ajax is handled async, thus needs a callback to where the data will be passed when the request is succesfuly handled
$.ajax({
type: "POST",
url : "data/newpass.php/",
success: function(data) {
//change UI here
document.getElementById("captcha").value = data;
},
});
Please add code in success of ajax because may be session value will be changed on ajax success.
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data,
success :function(data){
document.getElementById("captcha").value = data;
}
});
Please try with this.

Calling a function in php with link in html

I'm trying to call a function with a link in html. I found the following example:
click to run function!
if(isset($_POST['runfunction'])){
}
This works perfectly fine, the problem is that when I click the link, "?runfunction" keeps standing in my url bar. So when I submit a form on my page it goes totally wrong (it's way to long to upload here). I do some SQL queries and I'm getting weird values in my SQL database. When I type in just my normal url it works fine. So I'm pretty sure that's the problem. I found another example with ajax :
$("a").click(function(){
jQuery.ajax({
url: "path/to/controller",
type: "POST",
dataType: 'json',
data: {'mentod':'ExportExcel'},
success: successCallback,
error:failureCallback
});
});
I don't fully understand this example (because I never use AJAX) but my php script is included in the html page "include("")". So I can't type in url because it has to be the same page. Can someone give a little bit of info about this, or give an example of how I can fix this? Thanks in advance!
You can add a callback method then remove it from the url by javascript
function successCallback () {
url = window.location.href;
window.location = url.replace("runfunction", "");
}

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

Send data with ajax but empty $_POST in php

I'm trying to save a data attribute of a div on click into a variable PHP. So I used $.ajax to send data with POST but it return an empty array.
However, the POST is visible in the console with good data.
AJAX
$('.get-thumbnail-id').click(function() {
var thumbnail_id = $(this).data('id');
$.ajax({
type: "POST",
url: "gallery.php/",
data: {thumbnail_id: thumbnail_id}
});
});
GALLERY.PHP
var_dump($_POST['thumbnail_id']);
I must have done something wrong but I really don't know what... any help is appreciated, thanks.
You should be doing
var_dump($_POST['thumbnail_id']);
Because the POST variable you are passing in the AJAX call has name thumbnail_id not just id
and check it with
$.ajax({
type: "POST",
url: "gallery.php/",
data: {thumbnail_id: thumbnail_id},
success : function(data){console.log(data);}
});
Check whether is prints anything in the console.

How to properly pass a jquery value to php using ajax?

I want to pass a value from my jquery code to a php variable after a user inputs through a textbox, but I don't receive any value at all in the PHP side through POST.I'm using .change and .post, does anyone here knows how to do it properly?
here's my code:
$(document).ready(function(){
$("#packagename").change(function(){
var packagename = $('#packagename').val();
var url = '{{url}}'; //localhost/test/test.php
$.ajax({
type: 'post',
url: url,
dataType:html,
data:{'val':packagename},
});
});
});
try it
$(document).ready(function(){
$("#packagename").change(function(){
var packagename = $('#packagename').val();
var url = '{{url}}'; //localhost/test/test.php
$.ajax({
type: 'post',
url: url,
dataType:text,
data:{'val':packagename},
success:function(result){
alert(result);
}
});
});
});
The only problem that I can see offhand is that the html in dataType:html, needs to have quotes around it like this: dataType: 'html',. Otherwise your code will look for the variable html, not find it, and throw an error.
http://api.jquery.com/jQuery.post/
dataType
Type: String
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
change dataType: html, to dataType: 'html',
Have you tried just putting the url into the url field instead of whatever that object is you are trying to use?
I will assume you are not trying to ajax to the page you are currently on and expecting the php variable to display on the current page.

Categories