JQuery Ajax error - php

I am posting some form values through ajax to a PHP script. The PHP echoes 1 if it's successful and 2 if not.
The PHP seems to be working ok but I am being redirected to the url in the javascript and shown the number 1 on a blank page instead of it being echoed back to the ajax request.
This is my javascript, can anyone see where I am going wrong?
$(".save").click(function() {
var area = $("input#area").val();
var january = $("input#january").val();
var target = $("input#target").val();
var ach = $("input#achieved").val();
var comments = $("input#comments").val();
var token = "<?php echo $token; ?>";
var dataString = 'area='+ area + '&january=' + january + '&target=' + target + '&achieved=' + ach + '&comments=' + comments + '&ci_token=' + token;
$.ajax({
type: "POST",
url: "review/update-review/<?php echo $yr; ?>",
data: dataString,
success: function(msg) {
if(msg == 1)
{
alert("Your review has been updated.");
}
else
{
alert("There was a problem updating your review. Please try again.");
}
}
});
return false; });

I think the problem may be down to the format of your data parameters. for
type : "POST"
then for
data : "{param1: 'param1', param2: 'param2'}"
do you have a tool like fiddler to view the communications between your browser and server. if not i would recommend downloading fiddler (it's free). it will give you a lot of insight as to what is actually happening behind the scenes and can give invaluable information about what might have gone wrong with an ajax style post.

The code looks pretty much fine to me, including the syntax. Still some possibilities arise, which are:-
The URL for executing the PHP code, which you are using in the example ("review/update-review/<?php echo $yr; ?>"), may be incorrectly given with reference to your current page.
The variables which you are using it here to capture the values of the INPUT elements, may be producing some extra special characters (like "&") which may lead to erroneous processing, resulting in the JavaScript problem.
Hope it helps.

For starters if(msg == 1) will not be == 1 because what your fetching is a string so it would b if(msg == '1').
Where you have
var dataString = 'area='+ area + '&january=' + january + '&target=' + target + '&achieved=' + ach + '&comments=' + comments + '&ci_token=' + token;
Change that to an object like so:
var dataObject = {
area : area,
january : january,
target : target,
achieved : ach,
comments : comments,
ci_token : token
}
and then change it in the ajax request to dataObject
Debug
Firefox: firbug.
if your using chrome hit Ctrl+Shift+J to open the javascript console and debug. look out for all the heaDers and data your sending and you can use console.log(varaible) to track the values of a variable.

Related

jQuery AJAX can't work when injected on external URL?

I am currently trying to retrieve some data from book search sites and populate a personal database with that data. My idea is to inject the necessary jQuery on the page, so that when I see a title I think I'd like to return to in future, I can then just click a cheeckbox, make necessary additional comments, which I then hope to submit by AJAX to a PHP script which then populates my MySQL database for me with the appropriate title.
Do look at this example for a library catalogue:
// for every book entry, append checkboxes
$('.document-frame').append('<p>Choose:?<input type="checkbox" class="Jcustom_c" /></p><p>Serendepity?:<input type="checkbox" class="Jserep" /></p><p>Include snippet?:<input type="checkbox" class="Jsnippet" /></p>');
// append a Submit button at the bottom of the page, and a blank div for feedback upon success in POST-ing the necessary data
$('#resultPage').append('<input id="Justin" class="Jcustom" type="submit"/><div id="Jfeedback"></div>');
// whenever my checkbox is checked, retrieve / "scrape" the necessary book data
$('.Jcustom_c').change(function() {
if ($(this).is(':checked'))
{
var title = $(this).parent().parent().find('.title a').text();
var author = $(this).parent().parent().find('.authors a').text();
var publishd = $(this).parent().parent().find('.publisher').text();
var status = $(this).parent().parent().find('.metadata .summary').text();
var img_link = $(this).parent().parent().find('img.artwork').attr("src")
// create an XML string from that data. Escape "<" and ">", otherwise when we append the string to the browser for feedback, the browser will not render them correctly.
var appended = '<div class="Jappended"><item><title>' + title + '</title><author>' + author + '</author><publisher_n_edn>' + publishd + '</publisher_n_edn><status>' + status + '</status><image>' + img_link + '</image><serep>N</serep></item></div>';
// show the string just below the book title. Hence if I "pick" the book from the catalogue, the XML string will show up to confirm my the fact that I "picked" it.
$(this).parent().parent().append(appended);
}
// if I uncheck the box, I remove the XML string
else {
$(this).parent().nextAll(".Jappended").remove(appended);
$(this).parent().prevAll(".Jappended").remove(appended);
}
});
And then I have the AJAX:
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
$(".Jappended").each(function() {
var placeh = $(this).text();
string = string + placeh;
$('.results_container').append(string);
})
// these come from <textarea> boxes I append to the end of the page just before the Submit button. (Above, I did not include the jQuery to append these boxes.)
var odp = $("#odp").val()
var mre = $("#motivation_revisit").val()
var mra = $("#motivation_rationale").val()
var stu = $(".hdr_block h5 span").text()
var string = string + "<odpath>" + odp + "</odpath><stused>" + stu + "</stused><motivation><revisit>" + mre + "</revisit><rationale>" + mra + "</rationale></motivation></itemset>"
var post_var = { xml_string : string, source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
$('#Jfeedback').html(data);
});
My problem is that I can't seem to get the AJAX to work: When I click on my Submit button, I do not see the output I would expect when I used the exact same jQuery on an HTML file I called from localhost. This, which I called using http://localhost:8888/some_html.html worked:
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
$(document).ready( function() {
...
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
/*
$(".Jappended").each(function() {
var post_var = { xml_string : "hello", source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
// if (data == "Success") {
$('#Jfeedback').html(data);
// }
});
});
});
</script>
<body>
...
</body>
</html>
db-ajax.php is simply:
echo "Success";
I have read this post: jQuery cannot retrieve data from localhost, which mentions something about "JavaScript cannot currently make direct requests cross-domain due to the Same-origin Policy". Is this the reason why my code didn't work on the external page? If yes, what can I do to make the code work, or what other approaches can I adopt to achieve the same goal? I have mutliple book search sites that I am working on, and many of these do not have an API where I can extract data directly from.
Thank you in advance.
P.S.: I've also tried the suggestion by CG_DEV on How to use type: "POST" in jsonp ajax call, which says that $.post can be done with jsonp, which is the data type to use for cross-domain AJAX. Result: On Firebug I do see the POST request being made. But my function callback is not fired, and firebug doesn't register a Response body when at least "Success" should be returned.
you can set allow cross origin resource sharing
Follow two steps:
From server set this on response header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:*
//* if you want to allow it for all origin domain , or you can specify origin domains also to which you want to allow cors.
In client side add this on your page
$.support.cors = true;
Cons: It is not fully supported on ie < ie10.

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 not sending data at all

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.

jQuery not generating correct queryString

I have been working on a website that uses a combination of PHP, jQuery, MySQL and XHTML in order to register students for a piano recital. This has no official purpose other than a learning exercise for me in getting all of these to work together. However, I have had a lot of problems getting the PHP to talk with the database and I'm not sure what my problem is. But before that can be tackled there is a really annoying issue that I've run across. For some reason my jQuery is not building a complete post URL for the PHP.
I am using jQuery version: 1.4.2 from Google. The query string is being built by using:
var ajaxOpts = {
type: "post",
url: "../php/addRecital.php",
data: "&performance=" + $("#performanceType :selected").text() +
"&groupName=" + $("#groupName").val() +
"&student1fName=" + $("#firstName").val() +
"&student1lname=" + $("#lastName").val() +
"&student1id=" + $("#studentID").val() +
"&student2fname=" + $("#Second_Student_firstName").val() +
"&student2lname=" + $("#Second_Student_lastName").val() +
"&student2id=" + $("#Second_Student_studentID").val() +
"&skillSelect=" + $("#skillSelect :selected").text() +
"&instrument1=" + $("#instument1 :selected").text() +
"&otherInstrument1=" + $("#otherInstrument1").val() +
"&instrument2=" + $("#Instument2 :selected").text() +
"&otherInstrument2=" + $("#otherInstrument2").val() +
"&location=" + $("#locationSelect :selected").text() +
"&roomNumber=" + $("#roomNumber").val() +
"&time=" + $("#timeSlotSelect :selected").text()
,
success: function(data) { ...
There is more than the above function, but I didn't think that it would pertain to here. I then call the code using:
$.ajax(ajaxOpts);
However, instead of creating the entire query string I get:
http://sterrcs123.mezoka.com/schoolProject/assign/assign13.html?groupName=&firstName=Samuel&lastName=Terrazas&studentID=23-343-3434&Second_Student_firstName=&Second_Student_lastName=&Second_Student_studentID=&otherInstrument=&Second_Student_Instrument=&roomNumber=2
Which as you can tell is missing a number of keys and their values. I would appreciate any help I can get because this is really driving me insane. Thanks.
It appears that your form is simply submitting itself without using your AJAX operation. Did you attach to the form's submit event and THEN run your ajax call? You will also want to return false from the submit event handler to prevent the default behavior you are seeing above.
Example:
$('#formid').submit(function(){
//your ajax code here.
return false;
});
If you're talking to an ASP.Net web service then you would need data to be a JSON string of your arguments. Otherwise, you can pass your data in by using an object literal (truncated for brevity):
var ajaxOpts = {
type: "post",
url: "../php/addRecital.php",
data: {
performance: $("#performanceType :selected").text(),
groupName: $("#groupName").val(),
student1fName: $("#firstName").val(),
student1lname: $("#lastName").val()
},
success: function(data)
}
As per the missing values, make sure you're capturing the button click / form submit.
$('form').submit(function (e) {
$.ajax(ajaxOpts);
return false;
});

Categories