Sending AJAX post request to PHP - javascript

So here is my AJAX code using JQuery:
$('#button-upload').on('click', function(){
if( sendSMSArr.length > 0 ){
$.ajax({
url: 'manager/smsendr4.php',
type: 'POST',
dataType: 'json',
data: {'distribution': sendSMSArr},
success: function(response){
}
});
}
});
The request isn't registered in the network.
Secondly, I'm not sure how can I collect this data with PHP using $_POST.

You seem to be a php newbie. Here is a snippet of code you can use to retrive the ajax data.
Here is the link to the documentation about the global variable $_POST I suggest you to read it.
Another useful link about the predefined variables in php
JS code:
$('#button-upload').on('click', function(event){
event.preventDefault();
if( sendSMSArr.length > 0 ){
$.ajax({
url: 'manager/smsendr4.php',
type: 'POST',
dataType: 'json',
data: {'distribution': sendSMSArr},
success: function(response){
console.log(response);
}
});
}
});
PHP:
<?php
if(isset($_POST['distribution'])){
# I've added a sanitization filter, but you can omit it if you don't need to pass the data to a database.
$dist = filter_var($_POST['distribution'], FILTER_SANITIZE_STRING);
# put your logics here after you got the distribution $_POST variable value.
}
?>

Related

AJAX does not send POST

First of all, I have already read through many other posts and tried different things, but no solution approach has worked so far.
My problem: ajax does not send the POST data.
fillTable.js
function fillTableWithData(htmlID, tableSQL, colsSQL, orderSQL){
var jsondata = new FormData();
jsondata.append("action", htmlID);
jsondata.append("table", tableSQL);
jsondata.append("cols", colsSQL);
jsondata.append("order", orderSQL);
$.ajax({
url:"table.php",
method: "POST",
dataType: 'json',
contentType:false,
processData:false,
data: jsondata,
success:function(result){
// $(htmlID).html(result);
alert("test");
}
});
}
table.php
<?php
require('db.php');
echo (count($_POST)); // result is 0
if(isset($_POST['action'])){ // not set
if($_POST['action'] == "getDataAsRows"){
getDataAsRows($_POST['table'], $_POST['cols'], $_POST['order']);
}
}
function getDataAsRows($table, $cols, $order) {
...
}
?>
Both files are inside the same folder:
/scripts/fillTable.js
/scripts/table.php
The url should not be a problem, since the php code prints out the length of $_POST.

Header PHP not working after AJAX call from Javascript

so, this is probably a dumb question, but is it possible to execute the header function in a php file if I'm getting a response with AJAX?
In my case, I have a login form that gets error codes from the PHP script (custom error numbers hardcoded by me for testing) through AJAX (to avoid reloading the page) and alerts the associated message with JS, but if the username and password is correct, I want to create a PHP cookie and do a redirect. However I think AJAX only allows getting data, right?
This is my code:
JS
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
}
});
PHP
if(empty($user)){
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
setCookie(etc...); //this is
header('admin.php'); //what is not executing because I'm using AJAX
}else{
echo 902;
}
}
Please sorry if the question doesn't even make sense at all but I couldn't find a solution. Thanks in advance!
EDIT: I did not include the rest of the code to avoid complicating stuff, but if you need it for giving an anwser I'll add it right away! (:
You're right, you can't intermix like that. The php would simply execute right away, since it has no knowledge of the javascript and will be interpreted by the server at runtime, whereas the js will be interpreted by the browser.
One possible solution is to set a cookie with js and redirect with js as well. Or you could have the server that receives the login request set the cookie when the login request succeeds and have the js do the redirect after it gets a successful response from the server.
You can't do like that because ajax request process in backed and return the particular response and if you want to store the cookies and redirect then you should do it in javascript side while you get the response success
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location = "admin.php";
}
});
if(empty($user)){
setCookie(etc...); //this is
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo response// what every you want to store
}else{
echo 902;
}
}
If the ajax response satisfies your condition for redirection, you can use below:
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location="%LINK HERE%";
}
});
It's kind of ironic that you use ajax to avoid loading the page, but you'll be redirecting in another page anyway.
test sending data in json format:
Javascript
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
if(response.success){
window.location="%LINK HERE%";
}else{
var responseCode = parseInt(response.code);
alert(responseCode);
...
}
}
});
PHP
header("Content-type: application/json");
if(empty($user)){
echo json_encode(['success' => false, 'code' => 901]);
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo json_encode(['success' => true, 'data' => response]);
}else{
echo json_encode(['success' => false, 'code' => 902]);
}
}

Getting a particular value from ajax response

I am using ajax with masonry
Ajax code: This ajax is used to get data from
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
$items = $(data);
$grid.append( $items )
.masonry('appended', $items);
$(this).find(".loading").hide();
}
}
Php Part: This is just a small or sufficient part of php file to understand the problem
$b= "sv";
echo "asjdgsajd";
echo "a";
echo $b;
now i am getting everything correctly but i want to use say value of $b for setting a attribute value and also other values as content but how can i particularly get value of $b?
Thankyou
Change the dataType to json.
$.ajax({
type: "get",
url: "some.php",
dataType: "json",
success: function(data) {
//data will hold an object with your response data, no need to parse
console.log('Do whatever you want with ' + data.b + '.');
}
In some.php do the following:
$response =array(
'b' => "sv",
'a' => "asjdgsajd",
'c' => "a"
);
echo json_encode($response);
echo $b;
The items of the associative array will end up as properties of a javascript object, that you can use in your success callback (or done function as success is deprecated).
Try using json and change your php to send the json response that way you can send more content and access them on client side as you need it.
PHP Script :
$outArr=array("b"=>"sv","content1"=>"asjdgsajd","content2"=>"a");
$jsonResponse=json_encode($outArr);
echo $jsonResponse;
In AJAX function you can access your data like this:
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
data=$.parseJSON( data ); //parse response string
b=data.b;//value of b
content1=data.content1;//value of content1
$("#exampleDiv").attr("id",b).html(content1); //set the attribute and content here for an example div
}
}
})

codeigniter or PHP - how to go to a URL after a specific AJAX POST submission

I am successfully inserting data into my database in codeigniter via a an ajax post from javascript:
//JAVASCRIPT:
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
$('body').append(data); //MH - want to avoid this
}
});
//PHP:
public function respond(){
$this->load->model('scenarios_model');
$responseID = $this->scenarios_model->insert_response();
//redirect('/pages/view/name/$responseID') //MH - not working, so I have to do this
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
echo "<script>window.location = '$redirectURL'</script>";
}
But the problem is that I can't get codeigniter's redirect function to work, nor can I get PHP's header location method to work, as mentioned here:
Redirect to specified URL on PHP script completion?
either - I'm guessing this is because the headers are already sent? So as you can see, in order to get this to work, I have to echo out a script tag and dynamically insert it into the DOM, which seems janky. How do I do this properly?
Maybe you can 'return' the url in respond function and use it in js
PHP :
public function respond(){
// code
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
return json_encode(['url' => $redirectURL]);
}
JS :
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
dataType: 'JSON',
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
window.location = data.url
}
});
you have to concatenate the variable. That's all.
redirect('controller_name/function_name/parameter/'.$redirectURL);

How to alert ajax response

I've read dozens of related posts, but I still can't get this to work.
I want to alert the response in jquery I get from PHP.
PHP:
$msg=array();
if(empty($whatever)){
$msg['cenas']="Não há contas";
}else{
$msg['cenas']="Há contas";
};
echo json_encode($msg);
JS:
$.ajax({
url: 'myscript.php',
dataType: 'json',
success: function(response){
alert(response.cenas);
}
});
PHP is echoing
{cenas: "Há contas}"
But I can't get it to alert in JS.
The php should echo back {"cenas": "Há contas"}, but what did you get in the alert? Did you get an undefined? If so, try to use jQuery.parseJSON before alert. e.g:
$.ajax({
url:"myscript.php",
dataType: "json",
success:function(data){
var obj = jQuery.parseJSON(data);
alert(obj.cenas);
}
});
You should tell jQuery to expect (and parse) JSON in the response (although jQuery could guess this correctly...) and you should write your javascript correctly:
$.ajax({
url: 'myscript.php',
dataType: 'json',
success: function(response){
alert(response.cenas);
}
});
Try
$.ajax({
url:"myscript.php",
dataType: "json",
success:function(data){
alert(data.cenas);
}
});
You have a syntax error.
Check out the Docs for $.ajax

Categories

Resources