jquery ajax not working with data field - php

When i submit a jquery ajax request without the data value, it works, when i submit it with the data value, nothing happens. I check if it works using firebug. I think its a simple mistake but i cant seem to figure it out. Please Help.
Here is the Jquery Code
var inputString = $("something").val();
var suggestions = $.ajax({
url: "temp.php",
type: "POST",
data: {valueInput : inputString},
dataType: "html"
});
temp.php just has some simple code since I'm testing:
echo "We got sumn here";
another thing is the suggestions variable is empty, any ideas?

You can try:
data: 'valueInput=' + encodeURIComponent(inputString),
Update
suggestions is being set to the jqXHR object returned from the $.ajax() function. If you want to do work on the server-response then you need to set a success callback somehow. Here are two ways:
var inputString = $("something").val();
$.ajax({
url : "temp.php",
type : "POST",
data : 'valueInput=' + encodeURIComponent(inputString),
dataType : "html",
success : function (serverResponse) {
//you can now do work on the server-response, it's stored in the serverResponse variable
alert(serverResponse);
}
});
OR
var inputString = $("something").val(),
suggestions = $.ajax({
url : "temp.php",
type : "POST",
data : 'valueInput=' + encodeURIComponent(inputString),
dataType : "html"
});
$.when(suggestions).then(function () {
//this is your callback function
});
I suggest the first method, the second is more advanced and is really only helpful if you want to wait for a set of AJAX requests to complete before doing something.

valueInput should be in quotes as it's a name. 'valueInput'
var inputString = $("something").val();
var suggestions = $.ajax({
url: "temp.php",
type: "POST",
data: {'valueInput': inputString},
dataType: "html"
});

You need to pass data in a form of query string. It should be something like a=1&b=2&c=3&d=4&e=5
You can use .serialize() method over jQuery object that has selected form elements or form tag. So, maybe this code shall be helpful.
var suggestions = $.ajax({
url: "temp.php",
type: "POST",
data: $("something").serialize(),
dataType: "html"
});

You can try
data: JSON.stringify({'valueInput': inputString}),
in you data parameter.

Related

Post variable not passing

Any idea why this doesn't work? I have tried to see if the button clicked actually works with alerts, had alerts as well as before and after the ajax code and they both worked.
var selectedCheckboxes = "12421";
jQuery(document).ready(function($){
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: { selectedCheckboxes: "selectedCheckboxes" },
success: function(response){
//do action
},
error: function(){
// do action
}
});
});
});
the link:
Edit
test.php
<?php
echo $_POST["selectedCheckboxes"];
?>
Try this instead:
Edit
If you want the output of the php in your page you have to do something like this in your javascsript
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: { selectedCheckboxes: selectedCheckboxes },
success: function(response){
$("body").html(response);
},
error: function(){
// do action
}
});
});
You may need to change the "body" tag.. or not
depends on what the teste.php returns
Well, if you don't want the output to be placed inside your current page html, maybe a different aproach would be better.
Maybe there are better answers but you could try something like:
<form method="post" action="test.php" onsubmit="javascript:$('#selectedCheckboxes').val(selectedCheckboxes);">
<input type="hidden" value="" name="selectedCheckboxes" id="selectedCheckboxes">
<input type="submit" value="Edit">
</form>
You would have to style the submit input
Does the idea help? No ajax though.
The reason you're not seeing the AJAX reqeust go through is because when the you click on the anchor tag, the browser is performing the default action of navigating to 'test.php', which cancels the AJAX call. Since you are simply GET'ing that page, and not POST'ing to it, there is nothing in $_POST. In order to prevent this default action, either use a span instead of an a tag (recommended), or prevent the default action, doing something like this:
Edit
If I get you right, you want to pass selectedCheckboxes as JSON to the Server. In this case you need to actually pass your selectedCheckboxes variable to the Server.
Like this:
$.ajax({
url: "test.php",
type: "POST",
data: selectedCheckboxes,
success: function(response){
//do action
},
error: function(){
// do action
}
});
The problem with your code is that you passed a new JSONObject containing a String that contains "selectedCheckboxes". You did not pass the actual variable.
Put a return false; after ajax call
You try to pass a variable selectedCheckboxes but unfortunately with double ("") quotes you passing a string as selectedCheckboxes
Use below code
var selectedCheckboxes = "12421";
var dataObject = {};
data[selectedCheckboxes] = 1;
jQuery(document).ready(function($){
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: dataObject ,
success: function(response){
//do action
},
error: function(){
// do action
}
});
});
});
Hope this helps...

ajax load an external file by passing parameters

Am trying to load an external file to a div using this function
$(document).ready(function(){
$("#postdiv").load('posts.php');
});
This is working alright.
The problem is, I need to pass parameters/variables to posts.php from the caller page and use them to do some filtering.
How can i do this ?
You can pass parameters with jquery load
This method will pass parameter as POST
$("#postdiv").load('posts.php',{'name' : 'Test','age' : 25});
if you want pass it as GET you can do like this
$("#postdiv").load('posts.php?name=Test&age=25');
you can read more here
Use ajax
ajax is better option,best practice.
var value = "value of the data here";
$.ajax({
url: "posts.php",
data: "key="+value,
type: "post",
success: function(data){
$('#postdiv').html(data);
}
});
you can make an ajax call
$.ajax({
url: "posts.php",
data: data,
type: "post",
success: function(data){
$('#postdiv').html(data);
}
});
or you want to go for load then try below code
$( "#postdiv" ).load( "posts.php", { "test[]": [ "test1", "test2" ] } );

Sending two variables in a single AJAX request

I have a page that gets the user from $_POST. It is something like this:
$login=$_POST['name'];
Then when I click a button it makes an AJAX request like the following:
var id = $(this).val();
var dataString = 'Empresa=' + id;
$.ajax({
type: "POST",
url: "processemp.php",
data: dataString,
success: function (html) {
This works fine but I need to send $login with the request too. How can I send two variables at once?
You can try one of the two solutions below, but please note that the script should be written in the PHP page, not in a separate javascript file.
The data option of jQuery.ajax() accepts two types of form: PlanObject or String.
data
Type: PlainObject or String Data to be sent to the server. It is
converted to a query string, if not already a string. It's appended to
the url for GET-requests. See processData option to prevent this
automatic processing. Object must be Key/Value pairs. If value is an
Array, jQuery serializes multiple values with same key based on the
value of the traditional setting (described below).
As a plain object,
var id = $(this).val();
$.ajax({
type: "POST",
url: "processemp.php",
data: {
Empresa : id,
login : '<?php echo $login; ?>'
},
success: function(html){
}
});
As a query string,
var id = $(this).val();
$.ajax({
type: "POST",
url: "processemp.php",
data: 'Empresa=' + id + '&login= <?php echo $login; ?>',
success: function(html){
}
});

$.ajax POST Undefined index

Apologies in advance for any mistakes. This is my first post on StackOverflow.
So basically I have a php function. Inside it is a jQuery click function with a variable, into which I'm saving the clicked element's text. I'm trying to send that variable's value to my Uredi.php file, via $.ajax function, to save it into a php variable. However, I'm getting an "Undefined index" error. Help would be greatly appreciated. Thank you.
Here's the code:
PHP function:
public function uredi()
{
?>
<script>
$('.edit').click(function(){
$('.naslov_edit').val($(this).text());
$('#on_top').hide();
var refId = $(this).text();
$.ajax({
url: 'uredi.php',
type: "POST",
data: {id: refId},
success: function(data){
alert(data);
}
});
});
</script>
<?php
}
Uredi.php:
<?php
include 'Funkcije.php';
$uredi = new urejanje();
$uredi->uredi();
$id = $_POST['id'];
echo $id;
?>
Funkcije.php is the file with the uredi() function.
EDIT: Thank you everyone for helping. I figured out the problem. Turns out I just had to clean up my code a bit.
Why are you assigning $(this).text() to var id and then not using it in the $.ajax()? Remember scope and what doe $(this) actually reference within the $ajax()? I would also shy away from naming variables "id" Try:
var refId = $(this).text();
$.ajax({
url: 'uredi.php',
type: "POST",
//dataType: 'json',
data: {id: refId},
success: function(data){
alert(data);
}
});
Use this;
$.ajax({
url: 'uredi.php',
type: "POST",
data: "id=" + refId,
success: function(data){
alert(data);
}
});
perhaps you meant to read the post vars before initializing the class and maybe even pass Id in?
$id = $_POST['id'];
$uredi = new urejanje();
$uredi->uredi($id);
In any case I think You'll need to show us whats inside Funkcije.php

data return is null in php form after ajax submit

i am trying to submit a php form through ajax, my jquery code is
$("#editContraForm").submit(function editContra (e) {
e.preventDefault();
dataString = $("#editContraForm").serialize();
$.ajax({
type: "POST",
url: "./validations/contraAjax.php",
data: dataString,
action : "edit",
dataType: "text",
success: function(data) {
console.debug("success : "+data);
},
error : function(error){
console.debug("erro");
}
});
});
and php code is (contraAjax.php)
if(!isset($_SESSION))
session_start();
include_once '../connect/connectOpen.php';
$action=isset($_REQUEST['action'])?$_REQUEST['action']:'';
if($action=="edit"){
echo 'good';
}
and the call is successfule (as shown in firbug) but console prints 'success: ', means data is null. What is wrong with this code, Kindly help me
You should not serialize data, but pass an object.
See jQuery documentation: http://api.jquery.com/jQuery.ajax/
use action as a parameter and then access it using $_POST['action'].
also try to var_dump($_POST['action']);
To add an action parameter just concatenate it into the data string.
data: dataString + '&action=edit',

Categories