jquery post not passing all parameters - php

i have this jquery code:
var idd = $(this).attr("id");
var page = $(this).attr("page");
var data = "lastmsg="+idd+"&page="+page;
$.ajax({
type: "POST",
url: "ajax_more.php",
data: data,
success: function(html){
$("ol#live_updates").append(html);
$("#more"+idd).remove(); // removing old more button
}
});
and this is the "ajax_more.php" code:
if(isset($_POST['lastmsg']))
{
$lastmsg = mysql_real_escape_string($_POST['lastmsg']);
$page = mysql_real_escape_string($_POST['page']);
echo $lastmsg . " " . $page;
}
Only ($lastmsg) passed, but any other parameter like ($page) is not passed. Where is the problem ??
i tried ($.post) and ($.ajax) with "POST" type, both not working...

data should be an object.
var data = {lastmsg: idd, page: page};

You need to properly encode all of your ajaxed parameters using encodeURI.
See my answer here for more information. Also, use your browser's console to debug.

Related

What could be wrong with this request in AJAX and PHP?

I'm trying to call a PHP page passing parameters with AJAX. I can see that the page is called, but the $_REQUEST doesn't take any parameters. If anyone can help me, I'd appreciate it. Thanks!
My AJAX is that:
<script>
$(document).ready(function(){
$('.c_x').change(function(){
var href = $(this).val();
$.ajax({
type: "POST",
url: "utils/inc_iscrizione.php",
data: 'cod_evento=' + href,
success: function (data) {
alert("data:" + data);
}
});
})
});
</script>
In the PHP Page, I have this.
if(isset($_REQUEST["cod_evento"]))
{
$search = $_REQUEST["cod_evento"];
echo "<script>alert('OK');</script>";
}
else
{
$search = "";
echo "<script>alert('FAIL');</script>";
}
Always the answer is failure. Thank you!
1- change your data format in ajax request from data:'cod_evento=' + href, to data : {code_evento:href}
2 - change your php echo from echo "alert('OK');" to echo "OK"; and same for else clause
Recommended
1 - change $_REQUEST to $_POST
2 - change alert('data:'+ data) to console.log(data)

$_Post failing (Sending Ajax)

Can someone please show me the correct way I can add these two lines of code
data: {name: info, me: '<?php echo $me; ?>'},
data: dataString ,
So that I can send them in a $_POST to my action.php , I have tried several ways to do this but cannot get both of them successfully to be passed on to my action_comments.php I understand I'm missing something possible when using data: below or have not correctly formatted my code . I'm a total beginner with very little experience so sorry if I lack good practice but hopefully can be better from my debugging . Thanks to anyone who helps me get passed this .
Here is complete code to give overview what Im doing
<script type="text/javascript">
$(function() {
// call the submit button ref: name
$(".submit_button").click(function() {
declare textcontent
var textcontent = $("#content").val();
//dataString = 'content' globel var
var dataString = 'content='+ textcontent;
declare info
var info = $('#name').val();
// option no text inputted
if(textcontent=='')
{
// show message if no text
alert("Enter some text..");
$("#content").focus();
}
else
{
//display text animation loading
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
//var info equals the string
var info = $('#content').val();
//start ajax call
$.ajax({
type: "POST",
//path to my action.php
url: "actions/action_comment.php",
//Need to undestand how to correctly format these lines so
//they are both succesful when submitted to my action_comment.php
$me is declared (not-shown here it holds integer)
data: {name: info, me: '<?php echo $me; ?>'},
// pass the string from textarea to $_POST
data: dataString ,
// I can get one or the other to work but not both
cache: true,
// feed the success my data
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
I have my $_POST as follows in action_comment.php
echo $me = $_POST['me'];
//DATASTRING FROM TEXTAREA
echo $content= $_POST['content'];
var dataString = 'content='+ textcontent;
$.ajax({
type: "POST",
url: "actions/action_comment.php",
data: {name: info, me: '<?php echo $me; ?>',txt_data: dataString},
....
});
Cannot use data attribute multiple times in same ajax request. Within php file you can access like $_POST['txt_data'] to get textarea content and same way for other parameters;
define data attribute once and pass all the data like as shown above.
if you want to post whole form data you can use this way
var form = $('#my_form');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
..
..
});

How to access AJAX response variables in PHP

I can't access my variables through ajax using php.
AJAX CODE
$("input[name='absent[]'").change(function() {
var obj = $(this); //checkbox
var valueZero = obj.val();
var Code = obj.attr('data-Code');
var value = obj.attr('data-session');
/*var theTR = $(this).parent('tr').children().find('td:eq(0)').addClass('hidden');*/
/* alert( theTR.text());*/
/*$(this).addClass('hidden');*/
$.ajax({
data: "{ code: '"+ Code +"', abt_prt: "+ valueZero +", InOut: "+ value +" }", // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
});
PHP CODE
<?php
if(isset($_REQUEST))
{
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
//need this variables to perform a insert query
}
?>
Do try this :
JAVASCRIPT
var mainString = "code="+Code+"&abt_prt="+valueZero+"&InOut="+value;
IN AJAX
data : mainString
PHP
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
use data like
data: { code:Code , abt_prt : valueZero , InOut : value },
and in php I don't really know what is $_REQUEST is but you can use
if(isset($_POST)){
}
Try changing data variable to:
data: {"code":Code,"abt_prt":valueZero,"InOut":value},
You are misunderstanding how AJAX parameters have to be sent. You do not need to send an index, you can send a simple Javascript object, like this:
$.ajax({
data: { code: Code, abt_prt: valueZero, InOut:value}, // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
However, if for some reason you want to send a string like you did, then decode it using json_decode.

Using jQuery to fetch variable from my database

I have done some reading and I think i need to use json for this. I have never used this before. I am trying to accomplish this, but in jQuery
$email_exist_check = mysqli_query($connect, "SELECT * FROM accounts WHERE email='$desired_email'") or die(mysql_error());
$email_exist = mysqli_num_rows($email_exist_check);
if ($email_exist == 0) {
//stop and make user write something else
} else {
//keep going
}
I am switching my website over from php to jQuery, which is also very new to me but seems so much better. Here is a piece of my jQuery. I am validating a form. The form works and submits, but now i want to see if the email exists in my database before submission. How would i do this?
if (email == "") {
$("#error5").css("display", "inline");
$("#email").focus();
return false;
}
// Im guessing the new code would go here
var dataString = $("#acc_form").serialize();
var action = $("#acc_form").attr('action');
$.ajax({
type: "POST",
url: action,
data: dataString,
success: window.location.assign("cashcheck_order.php")
});
This is a basic ajax call using jquery
var thing1; //thing 1 to use in js
var thing2; //thing 2 to use
var form = ("#acc_form"); //localize the form to a variable. you don't need to keep looking it up
var dataString = form.serialize();
var action = form.attr('action');
$.ajax({
url: action,
data: dataString,
type: "post",
success: function(data){
var responseData = $.parseJSON(data); //json native decoding if available, otherwise will do it with jquery
thing1 = responseData["thing1"];
thing2 = responseData["thing2"];
},
error: function(data){
console.log("error", data);
}
});
On the php side, to bring the vars in you use
$input1 = isset($_GET["name_of_input1"]) ? $_GET["name_of_input1"] : "";
if this is set, set this value, else set blank.
you can use $_POST, $_REQUEST if you prefer.
do not forget to sanitize your inputs.
Now to send it back to the js file
$dataToReturn = [
"thing1"=>"I'm thing 1",
"thing2"=>"I'm thing 2"
];
//sending back data
echo json_encode($dataToReturn);

Cannot send jQuery ajax() request to php

I have a trouble in using ajax() function. I have an html file with a form and have a segment of JavaScript code:
<script>
$(document).ready(function(){
$("form").submit(function(){
var url = "xxx.php/";
var param = $("#streetInput").serialize() + "&";
param += $("#cityInput").serialize() + "&";
param += $("#stateInput").serialize();
htmlobj = $.ajax({
url: url,
data: param,
type: 'GET',
dataType: 'JSON',
success: function(output) {
// parse the data here
},
error: function() {
}
});
});
});
</script>
I want construct an URL pointing to a specified php file by GET method. However, I don't know how to retrieve the parameters sent through URL in xxx.php file. I don't know how to debug. I just type
<?php
echo $_GET("streetInput");
echo $_GET("cityInput");
......
$xml = simplexml_load_file($url);
?>
but it didn't work. Can someone help me out? I want to give three parameters through URL to xxx.php, then print those elements
In xxx.php file, I construct a URL for an API request and get an XML file back. And I want to convert the $xml file to JSON format and return to my html file.
Change your JS code to:
<script>
$(document).ready(function(){
$("form").submit(function(){
var url = "xxx.php";
var param = $("#streetInput").serialize() + "&";
param += $("#cityInput").serialize() + "&";
param += $("#stateInput").serialize();
$.ajax({url: url, data: param, type: 'GET'});
});
});
</script>
Or, if you have only these fields in form, use this:
<script>
$(document).ready(function(){
$("form").submit(function(){
var url = "xxx.php";
var param = $(this).serializeArray(); //<- Or, .serialize() can also be used
$.ajax({url: url, data: param, type: 'GET'});
});
});
</script>

Categories