How to get post values with ajax .post - php

I have two files filter.php and products.php included to index.php and I am using .post submit form without refreshing. I send data to products.php and return it back also i refresh my filter and there is my problem. When i try to var dump post data in filter.php it is empty
Here is my script
function ajaxFilter()
{
var str = jQuery( "form[name=\"filters\"]" ).serialize();
jQuery.post( "/", str )
.done(function( data ) {
var productList = jQuery(data).find(".list_product").html();
var filter = jQuery(data).find(".filters").html();
jQuery(".list_product").html(productList);
jQuery(".filters").html(filter);
});
}
Any ideas how to get POST?
I though about putting my post via script to hidden inputs and return them also as html
If it is bad idea or just wrong start.

try this:
var Data = $("form[name=\"filters\"]").serializeArray();
var URL = "products.php"; // whatever filepath where you send data
jQuery.ajax({
type: "POST",
url: URL,
processData: true,
data: Data,
dataType: "html",
success: function (productList) {
// filter your result whatever you return from products.php
jQuery(".list_product").html(productList);
},
error: function (x, y, z) {
var a = x.responseText;
jQuery(".list_product").html(a);
}
});

Use the full URL.
Provide the return values of .error() if you still have problems.

Related

Bringing back several variables into ajax form POST success as jQuery variables

I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery

jQuery Ajax(post), data not being received by PHP

The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}

Serialize() form in an existing ajax function

Actually the following function works fine, but now I need to add other variable in order to return from the php file the right statement.
function sssssss1(page) {
loading_show();
$.ajax({
type: "GET",
url: "load_data.php",
data: "page=" + page,
success: function (msg) {
$("#search").ajaxComplete(function (event, request, settings) {
loading_hide();
$("#search").html(msg);
});
}
});
}
I need to add the following two variable to be read by my php file. I have tried different solution, but nothing seem working
var form2 = document.myform2;
var dataString1 = $(form2).serialize();
How to add those variable in my existing function? Any idea?
You can send object as data,
this line:
data: "page="+page,
could be
data: {mypage:"page="+page, form2:document.myform2, dataString1:$(form2).serialize()}
and your PHP can get it like:
$page = $_GET['mypage'];
$form2 = $_GET['form2'];
$dataString = $_GET['dataString1'];
Hope it Help.

How can I add the content of a page in a div with Ajax?

I have a list in my site, and when I click each of the list items, I want the div next to them to reload with ajax, so as not to reload the whole page.
Here is my javascript
parameters = "category_id="+categoryId;
var result = ajaxFunction("changeCategory.php", parameters);
$("#mydiv").html(result);
The ajaxFunction() function is the regular $.ajax() jQuery function, with "POST". In the "changeCategory.php" I call with include another php file.
The problem is that the whole page is reloaded instead of only the div. I want to use this ajax function I have, cause I want to send data to my php file.
Does anyone know what should I do to reload only the div?
Thanks in advance
Try this
$(document).ready(function(){
var parameters = {category_id:categoryId};
$.ajax({
url:'changeCategory.php',
type:'post',
data:parameters,
dataType:'html',
success:function(result){
$("#mydiv").html(result);
},
error:function(){
alert('Error in loading [itemid]...');
}
});
});
Also verify that when in your click event this line is written or not return false; This is required.
Try using load to load the div with the url contents -
$("#mydiv").load("changeCategory.php", {category_id: "category_id_value"} );
You can pass data to the url.
The POST method is used if data is provided as an object; otherwise, GET is assumed.
you could send a query to that PHP so it "understands" that it needs to output only the div, like this:
in your javascript:
//add the query here
parameters = "category_id="+categoryId + "&type=divonly";
var result = ajaxFunction("changeCategory.php", parameters);
$("#mydiv").html(result);
in your "changeCategory.php":
//add a query check:
$type = "";
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
//then, depending on the type, output only the div:
if($type === "divonly"){
//output the div only;
} else {
//your normal page
}
$(document).ready(function() {
$.ajax({
url: "right.php",
type: "POST",
data: {},
cache: false,
success: function (response) {
$('#right_description').html(response);
}
});
});
The whole page is reloaded that means there may be an error in your javascript code
check it again
or try this one
function name_of_your_function(id)
{
var html = $.ajax({
type: "GET",
url: "ajax_main_sectors.php",
data: "sec="+id,
async: false
}).responseText;
document.getElementById("your div id").innerHTML=html;
}
you can use get method or post method....

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Categories