Ajax not sending data at all - php

im working on a script that sends a few data stored using GET to a PHP script(process it then put it into database).
here's the ajax script , im using jQuery ajax
(i have included the latest jQuery script)
function send(){
$.ajax({
type: "GET",
url: "http://examplewebsite.com/vars/parse.php",
data: "id=" + id + "&purl=" + purl + "&send" + "true",
cache: false,
success: function(){
alert("Sent");
}
});
}
id and purl are JavaScript variables .
send() function is set in :
Send
PHP code:
<?php
//Connect to database
include ("config.php");
//Get the values
$id = $_GET['id'];
$purl = $_GET['purl'];
$send = $_GET['send'];
if ($send == 'true') {
$insertdata = "INSERT INTO data (id,purl,send) VALUES ('$id','$purl',+1)";
mysql_query($insertdata) or die(mysql_error());
} else {
//do nothing
}
?>
when i type http://examplewebsite.com/vars/parse.php?id=123&purl=example&send=true
it works, the php injects the data into the database as i wanted but when i use send() and wanted to use ajax to send the data, failed.
Is there any mistakes that im making?

You're missing the = after send,
function send(){
$.ajax({
type: "GET",
url: "http://examplewebsite.com/vars/parse.php",
data: "id=" + id + "&purl=" + purl + "&send=" + "true",
cache: false,
success: function(){
alert("Sent");
}
});
}
should fix it, also. post more information about your javascript. We just have to assume id and purl are filled out. Did you try debugging them (if this doesn't work).
Also, debug the URL that is requested, you can use firefox or chrome dev-tools for this. What url is being send to the PHP page and is it correct

missing "=" in the data string.
data: "id=" + id + "&purl=" + purl + "&send" + "true",
should be
data: "id=" + id + "&purl=" + purl + "&send=" + "true",

It depends where you are running your script, because ajax calls are not meant to work on other domains. If you need to run the js on http://example1.com and the call to go to http://example2.com you need another approach.
An idea is to use json

Try
data: { id: id, purl: purl, send: true }
See if that makes any difference

First, i suggest (if you use Chrome or Safari) to use the Web Inspector (Right Click anywhere - inspect element) and then press ESC to show to console, this will assist you in validating your JS code. That would show you you have a '=' missing.
Second, i would try something a bit more simple just to make sure you get to the file.
JS:
// Don't forget encoding the data before sending, this is just a simple example
$.get("parse.php?sent=true",
function(data){
alert("I think i got a nibble...");
alert(data);
}
);
On the php file :
$sent = (isset($_GET['sent']) && !empty($_GET['sent']))?$sent:false;
if($sent) echo 'whatever data you want back';
Just make sure that you actually get the alert, and if so , move on from there to build the PHP file as needed for your data.
Hope this assists,
Shai.

Related

php lost some path of string after submition using ajax post

I am trying to submit a comment using ajax post with php, it's working very fine as i expected it to but when i try to submit some sting that contain & it lossess path of the sting only show from beginging till where the and is.
I really don't know how to fix this, i have no idea about what is the problem please i need help.
See example
MY ajax
<script>
$('#submitcomment').on('click', function(){
try{
var message = $('.commentTextinput').val();
var key= $(this).attr('data-keyname');
$.ajax({
url: UrlExistsA('snippet/snippetcomment'),
data: 'message=' + message + '&key=' + key,
type: 'POST',
beforeSend: function(){
$('#submitcomment').html('Wait....');
},
success: function(data){
$('tr.replyList:last-child').after(data);
$('.commentTextinput').val('');
$('#submitcomment').html('Comment');
},
error: function(data){
alert('Processing Error' + '<br/>' + data);
}
});
}catch(err){alert(err.message);}
finally{}
});
</script>
Here is test php
<?php
if(isset($_POST['message'])){
$postReply = htmlentities($_POST['message'], ENT_QUOTES, "UTF-8");
echo $postReply;
}
The above will output this
tomorrow we will run faster, stretch out our arms farther... And then
one fine morning
But the original string posted was
tomorrow we will run faster, stretch out our arms farther... And then
one fine morning— So we beat on, boats against the current,
borne back ceaselessly into the past.
also when i tried to submit &&&&&&&&&&&&&&&&&&&&&&& it return empty But when i echo the above string without using ajax it was very okay
You need to call encodeURIComponent to encode special characters in the parameter string. & is the separator between parameters, so you need to encode it.
data: 'message=' + encodeURIComponent(message) + '&key=' + encodeURIComponent(key),
But a simpler way is to use an object instead of a string, then jQuery will encode it automatically.
data: { message: message, key: key },

Cant POSTing value of CKEDITOR and Lose the Format of CKEDITOR [PHP with JQUERY AJAX ]

I had ckeditor's values, when those content contained special characters, in my case it happened when a was inside the content of the editor. It "killed" the url since ?data=blabla is a malformed url..
var this = "conten=" + CKEDITOR.instances.tIsi.getData();
$.ajax({
url: "action/prosesPOST.php",
type: "POST",
data: this,
cache: false,
success: function(msg) {
alert(datanya);
if (msg == "yes") {} else {
alert("Failde to Update data," + msg);
}
}
});​
and i change it be
var this ={
conten: CKEDITOR.instances.tIsi.getData();
}
and viola i can update and posting that but all format of ckeditor lose when showed it on ckeditor on showing on table.
=================================== SOLVED ====================================
the problems is when i am posting it like this :
var this = "conten=" + CKEDITOR.instances.tIsi.getData();
ckeditor value unshowed,i know it because use alert(this); before ajax sending and value is null
when i am using :
var this = {conten: CKEDITOR.instances.tIsi.getData()}
data not null and inserted to database but my format style lose like "margin","align",etc make it like string,ex : BOLD be => < b >BOLD < / b >
and i solved this with simple trick make it be *html_entity_decode($value_on_database)* changing the object data to normal when i want showing it on ckeditor or the other.
CHEERS :))
Not sure how if I understood your question correctly. Is the issue with POSTing data or is the data malformed somehow? Meaning is it not as you expected on the server?
Does the following work (Edited to be more complete)?
$.ajax({
url: "action/prosesPOST.php",
type: "POST",
data: {conten: CKEDITOR.instances.tIsi.getData();}
cache: false,
success: function(msg) {
alert(datanya);
if (msg == "yes") {} else {
alert("Failde to Update data," + msg);
}
}
});​
Is the data posted correctly? If you debug the data in PHP, is it as you expected? How do you output the data if it looks OK before using it?
I would also use another variable name rather than "this" as it already has an expected meaning in JavaScript.

jQuery posts error text when posting with ajax

When I'm posting via ajax I'm sometimes getting extra characters posted for example. If the text passed though ajax yo a php $_POST I end up getting:
This is my messagejQuery127638276487364873268_374632874687326487
99% of the time posts pass though fine... I'm unsure how to capture and remove this error as it only happens some of the time.
// this is the ajax that we need to post the footprint to the wall.
$('#submitbutton').click(function () {
var footPrint = $('#footPrint').val();
var goUserId = '1';
$.ajax({
type: 'POST',
url: '/scripts/ajax-ProfileObjects.php',
data: 'do=leave_footprint&footPrint=' + footPrint + '&ref=' + goUserId + '&json=1',
dataType: 'json',
success: function(data){
var textError = data.error;
var textAction = data.action;
var textList = data.list;
if (textError == 'post_twice' || textError =='footprint_empty' || textError == 'login_req') {
// display the error.
} else {
// lets fade out the item and update the page.
}
});
return false; });
Try set cache to false. From http://api.jquery.com/jQuery.ajax/
cache Boolean
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.
I found out through a process of elimination that the error was being caused by invalid data being passed to the query string.
The line:
data: 'do=leave_footprint&footPrint=' + footPrint + '&ref=' + goUserId + '&json=1',
I noticed that the footPrint variable would always break the script if '??' was passed. A number of members when asking a question would use a '??' when and not a single '?'
By wrapping the footPrint var in encodeURIComponent() I can send all the text though to the PHP script without breaking the URL string.
New Line:
data: 'do=leave_footprint&footPrint=' + encodeURIComponent(footPrint) + '&ref=' + goUserId + '&json=1',
This solution has worked for me... questions comments and suggestions still welcome.

ajax and javascript issue - functions not firing or firing mutiple times

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.

ajax POST not working, can't figure why

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.

Categories