jQuery ajax returning 'Object Object' - php

I am trying to send data to a PHP script using jQuery Ajax. For some reason the Ajax request is throwing up an error and returning the following data from the PHP script - [object Object]
I've copied my code in below. I've also copied code using the exact same method elsewhere on the page which seems to work fine!
Can anyone explain why this is happening?
Firstly, the code that is working fine
jQuery
$("#reqtable a").click(function(){
var cells = [];
var name;
var account;
var module;
var email;
$(this).parent().parent().find("td").each(function(){
cells.push($(this).html());
});
$(this).parent().parent().find("input").each(function(){
email = $(this).val();
});
$(this).parent().parent().prop('id', 'die');
name = cells[0];
account = cells[1];
module = cells [2];
$.ajax({
url: "release.php",
type: "POST",
data: {name: name, account: account, module: module, email: email},
success: function(){
$("#die").remove();
}
});
});
PHP
<?php
include('../../dbconnect.php');
$name = $_POST['name'];
$account = $_POST['account'];
$email = $_POST['email'];
$module = $_POST['module'];
$releasequery = "INSERT INTO release_assignment(name, account, email, module) VALUES ('$name', '$account', '$email', '$module')";
$release = $conn->query($releasequery);
$erasequery = "DELETE FROM request_assignment WHERE email='$email' AND module = $module";
$erase = $conn->query($erasequery);
?>
And now the code that IS NOT working.
jQuery
$("#downloadtable a").click(function(){
var dlcells = [];
var dlname;
var dlaccount;
var dlmodule;
var dlemail;
var dlsub;
var dlpath;
$(this).parent().parent().find("td").each(function(){
dlcells.push($(this).html());
});
$(this).parent().parent().find("input.dlemail").each(function(){
dlemail = $(this).val();
});
$(this).parent().parent().find("input.dlsub").each(function(){
dlsub = $(this).val();
});
$(this).parent().parent().find("input.dlpath").each(function(){
dlpath = $(this).val();
});
$(this).parent().parent().prop('id', 'die2');
dlname = dlcells[0];
dlaccount = dlcells[1];
dlmodule = dlcells [2];
$.ajax({
url: "download.php",
type: "POST",
data: {dlname: dlname, dlaccount: dlaccount, dlmodule: dlmodule, dlemail: dlemail, dlsub: dlsub, dlpath: dlpath},
success: function(data){
$("#die2").remove();
},
error: function(data){
$('#downloaddiv').html('<p>' + data + '</p>');
}
});
});
PHP
<?php
include('../../dbconnect.php');
$name = $_POST['dlname'];
$email = $_POST['dlemail'];
$account = $_POST['dlaccount'];
$module = $_POST['dlmodule'];
$path = $_POST['dlpath'];
$submission = $_POST['dlsub'];
$feedbackquery = "INSERT INTO feedback_assignments(name, email, level, unit, assignmentpath, submission) VALUES ('$name', $email, '$account', '$module', '$path', '$submission')";
$feedback = $conn->query($feedbackquery);
$erasequery = "DELETE FROM uploaded_assignments WHERE email='$email' AND unit = $module";
$erase = $conn->query($erasequery);
?>
When I comment out all the PHP code and simply put echo ($_POST['dlname']); it returns the data [object Object]
Can anyone explain what is going on and why it seems to work with one block of code but not the other?
Thanks!
Chris
Update: It might be worth mentioning that the initial link ('#downloadtable a') actually instigates a file download as well as the ajax call, whereas in the code that is working it simply makes the ajax call and nothing else. I don't know if this is throwing a spanner in the works but thought it worth mentioning.
Update 2: Using the jQuery Ajax error callback as described below I'm getting the following response:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
AJAX error: error :
The code I've used in the error callback is as follows:
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
Unfortunately I don't understand what this means. Can anyone shed any light on this?
Update 3 OK, I've found the reason for Ajax blowing up on me, and it relates to update number 1 (above). Basically because the link is to a file download (a .docx file) it seems to be causing the problem with ajax. When I change the link to href='#' instead of href="document.docx", the ajax and PHP script works.
This throws up a new question, of course - how can I get the link to download the file whilst simultaneously updating the database?

Specify a dataType and use console to debug your data response.
Also, notice that the error callback contains the following arguments and not any "data";
error Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
Update
The target file download.php might be throwing an exception. Possibly because of some missing quotes around $email on the line;
$feedbackquery = "INSERT INTO feedback_assignments(name, email, level, unit, assignmentpath, submission) VALUES ('$name', $email, '$account', '$module', '$path', '$submission')";
Debug download.php and make sure it generates the expected output/response.
I advice you to escape the values you are using to build your SQL query with to prevent SQL injection.

Related

AJAX Call Return PHP Value Empty

i have a problem about ajax call, i dont get what exactly why i still getting this empty success call. i tried the past solution to solve this but i don't know what the cause of this.
as you can see this my table then when i click the action of update, delete, or, add, even print_r($_POST) it's still empty.
then when i go to console i got this error.
the value of selected attr still send to the php file
heres my code :
$(document).on('click', '.update', function(){
var user_ID = $(this).attr('id');
$.ajax({
url:"datatable/account/fetch_single.php",
method:"POST",
data:{user_ID:user_ID},
dataType:"json",
success:function(data)
{
console.log(data);
$('#account_modal').modal('show');
$('#username').prop("disabled", true);
$('#username').val(data.user_Name);
$('#email').val(data.user_Email);
$('#pass').val(data.user_Pass);
$('#con_pass').val(data.user_Pass);
$('#level').val(data.level_ID).change();
$('#status').val(data.user_status).change();
$('#action').val('Edit');
$('#operation').val('Edit');
$('.modal-title').text('Edit Account Info');
$('#user_ID').val(user_ID);
}
})
});
fetch_single.php
include('db.php');
include('function.php');
if(isset($_POST["user_ID"]))
{
$output = array();
$statement = $conn->prepare(
"SELECT * FROM `user_accounts`
WHERE user_ID = '".$_POST["user_ID"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["level_ID"] = $row["level_ID"];
$output["user_Name"] = $row["user_Name"];
$output["user_Pass"] = decryptIt($row["user_Pass"]);
$output["user_Email"] = $row["user_Email"];
$output["user_status"] = $row["user_status"];
}
echo json_encode($output);
}
or it's might be the cause of problem is the design template?
i solve this issue, in my requested php file i change my $_POST to $_REQUEST if your data in ajax look like
data:{user_ID:user_ID}
or
data: "fname="+fname+"&lname="+lname
this might work for you, then if your data look like this data:new FormData(this) maybe you should use this type
data:{user_ID:user_ID}
to work the request and execute your sql.
but the best solution i got is change your
method:"POST"
to
type:"POST"
to solve this problem.
if your data.success_variable is undefined add
header('Content-type: application/json.');
to your requested php file.
Related topic:
ppumkin5 answer to
JQuery Ajax is sending GET instead of POST

getting error when i send the textfield value through ajax request to php using sencha touch

my view contains the following code
this.keypadDisplay = Ext.create('Ext.field.Text', {
xtype:'textfield',
disabled: true,
value: ''
});
my ajax request code is
handler: function(b, e) {
var thisUser = this.getValue();
alert(thisUser);
//params[this.getSubmitParamName()] = this.getValue();
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: thisUser,
method:'GET',
success: function(response, opts){
var text = response.responseText;
console.log(response.responseText);
alert(thisUser);
//alert(this.getValue());
//alert('Value: ' + this.getValue());
Ext.Msg.alert('success', text);
},
failure: function(response, opts){
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
},
scope: this
});
}
here i'm getting the "this.getValue" successfully. i want to insert to this.getValue to the code table.
my code.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('form',$con);
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisUser.value']."')";
if(mysql_query($insert))
{
echo('values inserted successfully');
}
else
{
echo('failure' . mysql_error());
}
?>
here im getting the error as "Undefined index:thisUser.Value in .../keypadapp/code.php " on line 5.
can anyone help me to ? thanks in advance...
Assign param value to variable in ajax call:
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: 'thisuser='+thisUser,
Then in php, access the value:
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisuser']."')";
Try changing $_GET['thisUser.value'] to $_GET['thisUser_value'] dots in $_GET and $_POST get converted to underscores in PHP. See this for more info https://stackoverflow.com/a/68742/589909
Update
Looking closer at your code you can't get javascript values of an object in php like you are doing. I assume that thisUser is an object. So when passing it as a param its properties will be posted to the server individually. So if it had a property called foo you would get it like so. $_GET['foo']; also you could dump the get request to see what was sent. var_dump($_GET);

jquery ajax always error even when update happens

When i call the function below:
function savePlace(id) {
var myName = $('#placeName').val();
var myAtmosphere = $('#placeAtmosphere').val()
var myType = $('#placeFoodType').val()
var myPrice = $('#placePrice').val();
$.ajax({
type: "POST",
url: "savePlace.php",
data: {"placeID" : id, "placeName": myName, "placeAtmosphere" : myAtmosphere, "placeType": myType, "placePrice" : myPrice},
dataType:"html",
success: function(data){
alert("YES");
},
// error function is always being called - even if database gets updated correctly
error: function (data) {
alert("no");
}
});
return false;
}
it will run - in that it will execute the php in savePlace.php (which runs a mysql update command). savePlace.php returns nothing currently, but it could return html or text if it's needed.
In any case, the error handler is always executed. i have checked in the chrome js inspector, and it reports:
statusText:"error"
responseText:""
status:0
Here is the mysql code, if that helps
<?php
require_once 'config/Common.php';
mysqli_report(MYSQLI_REPORT_ALL);
$placeID = htmlspecialchars(trim($_POST['placeID']));
$placeID = (int)$placeID;
$placeName = htmlspecialchars(trim($_POST['placeName']));
$placeAtmosphere = htmlspecialchars(trim($_POST['placeAtmosphere']));
$placeType = htmlspecialchars(trim($_POST['placeType']));
$placePrice = htmlspecialchars(trim($_POST['placePrice']));
$stmt = $EAE_CON->prepare("UPDATE EAE_PLACES SET NAME=?,ATMOSPHERE=?,FOOD_TYPE=?,PRICE=? WHERE idEAE_PLACES=?");
$stmt->bind_param('ssssi',$placeName, $placeAtmosphere, $placeType, $placePrice, $placeID);
$stmt->execute();
echo "Stuff";
?>
Note: I am running on localhost (my local machine, XAMPP)
I found the problem. I had to change the markup of a button that activated this function. For some reason that affected this.
I changed it from a to a . I'm not sure why that made a difference, but it appears to have fixed the problem.

Insert query in php not working with ajax

I am having some problems with insert query which is called from ajax. The ajax call comes back with success and I am able to see it with the changed html as noted below in the code under success:function(). I am not sure why the insert query in process.php is not working. dataString has the arguments correct (alert for dataString shows the right arguments) and my fields in database can take null values.
js code
var dataString=$('#testimonials').serialize();
alert (dataString);
$.ajax(
{
type: "POST",
url: "process.php",
data: dataString,
success:function() {
$('#testimonials').html("<div id='message'></div>");
$('#message').html("<h2>Your information has been submitted!</h2>")
.append("<p>Thank you for your help and support.</p>")
.hide()
.fadeIn(1500, function()
{
$('#message').append("<img id='checkmark' src='images/check.png' height='30' width='30'/>");
});
});
process.php file
$company =mysql_escape_string($_POST('company'));
$jobfunc = mysql_escape_string($_POST('jobfunc'));
$location = mysql_escape_string($_POST('location'));
$overall = mysql_escape_string($_POST('overall'));
$detail = mysql_escape_string($_POST('detail'));
$pros = mysql_escape_string($_POST('pros'));
$cons = mysql_escape_string($_POST('cons'));
$sr_mgmt = mysql_escape_string($_POST('sr_mgmt'));
$submitted_by = mysql_escape_string($_POST('submitted_by'));
$class = mysql_escape_string($_POST('classof'));
$school = mysql_escape_string($_POST('school'));
$anonymous = mysql_escape_string($_POST('anonymous'));
mysql_select_db($database_connTest, $connTest);
$query_AddTestimonial = "INSERT into testimonials (company,job_function,location,overall,project_details,pros,cons,sr_mgmt,submitted_by,class,school,anonymous) VALUES ('$company','$jobfunc','$location','$overall','$detail','$pros','$cons','$sr_mgmt','$submitted_by','$class','$school','$anonymous')";
$result_AddTestimonial = mysql_query($query_AddTestimonial) or die(mysql_error());
In the penultimate line when you create $query_AddTestimonial, the string you're creating isn't putting the php variables in because you're not telling it that they're variables. You can use the php variables like this:
$query_AddTestimonial = "INSERT into testimonials (company,job_function,location,overall,project_details,pros,cons,sr_mgmt,submitted_by,class,school,anonymous) VALUES ('{$company}','{$jobfunc}','{$location}','{$overall}','{$detail}','{$pros}','{$cons}','{$sr_mgmt}','{$submitted_by}','{$class}','{$school}','{$anonymous}')";
The problem was with the way I was calling the variables. It should have been $_POST['company'] rather than $_POST('company'). Completely missed it (the square brackets for $_POST since its an array)

jQuery ajax call won't update mysql after pressing back button

I have a form that uses ajax to submit data to a mysql database, then sends the form on to PayPal.
However, after submitting, if I click the back button on my browser, change some fields, and then submit the form again, the mysql data isn't updated, nor is a new entry created.
Here's my Jquery:
$j(".submit").click(function() {
var hasError = false;
var order_id = $j('input[name="custom"]').val();
var order_amount = $j('input[name="amount"]').val();
var service_type = $j('input[name="item_name"]').val();
var order_to = $j('input[name="to"]').val();
var order_from = $j('input[name="from"]').val();
var order_message = $j('textarea#message').val();
if(hasError == false) {
var dataString = 'order_id='+ order_id + '&order_amount=' + order_amount + '&service_type=' + service_type + '&order_to=' + order_to + '&order_from=' + order_from + '&order_message=' + order_message;
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php", data: dataString, success: function() { } });
} else {
return false;
}
});
Here's what my PHP script looks like:
<?php
// Make a MySQL Connection
include('dbconnect.php');
// Get data
$order_id = $_GET['order_id'];
$amount = $_GET['order_amount'];
$type = $_GET['service_type'];
$to = $_GET['order_to'];
$from = $_GET['order_from'];
$message = $_GET['order_message'];
// Insert a row of information into the table
mysql_query("REPLACE INTO gift_certificates (order_id, order_type, amount, order_to, order_from, order_message) VALUES('$order_id', '$type', '$amount', '$to', '$from', '$message')");
mysql_close();
?>
Any ideas?
You really should be using POST instead of GET, but regardless, I would check the following:
That jQuery is executing the ajax call after you click back and change the information, you should probably put either a console.log or an alert calls to see if javascript is failing
Add some echos in the PHP and some exits and go line by line and see how far it gets. Since you have it as a get, you can just load up another tab in your browser and change the information you need to.
if $j in your jQuery is the form you should be able to just do $j.serialize(), it's a handy function to get all the form data in one string
Mate,
Have you enclosed your jquery in
$j(function(){
});
To make sure it is only executed when the dom is ready?
Also, I'm assuming that you've manually gone and renamed jquery from "$" to "$j" to prevent namespace conflicts. If that isn't the case it should be $(function and not $j(function
Anyway apart from that, here are some tips for your code:
Step 1: rename all the "name" fields to be the name you want them to be in your "dataString" object. For example change input[name=from] to have the name "order_from"
Step 2:
Use this code.
$j(function(){
$j(".submit").click(function() {
var hasError = false;
if(hasError == false) {
var dataString = $j('form').serialize();
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php?uu="+Math.random(), data: dataString, success: function() { } });
} else {
return false;
}
});
});
You'll notice i slapped a random variable "uu=random" on the url, this is generally a built in function to jquery, but to make sure it isn't caching the response you can force it using this method.
good luck. If that doesn't work, try the script without renaming jquery on a fresh page. See if that works, you might have some collisions between that and other scripts on the page
Turns out the problem is due to the fact that I am using iframes. I was able to fix the problem by making the page without iframes. Thanks for your help all!

Categories