Used this script many times to pass 1 or 2 values to a PHP file, works fantastic. Using it now to pass 7 values and only the first 2 get through.
$(document).ready(function(){
$("form#send_note").submit(function() {
var to_user = $('#to_user').attr('value');
var from_user = $('#from_user').attr('value');
var defaultpic_from = $('#defaultpic_from').attr('value');
var defaultpic_to = $('#defaultpic_to').attr('value');
var your_username = $('#your_username').attr('value');
var message_title = $('#message_title').attr('value');
var message_contents = $('#message_contents').attr('value');
$.ajax({
type: "POST",
url: "../inbox/send_note.php",
data: "to_user="+ to_user +"& from_user="+ from_user + "& defaultpic_from="+ defaultpic_from + "& defaultpic_to="+ defaultpic_to + "& your_username="+ your_username + "& message_title="+ message_title + "& message_contents=" + message_contents,
success: function(){
$('form#send_note').hide(function(){$('div.success2').fadeIn();});
}
});
return false;
});
});
I have double checked all of the names, all is in order it's just the values after from_user (defaultpic_from) and so on won't go through.
I believe it's the way I have the "data:" listed. I am a complete newbie when it comes to javascript so any advice on the properway to get these through would be fantastic!
1) you know with jquery you can just do this, right?
var defaultpic_from = $('#defaultpic_from').val();
2) also, you don't need to turn the & into an entity, but as mentioned, you should be using encodeURIComponent in the values
3) have you verified all the variables actually have values before the ajax request gets made? what happens when you look in POST? Are you getting the members in POST, but no values? or no keys and no values?
4) Try using Chrome's Network tab in the developers tools to examine the request and response
here is an example I am using now, where params is nvp string and sync is true
var callService = function(sync, params, successCB, errorCB){
console.log('ENTER callService');
$.ajax({
type : 'POST',
url : 'required/core/Service.php',
async : sync,
data : params,
dataType : 'json',
success : function(data){
console.log('ENTER POST SUCCESS');
successCB(data);
},
error : function(){
console.log('ENTER POST ERROR');
errorCB();
}
});
};
what would be really helpful if you could go into the request and response headers and show them to us. you could have PHP echo
echo json_encode($_POST);
to make it easier to get the response
I bet the value of your default pic is terminating the query string. You can wrap your vars like this to ensure they are properly escaped:
$(document).ready(function(){
$("form#send_note").submit(function() {
var to_user = encodeURIComponent($('#to_user').attr('value'));
var from_user = encodeURIComponent($('#from_user').attr('value'));
var defaultpic_from = encodeURIComponent($('#defaultpic_from').attr('value'));
var defaultpic_to = encodeURIComponent($('#defaultpic_to').attr('value'));
var your_username = encodeURIComponent($('#your_username').attr('value'));
var message_title = encodeURIComponent($('#message_title').attr('value'));
var message_contents = encodeURIComponent($('#message_contents').attr('value'));
$.ajax({
type: "POST",
url: "../inbox/send_note.php",
data: {to_user:to_user, from_user:from_user, defaultpic_from: defaultpic_from, defaultpic_to:defaultpic_to, your_username:your_username, message_title:message_title, message_contents:message_contents},
success: function(){
$('form#send_note').hide(function(){$('div.success2').fadeIn();});
}
});
return false;
});
});
You will need to urldecode the post vars in php but that should do it.
Related
I'm trying to get an Ajax call working in JQuery, PHP and MySQL.
I have two variables I need to send: $speaker_id and $article_id.
I'm constructing my jQuery like so:
$('.ajax-call').click(function() {
var speakerID = <?=$speaker_id?>;
var articleID = $(this).attr('id');
var ajaxData = 'speaker_id=' + speakerID + ', article_id=' + articleID;
$.ajax({
type: 'POST',
url: 'update-read-article.php',
data: ajaxData,
dataType: 'text'
});
});
However, checking Chrome's Developer Tools "Network" tab once the call has been made, I see that update-read-article.php's received Form Data looks like so:
speaker_id: 16551, article_id
and not the expected:
speaker_id: 16551
article_id: 29
How can I construct my ajaxData so that my script can find both $_POST['speaker_id'] and $_POST['article_id?
Querystring values must be separated by an ampersand (&) not a comma (no space after the &):
var ajaxData = 'speaker_id=' + speakerID + '&article_id=' + articleID;
You must separate each parameter with "&". Comma's or other characters won't work, so remove them.
Your query string should look like:
var ajaxData = 'speaker_id=' + speakerID + '&article_id=' + articleID;
Your ajaxData may be defined the same way as query string but with request type POST this will be translated into post parameters.
Like so:
$('.ajax-call').click(function() {
$.ajax({
type: 'POST',
url: 'update-read-article.php',
data: 'speaker_id=<?=$speaker_id?>&article_id=' + $(this).attr('id'),
dataType: 'text'
});
});
Mind the ampersand (&) delimiting the parameters - same way as in query string (GET).
Or you may define that data as object:
$('.ajax-call').click(function() {
$.ajax({
type: 'POST',
url: 'update-read-article.php',
data: {
'speaker_id': <?=$speaker_id?>,
'article_id': $(this).attr('id')
},
dataType: 'text'
});
});
Use jQuery $.param({speaker_id: yourval, article_id: yourval}). You won't get confused with building the string manually.
Have you tried outputting ajaxData to console?
I have a table with dynamic data from database, each row consist of a text filed and 2 link (accept or reject). then if user clicks on any of these link, the row will disappear and the rest of the rows are only visible in table.
I get ID of each row with ajax by clicking on each link, however I also need to get the text-field value.
how can I get it?
I need to have in ajax cause after getting value I need to insert in database with php+sql.
this is my ajax part for link:
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'Test.php',
data: 'ajax=1&accept=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
how can I include text filed value in it?
please comment me which I'm really in need to solve it,
Thanks
You can add manually your text to the GET request.
(snippet)
data: 'ajax=1&accept=' + parent.attr('id').replace('record-','') + '&text=VALUE',
Substitute text with the name you want to be received in PHP. Substitute VALUE with the text entered on the page that you want to grab - and don't forget to encode the value.
You will need the name of id of the textfield first. Then you could do something like this:
var textboxvalue = $('name or id of textfield').val();
Then you will need to append this value to your data string:
data: 'ajax=1&textvalue='+textboxvalue+'accept=' + parent.attr('id').replace('record-',''),
Then you can use $_GET['textvalue']; to get the value of textbox.
Use following and you're good to go. Also you had extra '});' at the end line of JS fragment. I had it removed. But make sure you give id to text fields in following pattern : text-fld-RECORD_ID where RECORD_ID is the ID of the record.
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
var id = parent.attr('id').replace('record-','');
//make sure that text field has ID in pattern 'text-fld-RECORD_ID'
var text_fld = $('#text-fld-'+id).val();
$.ajax({
type: 'post', // I suggest using post; get will be harmful in such occasions
url: 'Test.php',
data: {ajax:1,accept:id,text:text_fld},
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
I have put together an ajax powered chat/social network with jquery, PHP - but am having problems with the javascript.
I have a js file in the main page which loads the php in a div container, the js file is underneath the div. But only one function for posting a msg seems to work but the others do not.
I have tried including the js file with the dynamically loaded php at the end of the ajax load the functions work fine but am getting mutiple entries of the same message/comment.
I am pretty sure its not the PHP as it seems to work fine with no ajax involvment. Is there a way to solve this?
this is the function that works fine:
$("#newmsgsend").click(function(){
var username = $("#loggedin").html();
var userid = $("#loggedin").attr("uid");
var message = $("#newmsgcontent").val();
if(message == "" || message == "Enter Message..."){
return false;
}
var datastring = 'username=' + username + '&message=' + message + '&uid=' + userid;
//alert(datastring);
$.ajax({
type: "POST",
url: "uploadmsgimage.php",
data: datastring,
success: function(data){
document.newmessage.newmsgcontent.value="";
//need to clear browse value too
$('.msgimage').hide('slow');
$('#addmsgimage').show('slow');
$(".usermsg").html(data);
$("#control").replaceWith('<input type="file" name="file"/>');
$(".msgimage").remove();
}
});
});
And this is one of them that does not work:
//like btn
$(".like").click(function(){
var postid = $(this).attr("pid");
var datastring = 'likeid=' + postid;
$.ajax({
type: "POST",
url: "addlike.php",
data: datastring,
success: function(data){
$(".usermsg").html(data);
}
});
});
From your post, I'm guessing that each message has a "Like" button, but you have 1 main submit button. When messages load dynamically, you have to assign the .like to each one when they come in, otherwise it will only be assigned to the existing messages.
The problem, from what I gather (and this is a guess) would probably be fixed using live so jQuery will automatically assign the click function to all messages including dynamically loaded messages; so instead of:
$(".like").click(function(){
Try this:
$(".like").live('click', function(){
If that doesn't solve the problem, then I'm probably not understanding what it is.
Disclaimer
I have searched for duplicates, but I can't seem to find them. I am surprised because this seems to be a big issue. I most likely am missing something big though.
Problem/Question
I am having the userid passed into through the url via php, myOtherScript.php?userid=1. How can I get that variable to be passed via ajax so that I may query the database with that userid, echo it out and return it to the page?
This is in global.js file
jQuery
$.ajax({
url: "myScript.php",
data: "userid=" - This is what I need: $_GET['userid'] - ,
success: function( data ) {
$('#myDiv').html( data );
}
});
Solution
WIth the help of bstakes and this answer, I was able to figure it out with this function: (top answer)
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Thanks for the answers guys!
$.ajax({
url: "myScript.php",
data: "userid=<?php echo intval($_GET['userid']); ?>",
success: function( data ) {
$('#myDiv').html( data );
}
});
You could also try using the search attribute of the window.location object.
If the url is http://www.mysite.com/display.php?userid=7 window.location.search will return "?userid=7". You will obviously need to remove the leading "?", but be aware that if there are additional GET paramaters, separated with ampersand '&', those will be included as well.
So, with a bit of additional Javascript, you can split on the '&', which gets you an array of "key=val", then you can spilt on the equal sign and create an object with {key : val}. Then you could use that object to access the query string params.
var qs = window.location.search.substring(1),
pieces = qs.split('&'),
i,
qsObj {},
tmp;
for ( var i in pieces ) {
tmp = pieces[i].split('=');
qsObj[tmp[0]] = tmp[1];
}
See https://developer.mozilla.org/En/Window.location for additional information on the window.location.
If you want to keep the JS seperate, put it in a function that accepts the user id...
function do_something(user_id) {
$.ajax({
url: "myScript.php",
data: "userid=" + user_id,
success: function( data ) {
$('#myDiv').html( data );
}
});
}
Then just call do_something($_GET['user_id']);
You might have to move the script inline on the PHP file then you echo out the $_GET['userid'] in the data area of your ajax call.
just found this: how to get GET and POST variables with JQuery?
I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.