PHP _POST with Ajax not working - javascript

I have the following JavaScript code:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js'></script>
<script>
function sterge(id_user){
console.log(id_user);
var mesaj_post ='id_user=' + id_user;
$.ajax({
type: 'post',
url: 'deleteStudent.php',
data: mesaj_post,
dataType: 'text',
cache: false,
success:function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
});
}
</script>
The problem is that in the PHP file called by function, POST is empty and I don't understand why. The parameter of the function is not empty/null, and script result is SUCCESS
PHP Code:
<?php
include 'connect.php';
if(isset($_POST['id_user']))
echo $_POST['id_user'];
else
echo "empty post";
?>
Can you help me fix it? Any help would be appreciated.
Thank You!

As #charlietfl first said in his comment, the replace was the problem. But not only that one. The form was also doing a replace.
Thank You!

I pointed out in my comment
Remove the window.location.replace - it calls your php with a GET and no id_user
Had you posted your form too, we could have seen you did not cancel the submission. I hope you did that with something like
$("#formID").on("submit",function(e) {
e.preventDefault();
$.post("deleteStudent.php",{ "id_user":$("#id_user").val() }, function(data) {
console.log(data);
});
});

of course this error occurs, you pass a string not josn object to correct this error you should do the following in javascript code :mesaj_post ={'id_user': id_user}; :)

Try with this code this may do helpful for you
function sterge(id_user){
console.log(id_user);
var mesaj_post = {
"id_user":id_user
};
$.ajax({
type: 'post',
url: 'deleteStudent.php',
data: mesaj_post,
dataType: 'text',
cache: false,
success:function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
});
}

Related

JQuery AJAX, Deleting from a table when successful and keeping when unsuccessful

$.ajax({
type: "GET",
dataType: 'html',
url: "submitreef" + "?id=" + $id,
timeout: 5000,
cache: false,
success: function(data, status, xhr) {
Materialize.toast('Deleted', 4000);
},
error: function(xhr, ajaxOptions, thrownError) {
Materialize.toast('Error, we could not delete the campaign, please try again later', 4000);
$error = 'true';
}
});
}
if ($error != '') {
$(this).closest('tr').remove();
}
});
My problem is that when a button is pressed to delete a record from a table it works flawlessly, but when the error function is called it does not delete, I am trying to fix this, and my attempted fix is above, but it didn't work.
If you tried to delete it twice and there were 2 errors, it would then work, but that of course isn't very useful.
I really hope someone could help me out.
Many thanks.
var trToRemove = $(this).closest('tr');
$.ajax({
type: "GET",
dataType: 'html',
url: "submitreef"+"?id="+$id,
timeout: 5000,
cache: false,
success: function(data, status, xhr) {
trToRemove.remove();
Materialize.toast('Deleted', 4000);
},
error: function(xhr, ajaxOptions, thrownError) {
Materialize.toast('Error, we could not delete the campaign, please try again later', 4000);
}
});
so its basically the problem with asynchronous ajax. your error or success gets called only when it receives a response from server. but your following code gets executed before that.
if ($error != '') {
$(this).closest('tr').remove();
}
so thats why its producing unexpected removal of the element.
as suggested by #MuhammadOmerAslam You must also keep in mind that success callback may get called but your actual data has not been deleted. so its better to return something after you deleted the data on server side and compare it in your success handler before removing the tr element.
if you return "success" after data is deleted on server side then your success function should look something like the following:
success: function(data, status, xhr) {
if(data=='success'){
trToRemove.remove();
Materialize.toast('Deleted', 4000);
}else{
Materialize.toast('Error, we could not delete the campaign, please try again later', 4000);
}
},

jquery:ajax not firing in document getready

I have added jquery in head section and below code are in body section.
Problem is this isn't working.
Even alert is not showing. I am not getting any error in firebug.
I want to execute ajax on page load. I am not sure my approach is good.
Please advise. Below are the js code.
<script type="text/javascript">
$('document').ready(function(){
alert('Test');
$.ajax({
type: 'post',
url: 'profile_exec.php',
cache: false,
dataType: 'json',
data: uid,
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
var applied_counts = data.applied_count;
alert(applied_counts);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
</script>
As you can see this should work fine:
$('document').ready(function(){
alert('ready');
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'GET',
}).then(function(data){
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
since even the alert is not showing, check your html code. Maybe swap your jQuery with the google CDN served jQuery.
Maybe you have conflict or noConflict somewhere else. Check this out: jQuery.noConflict
Try this code:
jQuery(document).ready(function(){alert('test')})

How to make a generic ajax function for php file

I hope you can understand my question. I am trying to make a generic ajax function that will send some data to a php file and get the server's response. There is a very similar question here jquery - creating a generic ajax function , however I am having some troubles sending the data in a json format. Let me provide you the JS code:
function CallMethod(url, parameters, successCallback) {
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(parameters),
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
var pars = {
id:"1",
message:"hello world"
};
function onSuccess(data) {
console.log(data);
}
CallMethod('ajaxGeneric.php', pars, onSuccess);
And now here is my php file 'ajaxGeneric.php':
<?php
$id = $_POST["id"];
$msg = $_POST["message"];
echo $id;
echo $msg;
?>
When I run the page I have this error in the Chrome's console:
SyntaxError: Unexpected token < in JSON at position 0(…)
The php file seems also to have some problems trying to get the post values. What am I doing wrong? sending the data? getting the data back?
Any help will be greatly appreciated.
Try removing JSON.stringify and pass the parameters directly,So that your function will look like this
function CallMethod(url, parameters, successCallback) {
$.ajax({
type: 'POST',
url: url,
data: parameters,
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}

How to transform $.post to $.ajax?

I have this $.post peace of code:
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
and I wont to transform it to $.ajax. On the servlet side I am demanding request.getParamter("dataName") but I do not know how to write data: section in $.ajax so that I can get parameters like that(request.getParamter("dataName"))? Also, it seems to be problem with this type of code, I am asuming cause of async, that I cannot do this:
var answer="";
function(data,status){
console.log("Data:"+data);
answer = data;
}
And that answer is keeping empty(""), even though in console is written in deed "true" or "false" as my server answers. What is this about?
Thanks in advance.
I found out that problem is in the click() event. Ajax finishes when click() finishes, so I am not able to get data before event is done. What is bad in that is that I cannot fetch data because it is finished. Does anyone know how to solve this?
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
becomes
function getResult(data) {
// do something with data
// you can result = data here
return data;
}
$.ajax({
url: "../admin-login",
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: {
dataName:JSON.stringify({
username:uname,
password:pass,
})
},
success: function (data, status) {
getResult(data);
console.log(data);
console.log(status);
},
error: function (xhr, desc, err) {
console.log(xhr);
}
});
You need to see how the information os arriving to your servlet as query parameter or payload.
See this HttpServletRequest get JSON POST data
You could try structuring your AJAX request like the below:
var dataName = username:uname, password:pass;
$.ajax({
url: "../admin-login",
data: JSON.stringify(dataName),
type: "POST",
cache: false,
dataType: "json"
}).done(function(data, status) {
console.log("Data:"+data);
answer = data;
});

Multiple AJAX calls with errors

I'm trying to make a generic function that allows me to get data from different sources at the same time.
I based my solution on this post, and ended up with this:
var servicesURL = 'http://www.somedomain.com/services/xml_proxy.php?url=';
function getExternalData(service, callback) {
$.ajax({
type: 'GET',
url: servicesURL+service,
dataType: 'jsonp',
jsonpCallback: 'myfunction',
success: function(data) { callback(data); },
error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus+': '+errorThrown); }
});
}
getExternalData('data1.xml', function(data) {
console.log(data)
});
getExternalData('data2.xml', function(data) {
console.log(data)
});
Here's the code of the proxy I'm using:
<?php
header('Content-type: application/json');
$url = $_GET['url'];
echo 'myfunction('.json_encode(simplexml_load_file($url)).')';
?>
It works fine when I make a single call to the function, but when I make more that one call (as I did above), I get the following errors:
parsererror: Error: myfunction was not called
Uncaught TypeError: Property 'myfunction' of object [object Object] is not a function
Any help would be highly appreciated
Try putting the second call inside the callback of the first. That should fix the issues you are having.
http://forum.jquery.com/topic/multiple-jsonp-requests-causing-errors

Categories