Passing JavaScript variables to PHP function using AJAX - javascript

In my dashboard.php I have a Javascript function that is called based on the user clicking a button. When the button is clicked, it calls a JavaScript function called getTeamMembers and values are passed across to it. The values passed across to this function are then sent to a PHP function (which is also located in dashboard.php).
However I am not getting any success and was hoping that someone could guide me on where I am going wrong. I am a noob when it comes to AJAX so I assume I am making a silly mistake.
I know my function is definitely getting the intended variable data passed to it, after doing a quick window.alert(myVar); within the function.
This is what I have so far:
function getTeamMembers(teamID,lecturer_id) {
var functionName = 'loadTeamMembersChart';
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: { functionName: 'loadTeamMembersChart', teamID: teamID, lecturer_id: lecturer_id },
success: function(){
alert("OK");
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
}
);
}
Before calling the desired php function, I collect the sent varaibles just before my php Dashboard class starts at the top of the file. I plan to pass the variables across once I can be sure that they are actually there.
However, when I click the button, nothing can be echo'd from the sent data.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if (!empty($_POST["teamID"]) && !empty($_POST["lecturer_id"]))
{
$teamID = $_POST['teamID'];
$lecturer_id = $_POST['lecturer_id'];
echo $teamID;
echo " is your teamID";
}
else
{
echo "no teamID supplied";
}
}

you else statement in you success function , and that's not how you set fail callback, try the following and tell us what do you see in the console.
function getTeamMembers(teamID,lecturer_id) {
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: {functionname: 'loadTeamMembersChart', arguments: [teamID, lecturer_id]},
success: function(data) {
console.log(data);
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
});
}

Seems like your function is not returning a success message when getting into the following statement.
if ($result) {
"Awesome, it worked"
}
Please try to add a return before the string.
if ($result) {
return "Awesome, it worked";
}
It can be other factors, but the information you provided is not enough to make any further analysis.

Related

jQuery Ajax not sending Post data to PHP file

I'm trying to send variables from my JavaScript to a PHP file using AJAX but it's not working. I've looked through all the similar asked questions (there are a bunch) but have yet to find a solution.
This is my first php file (one with the form, sends data to JavaScript):
<option value="imageOne" data-cuteform-image='assets/SketchThumbnails/imageOne.png></option>
<input id="inputURLID" type="text" name="inputURL">
<button type="submit" onclick="handleInputs(document.getElementById('sketch').value, document.getElementById('inputURLID').value); return false;">Submit</button>
JavaScript (where AJAX call is):
var content = {
'sketch': pickedSketch,
'songUrl': enteredURL
};
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
PHP (loadSketch.php):
if(isset($_POST['songUrl']))
{
$temp = $_POST['songUrl'];
echo $temp;
echo "received AJAX data";
} else {
echo "nothing in post variable";
}
When I get redirected to loadSketch.php (from the successful ajax call), "nothing in post variable" gets echoed out. Any ideas what I'm doing wrong?
Any insight is much appreciated! :)
Nothing is in songURL because when your Ajax function returns it is redirecting to the same page you just posted to. It is creating a new HTTP request to that PHP file with no data sending to it. Remove the comments on the console messages and you'll see the correct echo messages.
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
alert("success");
console.log(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
You should not use a submit button because it makes the whole page reload; instead use normal buttons and handle the click events calling your AJAX function.
HTML:
<button onclick="doAjaxFunction(param1, param2);">Calling Ajax Function<button>
JavaScript:
function doAjaxFunction(val1,val2){
$.ajax({
type: "POST",
url: "loadSketch.php",
dataType: "json",
data: {"'value1':'"+ val1+"', 'value2':'"+ val2+"'"},
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Then just pick your POST parameters in loadSketch.php and use them.
PHP:
$x = $_POST['value1'];
$y = $_POST['value2'];

Jquery Ajax Server Polling; Polling the server based on an earlier ajax response

What I am trying to do:
1. Initially gives an ajax request to the server based on some inputs
2. The server returns a job id generated by RQ (Python-rq)
3. Based on the job id ajax request made to a url constructed with the jobid regularly till a valid response is obtained
What I have:
$.ajax({
type: "POST",
url: "/start",
data:{crop: valueCrop, state: valueState, variablemeasure: valueVariable, unit:unitMeasure, from:yearFrom, to:yearTo},
success: function(results) {
console.log(results);
var jobId='';
jobId = results;
function ajax_request() {
$.ajax({
type: "GET",
url: "/results/" + jobId,
dataType: "json",
success:function(xhr_data) {
if (xhr_data == {"status":"pending","data":[]}){
console.log("Waiting for response");
setTimeout(function() { ajax_request(); }, 2000);
} else {
console.log(xhr_data);
}
},
error:function(error) {
console.log(error)
}
});
}
},
error: function(error) {
console.log(error)
}
})
Is this even possible? I am not getting any output at all on the console although the rq says the job is finished. I think it is not entering that if loop. When I visit the "/results/jobId" url I am able to see the result.
Please help.
I see a few bugs in this code. First of all, you have defined the function ajax_request(). But you are not calling it. You can call it at the end of its definition.
Secondly, this code is problematic:
if (xhr_data == {"status":"pending","data":[]})
The object notation creates another object which is definitely not equal to xhr_data.
You can do:
if (xhr_data.status === "pending")

Javascript-POST not working

onSubmit: function(invalid, e) {
e.preventDefault();
if(!invalid)
{
alert("test");
$.post('login.php', this.$form.serialize(), function(response) {
// asdasd
}, 'json');
}
}
I get the alert box but the post doesn't seem to work. Is there anything clearly wrong in the above code?
I am using IdealForms.
The request works, there must be an issue in your server side code. Make sure that:
1) login.php exists and it's in the right path.
2) Your PHP script echos JSON. Try a simple test script:
<?php
// login.php
echo json_encode(array('value' => true)); // send as JSON
Then in JavaScript log the response to the console (press F12 or Cmd+Shift+I):
onSubmit: function(invalid, e) {
e.preventDefault();
if(!invalid) {
$.post('login.php', this.$form.serialize(), function(response) {
console.log(response);
}, 'json'); // read as JSON
}
}
The console should output an object {value: true}.
PS: I'm the developer of Ideal Forms.
All you need to do is call JQuery, and use code like this:
$.ajax({
type: "POST",
url: "login.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});

JSON pass null value to MVC 4 controller in IE9

I got some problem while posting JSON data into MVC 4 controller.
Below method is working fine in Firefox but unfortunately failed in IE 9
The JavaScript :
var newCustomer = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '#Url.Content("~/CustomerHeader/CreateCustomerHeader")',
cache: false,
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newCustomer),
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
and this is my controller :
public JsonResult CreateCustomerHeader(CustomerHeader record)
{
try
{
if (!ModelState.IsValid)
{
return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
}
RepositoryHeader.Update(record);
return Json(new { Result = "OK", Record = record});
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
the "data" variable as in public JsonResult CreateCustomerHeader(CustomerHeader **data**) is getting NULL but while using FireFox it holds the correct value.
UPDATE : New method trying using $.post
function CreateNewCustomer(newCustomer) {
$.post("/CustomerHeader/CreateCustomerHeader",
newCustomer,
function (response, status, jqxhr) {
console.log(response.toString())
});
}
Based off the bit that you've shown, this is a simplified variation that may work more consistently, using jQuery.post() (http://api.jquery.com/jQuery.post/):
var data = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.post({
'#Url.Action("CreateCustomerHeader", "CustomerHeader")',
data,
function(response, status, jqxhr){
// do something with the response data
}).success(function () {
$("#message").html("Success");
}).error(function () {
$("#message").html("Save failed");
});
$.post() uses $.ajax as it's base, but abstracts some of the details away. For instance, $.post calls are not cached, so you don't need to set the cache state (and setting it is ignored if you do). Using a simple JavaScript object lets jQuery decide how to serialize the POST variables; when using this format, I rarely have issues with the model binder not being able to properly bind to my .NET classes.
response is whatever you send back from the controller; in your case, a JSON object. status is a simple text value like success or error, and jqxhr is a jQuery XMLHttpRequest object, which you could use to get some more information about the request, but I rarely find a need for it.
first of all I would like to apologize #Tieson.T for not providing details on JavaScript section of the view. The problem is actually caused by $('#addCustomerHeaderModal').modal('hide') that occurred just after ajax call.
The full script :
try{ ..
var newCustomer =
{
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '/CustomerHeader/CreateCustomerHeader',
cache: false,
type: "POST",
dataType: "json",
data: JSON.stringify(newCustomer),
contentType: "application/json; charset=utf-8",
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
}
catch(Error) {
console.log(Error.toString());
}
//$('#addCustomerHeaderModal').modal('hide')//THIS is the part that causing controller cannot retrieve the data but happened only with IE!
I have commented $('#addCustomerHeaderModal').modal('hide') and now the value received by controller is no more NULL with IE. Don't know why modal-hide event behave like this with IE9.
Thanks for all the efforts in solving my problem guys :-)

How to handle response of a POST request in jQuery

I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.

Categories