I'm trying to send variables from 2 form elements to another PHP script, through jquery.
Not sure what I'm doing wrong, just can't get the variables sent to the other PHP script.
Tried with jquery serialize as well, didn't get that to work either.
Tried with serialize() command as well.
Any suggestions more than welcome.
Thanks!
When putting the data in url manually, the return is correct. Then in data I have +page, as:
$.ajax
({
type: "GET",
url: "agent_talktime_pag.load.php?txtDate=2007-03-04&zone=Hongkong",
data: "page="+page,
success: function(msg)
If I use " var datastring = $('#idForm').serialize(); " the return doesn't work.
The variables get passed in the url, but the issue seems that the page="+page isn't passed. Which makes the load script not work. I tried to add a hidden field in the form like:
<input type="hidden" name="page" value="+page">
But, seems it's not passed as expected by the load script. The +page becomes just a string, think in the $.ajax it functions as a counter?
Any ideas?
$(document).ready(function(){
$("#driver").click(function(){
var datastring = $('#testform').serialize();
function loading_show(){
$('#loading').html("<img src='../images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "GET",
url: "agent_talktime_pag.load.php?txtDate=2007-03-04&zone=Hongkong",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
$(document).ready(function(){
$("#driver").click(function(){
var txtDate=$("#txtDate").val();
var zone=$("#zone").val();
var dataString = 'txtDate='+ txtDate + '&zone='zone;
});
function loading_show(){
$('#loading').html("<img src='../images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax ({
type: "GET",
url: "agent_talktime_pag.load.php",
data: dataString,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This is a pagination script using Jquery, Ajax and PHP
The enhancements done in this script pagination with first,last, previous, next buttons -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Pagination with Jquery, Ajax, PHP</title>
<script type="text/javascript" src="jquery/external/jquery/jquery.js"></script>
<script type="text/javascript" src="jquery/jquery-ui.min.js"></script>
<link rel="stylesheet" href="includes/jquery/jquery-ui.css">
<link type="text/css" rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div align="center" style="font-size:24px;color:#cc0000;font-weight:bold">Pagination with jquery, Ajax and PHP</div>
<form id="testform">
<input type="text" name="txtDate" id="txtDate">
<select id="zone" name="zone">
<option value="Hongkong">Hongkong</option>
<option value="EST">EST</option>
</select>
<input type="button" id="driver" name="submit" value="Search"/>
</form>
<div id="loading"></div>
<div id="container">
<div class="data"></div>
<div class="pagination"></div>
</div>
</body>
</html>
To send data you have to do as follows:
Error code:
var datastring = 'txtDate =' + txtDate + '& zone =' zone;
Code:
//Manual code
var datastring = {"name field" txtDate, "fieldname": zone} // zone = field values
otherwise:
var datastring = $('#idForm').serialize();
Code ajax:
$.ajax({
data: datastring, //date form
url: 'url',
type: 'get', //type
dataType: "html",
beforeSend: function () {
//code load
},
success: function (response)
{
//code
}
});
You shouldn't be posting data in the url as params. You should use data to map out your data fields that you're going to be sending:
type: "method",
data: {field1: field1, field2: field2}
Related
I have make a simple html file to get my data and add button to post data but however i am returning error 400
My get method are running fine with displaying the backend data out in the html but however post method i am returning some errors 400 due to my query which i not sure why is there any way i can prevent this error 400 ?
<!DOCTYPE html>
<html>
<head>
<title>Add recycables</title>
<!-- Stylesheet -->
<link rel="stylesheet" href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id = "add"></div>
<P>Add recycables</P>
<p>name: <input type="text" id="name"></p>
<p>type:<input type="text" id="type"> </p>
<button id="add">Add</button>
</body>
<script>
$(document).ready(function(){
var $items = $('#add');
var $name = $('#name');
var $type = $('#type');
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/get",
method:"GET",
// In this case, we are going to use headers as
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:"RecyclableGet(0)",
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, item, xhr,textStatus) {
//console.log(data)
$.each(data, function(i, item){
$items.append('<li>name: '+item.Name +', type: '+ item.RecyclableType + '</li>');
});
},
error:function(xhr,textStatus,err) {
console.log(err);
}
});
$('#add').on('click', function(){
var addRecyclables = {
Name: $name.val,
RecyclableType: $type.val
}
})
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/post",
method:"POST",
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:`RecyclableAdd('${name}','${type}')`,
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, Newitem, xhr,textStatus){
$items.append('<li>name: '+Newitem.Name +', type: '+ Newitem.RecyclableType + '</li>');
},
error:function(xhr,textStatus,err) {
console.log(err);
}
})
})
</script>
</html>
Json file look like
my html on web
The following button calls a jQuery function onClick. However, the Firefox dev console says "postData is not defined."
Here is the button and the jQuery script.
<div class="center_text_grid flex-item EMail_Pwd">
<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>
function sendReply() {
// autoresponder
}
postData().done(sendReply);
</script>
</form><br>
<br><br><br>
<!-- ________________ -->
<script type="text/javascript">
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
}
Why does the console say the function postData is not defined?
Thanks for any ideas.
I don't understand why you need two nested ajax calls, you really don't need them, I think. In any case, you can't declare a variable like this var datastring = $("#echo_test").serialize(); inside curly brackets, so move that line outside the ajax call.
Also take into consideration the order in which you declare/execute functions.
So, moving the script, where the function is declared, up:
<div class="center_text_grid flex-item EMail_Pwd">
<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>
<script type="text/javascript">
function postData() {
var datastring = $("#echo_test").serialize();
return $.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
}
</script>
<script>
function sendReply() {
// autoresponder
}
//also, this line is not needed for the button to work, this is just if
//you need the function to execute on page load as well
postData().done(sendReply);
</script>
HIH
you are calling postData before to implement the method, as mentioned move your function document.ready or put
<script type="text/javascript">
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
}
</script>
in the head of the html file
Remove onclick from the button and add handler in the $(document.ready) function:
<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)">Click to Submit Data</button></div>
...
<script type="text/javascript">
$(function(){
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
$("#btn_joinnow").click(postData);
});
</script>
I want to increment count field in database when a link is clicked in php file.
So, I've added the following jquery part to my .php file. But still, it doesn't work. Please help!
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
code.php:
<?php
$conn=mysqli_connect("localhost","root","","sample");
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($connection);
?>
You made a several mistakes in your code.
Update
You can send your SID input type text from ajax with data and you can get the value in your php file with the $sid = $_POST['sid'].
<body>
click here
<input type="text" value="" name="sid" id="sid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$('#click').click(function(event)
{
var sidvalue = $("#sid").val(); /*from here you get value of your sid input box*/
event.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php",
data: 'sid='+sidvalue ,
success: function() {
window.location.href = 'https://www.google.com/';
}
});
});
});
</script>
After the ajax success response you can make redirect to your desire location.
Code.php
<?php
$conn=mysqli_connect("localhost","root","","sample");
$sid = $_POST['sid']; // use this variable at anywhere you want.
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($conn);
?>
in code.php in mysqli_close you should use $conn not $connection.
Go with this code. It might help you. I have just tested all the things in localhost. This is working perfect.
use preventDefault() when click event is called.check jquery :
<body>
click here
<script>
$(function ()
{
$('#click').click(function(e)
{
e.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
Redirect your link on ajax success. Like this -
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php",
success: function(response){
window.location="http://www.google.com";
}
});
});
}
</script>
I viewed so many post aboit this but still cant get my code to work.
I want to get a php array of my checked checkboxes values.
heres my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<?php
echo'<form method="post">
<input type="checkbox" name="cim" value="valami">';
echo'<input type="checkbox" name="cim" value="valami2">';
echo'<input type="checkbox" name="cim" value="valami3">';
echo'<input type="checkbox" name="cim" value="valami4">
<input type="submit" value="Felvisz" name="feladat"></form>';
if (isset($_POST['feladat'])) {
?>
<script type="text/javascript">
var checkedValue = $('.messageCheckbox:checked').val();
var myJSON = JSON.stringify(checkedValue);
$.ajax({
type: "POST",
url: "proba.php",
data: { tomb : myJSON },
success: function(){
alert("OK");
}
});
</script>
<?php
var_dump($_POST);
$array = json_decode(stripslashes($_POST['tomb']));
foreach($array as $arr){
echo $arr;
}
}
?>
</body>
</html>
Massages i got:
Notice: Undefined index: tomb in D:\programok\xamp\htdocs\SZAKDOGA\Dropbox\proba.php on line 48
Warning: Invalid argument supplied for foreach() in D:\programok\xamp\htdocs\SZAKDOGA\Dropbox\proba.php on line 49
Please someone can help me to solve this?
To get an array , you must convert the name to accept multiple so change the input's :
name="cim"
to
name="cim[]"
Also your jquery ajax function should be this :
<script type="text/javascript">
$(function(){
$("form").on("submit",function(e){
e.preventDefault();
var checkedValue = $(this).serialize();
$.ajax({
type: "POST",
url: "proba.php",
data: checkedValue,
success: function(){
alert("OK");
}
});//end ajax
});//end form submit
});
</script>
in php the cim will be the array example
var_dump($_POST["cim"]);
hope it helps
currently, you are testing for checked boxes with class messageChecked. assign your checkboxes that class, give your form an id, then test for checked condition on each checkbox,
$('#yourForm').each(function() {
if($('.messageChecked').is(':checked')) {
checkedValue.push($('.messageChecked:checked').val());
}
}
now send it to your php script via ajax,
$.ajax({
type: "POST",
url: "proba.php",
data: { tomb : (checkedValue) },
success: function(){
alert("OK");
}
});
if done like this you can remove json_decode and stripslashes from your $_POST statement
i calling a jsonp functin and get response back but i want to use MaxTagId(var MaxTagId = data.pagination.next_max_tag_id;) the next time i press the button. My code now cant use the value MaxTagId each time i press button since my response from instagram api is same each time. If it it has used the MaxTagId value then each time i was clicking the button i should have got new respone since jsonp url was changing on each call! could any one tell me what i am doing wrong in using MaxTagID in jsonp url each time i press button?
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function callApi2(){
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/tags/mango/media/recent?access_token=xxxxxxx&max_tag_id=+MaxTagId+",
success: function(data) {
alert("Next Max Tag Id:"+data.pagination.next_max_tag_id);
document.myform.outputtext.value = document.myform.outputtext.value+data.pagination.next_max_tag_id+'\n' ;
var MaxTagId = data.pagination.next_max_tag_id;
console.log(data);
for (var i = 0; i < 21; i++) {
$(".content").append("<img class='SC-instagram-image' src='" + data.data[i].images.low_resolution.url +"' />");
}
}
});
}
</script>
</head>
<body>
<div class="content"></div>
<form id="myform" name="myform" action="./ok.php" method="post">
<td><textarea rows="6" cols="15" name="outputtext" style="width: 99%;"></textarea></td>
</form>
<button onclick="callApi2()">Start</button>
</html>
You should create a new variable outside of your function to store the ID in.
var maxTagId = null;
function callApi2() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/tags/mango/media/recent?access_token=xxxxxxx" + ( maxTagId ? "&max_tag_id=" + maxTagId : ""),
success: function(data) {
maxTagId = data.pagination.next_max_tag_id;
}
});
}
Of course these variables are now in the global namespace, so ideally you'd put them in a self-invoking function. For more info see: http://marcofranssen.nl/writing-modular-javascript-without-polluting-the-global-namespace/