I have the following ajax request:
var value = $.ajax({
type: "POST",
url: "url.php",
data: { $(someform).serialize(), something: test_number },
cache: false,
async: true
}).success(function(data){
alert("success!");
}).error(function() {
console.log("FAILED");
});
But it is logging FAILED although the url is right. What happens is that the page refreshes the page and the php query isn't done. I guess there are no errors within the url... any idea on why this happens?
You are kind of mixing methods to send your POST data. You can't serialize a query strong and then also append additional data to it using javascript object construct. You will likely need to manually append the last data element to the query string like this:
data: $(someform).serialize() + '&something=' + encodeURIComponent(test_number),
Of course there could still be a problem on the server-side script which is causing a non-200 HTTP response code (and triggering error handler). You just need to fix this first, and if you still have a problem, debug the server-side issue.
Related
I have been staring at this problem for the past 2 hours and can't seem to fathom it, even after validating that everything loads correctly when scouring the console.
I basically have two sliders on my page which will eventually populate results in a table, every time I change my slider I send an array of two values to my AJAX script:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
The browser successfully finds update_results.php but it does not perform the logic on the page ( I assume it has found the page as the 404 error does not appear in my console. )
At this point in time the script is extremely bare-bones as I'm obviously trying to establish communication between both files:
<?php
$vals = $_GET['values'];
echo $vals;
In this case $vals is never echoed to the page, am I missing something in my AJAX? I know the values enter the function as alerted them out before attaching the PHP script.
Ajax Calls are suffering from Browser Cache. If your browser thinks, that he already knows the content of update.php, he will return the cached content, and not trigger the script. Therefore your
modified code might simply not get executed. (Therefore your insert query wasn't executed)
To ensure this is not happening in your case, it is always a good idea to pass a parameter (timestamp) to the script, so your browser thinks it's another outcome:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?random_parameter=" + (new Date().getTime());
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
This will ensure that - at least - the browser cache is refreshed once per second for update_results.php, no matter what browser cache-settings or server-side cache advices are telling.
when Ajax is done, the success callback is triggered and the output of you php script is saved in data.
you can handle the data like this:
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
dataType: "text",
success: function(data) {
document.write( data )
}
});
PHP, running at server, is unaware of what happening at the front-end browser and it simply respond to ajax request as any other normal http request. So the failure of SQL query has nothing to do with javascript, which only responsible for sending ajax request and receiving and handling the response. I guess there's some errors in your php script.
I am using $.ajax to get a JSON response from a php script. if i log the data variable from the $.ajax success function it outputs a properly formatted JSON object, however when I try to access properties of the data var it's undefined. here is the php the is being sent back:
echo json_encode(array("status"=>true, "success"=>"Login Success", "message"=>"You have been logged in successfully."));
and here is my ajax call:
$.ajax({
type: "POST",
data: {
login: true,
username: $('#login-username').val(),
password: $('#login-password').val()
},
async: false,
url: "./php/client-login.php",
success: function (data) {
console.log(data.status);
if (data.status) {
console.log(data.success);
displayModal(data.success, data.message, "./js/login-modal-code.js");
} else if (!data.status) {
displayModal(data.error, data.message, "./js/login-modal-code.js");
}
},
error: function (jqXHR, status, responseText) {
console.log(status);
}
});
if i add the dataType: "json" option to the $.ajax call I get a parse error and if i try to do $.parseJSON(data); to access the data in the data var I get and unexpected token error. I'm not really sure what I'm doing wrong, I've used this setup before and it always has worked before but for some reason it isn't now. anyone see where i've gone wrong?
EDIT: forgot to mention here is the response from the php script:
{"status":true,"success":"Login Success","message":"You have been logged in successfully."}
EDIT 2: Here is a screen of my console. the top .length call is the json that was logged from console.log(data) and the bottom one is from the response in chrome dev tools network tab for the response from the php script. they line up perfectly yet the second is showing a length of 93, how can i fix this?
I was reading on jQuery Docs and found that "dataType: jsonp" does not work with sync request, and you're making this kind of request since you have async: false. Turning it on may solve your problem.
Also, give a look at the docs.
Good luck!
So I figured out a workaround for this problem, first I did JSON.stringify on the data followed by JSON.parse and lastly $.parseJSON() to get a javascript object to work with. Not sure why there are 2 invisible characters being added between when it leaves the php script and reaches the $.ajax call so if anyone knows why let me know
I would like to create an app that will send out a get request, then take the response and display it on the page,
this is part of my learning process, ultimately i would like to have the response be parsed and turned into
elements etc. but for now i am having trouble accessing the information within the response.
How can i alert() any of the results in the response?
the results of the script below ranged from undefined, to [object ojbect]
<script type="text/javascript">
var bbz;
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "MyDomain - its defined and on the web",
success: function(response) {
bbz = response;
alert(bbz.length);
alert(bbz);
alert(bbz[0]);
}
});
</script>
It looks to me like you are expecting a JSON response...
I am assuming this because of the way you are accessing properties of the response object -
bbz = response;
alert(bbz.length);
You'll want to set your dataType to "json".
If you set the dataType property to html, you should be able to simply return HTML.
You set dataType: "jsonp" which attempts to parse a jsonp object out of the data that is to be returned. However, what you really want is the markup that is in the file you are requesting data from. In order to do this, you must state the correct return type, so that the AJAX knows what data to give you, i.e. you tell the AJAX how to parse the data.
i took some interest in this script http://www.9lessons.info/2009/06/comment-system-with-jquery-ajax-and-php.html
and i see that the ajax calls commentajax.php.
what i want to do is to ignore that php, because i want to post to a json file and then get the response from the same file.
my server will use POST or PUT to put the data in the database, so there is no need for me to use php, just the syntax is killing me :)
i want to use :
$.ajax({
type: "POST",
url: "http://www.xxx.com/json",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
document.getElementById('comment').value='';
$("#name").focus();
$("#flash").hide();
}
});
but then how would the commentajax.php look like?
maybe replace the php with :
$.getJSON('http://www.xxx.com/json' , function(data) { ... });
any idea helps
Thanks.
edit1: i have the server-side script in place
If you have the server side scripting set up already, then what is the question again?
If you're asking how to handle the ajax call, then it's mostly a matter of looping through the JSON that you get back, and applying those values to the site in some manner. Pseudo code:
$.getJSON('http://www.xxx.com/json' , function(data) {
for(i=0; i<data.comment.length; i++) {
$(".commentTitle").html(data.comment[i].title);
$(".commentBody").html(data.comment[i].text);
}
});
If I am reading this correctly:
because i want to post to a json file and then get the response from the same file.
You are going to need some server side scripting in order to 'post' to the json file. How are you getting the data into the file.
You can 'read' the data file from the server, that's not a problem, it is a matter of getting the data into the file that you need the server side scripting for.
My ajax function has stopped working all of a sudden.
function get_file_info()
{
$.ajax({
type: "GET",
url: "http://localhost/includes/get_file_info.php",
dataType: "json",
jsonp: false,
jsonpCallback: "callbackName",
success: function(data) {
return data;
}
});
}
I did some debugging and found that the ajax request is going to
http://localhost/includes/get_file_info.php?_=1297356964250
I am just would like to know what it is and can be used for, also how to remove so the ajax request is like below so it works again.
http://localhost/includes/get_file_info.php
Many Thanks
If you add:
cache: true,
to your call it will remove the timestamp which is there to always call a different URL's so the browser doesn't cache the result. This is standard for calls except for datatypes script and jsonp.
As others have stated though, it would be good to change the server side to stop turning away anything with GET's, maybe check if the get is a _ and only numeric, if not then turn it away...
The "_=1297356964250" query string is jQuery's method of preventing the URL being cached and returning an old result. Adding this ensures that you're retrieving a new response every time.
This is not the cause of your request breaking down. It must be from another issue. Have you tried logging your response and seeing what it returns?
success: function(data) {
console.log(data);
}