Javascript-POST not working - javascript

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');
}
});

Related

Passing JavaScript variables to PHP function using AJAX

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.

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'];

Third parameter of $.post() is not working

I am sending a post request to the REST web service using the following code:
<script type="application/javascript">
$(document).ready(function() {
$("#logbutton").click(function(event){
$.post(
"http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
{
ephone: $("#mobile").val(),
epassword: $("#password").val()
},
function(data) {
data = $.parseJSON( data );
$(".ray").html("$" + data.tag);
console.log( "You clicked a paragraph!" );
}
);
});
});
The web service gives a JSON response in format below:
{"tag":"login","status":true}
The call from the jquery code is running i.e. the web service is running fine, but the function that I have created to parse JSON is not working.
NOTE:
I tried to run this code without providing any value in the text field. The console displayed the json response and also console.log line. But when I again entered the values into the fields, then it didn't. I am unable to understand this thing.
Anyone having any idea?
Thanks in advance.
You could try the more verbose and detailed form using $.ajax:
$(document).ready(function() {
$("#logbutton").click(function(event) {
var req = {
ephone: $("#mobile").val(),
epassword: $("#password").val()
};
$.ajax({
url: "http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
data: req,
dataType: 'json',
type: 'POST'
}).done(function(data) {
console.log(data);
$(".ray").html("$" + data.tag);
console.log("You clicked a paragraph!");
}).fail(function(err) {
console.error(err);
});
});
});
This will be easier for you to pinpoint where the error is coming from

AJAX not sending data

I am using the following code to get data from an input field and send it to PHP by POST but its not working
<script type="text/javascript">
$(document).ready(function () {
$("#id_1").change(function () {
var rat1 = $(this).val();
$.ajax({
url: "upload.php",
type: "post",
data: rat1,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
this is the input form
<input type="number" name="your_awesome_parameter" id="id_1" class="rating" data-clearable="remove"
data-icon-lib="fa" data-active-icon="fa-heart" data-inactive-icon="fa-heart-o"
data-clearable-icon="fa-trash-o"/>
You need to provide a name for the parameter. It should be:
data: { param_name: rat1 }
Then in upload.php you access it with $_POST['param_name']
Just in case, did you imported Jquery into your project?
I tested your code and I with the minor change that Barmar specified and it is working for me.
Try to use this code in your php file and see if you get any response in the developer tools console.
$data = $_POST["param_name"];
echo json_encode([$data]);
Try in this way men
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ejemplo_ajax_proceso.php',
type: 'post',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (response) {
$("#resultado").html(response);
}
});
}
change on input type number is not working in older versions of browsers, I think not sure. But try this below solution as you are using input type number.
$("#id_1").on("mouseup keyup",function () {
//your logic here
});
and passing data as already mentioned by others:
data: { param_name: rat1 }

ajax data sent wont work

below is an ajax but it wont work, what seems be the problem? assume that I have requestparser.php and inside it i have "echo "yes ajax work!";".
$(document).ready(function(){
// start ajax form submission
$.ajax({
url: "requestparser.php",
type:"POST",
data: ({ "pulldata" : "oy" }),
success:function(e){
if(($.trim(e)=="success")){
alert("yes");
}else{
alert("no");
}
},error:function(){
alert("error");
}
});
});
as above ajax function ,the process should be, on load it will send first a post request to requestparser.php with a post name of "pulldata" and post content of "oy" and when the requestparser receive that post request from the ajax so then respond with "yes ajax work!" and since the respond from requestparser.php is not equal to success then it should display "no".
any help would be greatly appreciated
I tried to debug your code and it worked fine for me. So can you try this code and say what error it shows ?
$(document).ready(function () {
$.ajax({
url: "test.php",
type: "POST",
data: ({
"pulldata": "oy"
}),
success: function (e) {
console.log(e);
},
error: function (e) {
console.error(e);
}
});
});
test.php
<?php
var_dump($_POST);
One more thing, just for confirmation, you have included jQuery in your page before using ajax right ?

Categories