Pass Jquery Array to phpself - php

Ok guys. Im new to jquery, and I have a jquery array that I need to pass as a $_POST to the same file which is called index.php. When they click the button I need it to reload the index.php so I can get the POST. Now I'm sure I'm doing something wrong here cause this isn't working. But I'm certain that its something simple that I'm missing, or that I'm doing it all wrong and I mis-understood how this works. Any help is appreciated as I've been on this and trying to figure it out for the last 6 hours.
The index.php also contains the jquery scripts which are below, and the Post check which is
if (isset($_POST['data'])){
echo "ok, data was sent.<br>";
echo " Data is - " .$_POST['data'];
}
And the Button call
echo "<p><input type=\"submit\" class=\"input-button\" id=\"btn-add\" value=\"Add Squad\" /></p>";
Jquery
$(document).ready(function(){
// Get items
function getItems(exampleNr)
{
var count = 0;
var columns = [];
$(exampleNr + ' ul.sortable-list').each(function(){
count++;
columns.push($('#squad'+count).val(), $(this).sortable('toArray').join(','));
});
return columns.join('|');
}
$(document).on('click','#btn-get', function() {
$.post('index.php', {'data': getItems('#squad')}
});
});

You aren't doing anything with the response of your POST.
If you want it to submit like a form, you will need to create a form, attach a hidden input to it with your key-value pair, then submit that form. $.post alone is used for AJAX.

Related

jQuery AJAX request not firing when posting to a php script.

I have a database table which I am trying to retrieve data from using JQUERY AJAX. When my first page loads it does a php call to a table and populates a select form element. - This works
I then want to select one of the options submit the form and have the row returned via Ajax.
Previously I had the script working with just PHP files but am having trouble getting it to work. When submitting the form my URL is changing:
http://localhost/FINTAN/testertester.php?name=Specifics.
I am not getting anything back. In addition when looking at my console I get a jquery not defined
factory (jquery). I can find the line in question in my jquery ui.js. Not sure if this is the issue or my code has caused the issue. I have cleard the firefox cache and due to the fact I have not had a successful AJAX call via jquery method am guessing it my code.
To get the code below I have mixed and matched a book and an online tutorial and many other sources and this is not my first attempt. Ideally I would like to output table row. However just getting a request working and knowing its not a conflict or compatability issue would makeme feel better and not hindered before I start
<script src="jquery/jquery-ui-1.11.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val;
}
}
$.post("addithandle1.php",
{
name:vname};
function(response,status){
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
}
}
</script>
</head>
<body>
<?php
include "config.php";
if (mysqli_connect_errno($con))
{
}
else
{
$result = mysqli_query($con, "SELECT * FROM script ");
echo " <Form method='post'> <label>Script :</label> <select id='name' name='name' >";
}
while($row = mysqli_fetch_array($result))
{
echo "<option value = '".$row['scriptname']."'>".$row['scriptname']."</option>";
}
echo "</select>";
echo "<button id='btn' class='btn-search'>Load Script </button></form>";
?>
</body></html>
This is my PHP file that I am trying to retrieve from
<?php
include 'config.php';
$batchtype2 = $_POST['name'];
$batchtype2 = mysqli_real_escape_string($con,$batchtype2);
$sql = "SELECT * FROM script WHERE scriptname = '".$batchtype2."' ";
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo '<tr><td>'.$row['scriptname'].'</td></tr>';
echo '<tr><td>'.$row['scripthours'].'</td></tr>';
echo '<tr><td>'.$row['scripttotal'].'</td></tr>';
}
}
mysqli_close($con);
?>
Thanks in advance for any help
By making the following corrections (you have some syntax issues as well as usage issues which should be revealed in your browser's console when you load this page) in your JavaScript/jQuery this will work like you expect -
Make sure to change this line -
var vname = $("#name").val;
to this -
var vname = $("#name").val(); // note the parentheses
in your function -
$(document).ready(function(){
$("#btn").click(function(e){
e.preventDefault(); // prevent the default action of the click
var vname = $("#name").val();
$.post("addithandle1.php", {name:vname}, function(response, status) { // POST instead of GET
// never use alert() for troubleshooting
// output for AJAX must be in the callback for the AJAX function
console.log("recieved data-------*\n\nResponse : " + response +"\n\nStatus : " + status);
$('#table').html(response); // put response in div
});
});
});
Now $_POST['name'] should get populated properly.
To get the table to appear in your requesting page first make sure that your PHP forms the table completely.
Add a div to your requesting page and modify the AJAX call above as shown.
<div id="table"></div>
Now, when you make a request the div on the requesting page will be updated with whatever comes back from the PHP script.
There are a couple of things about your script.
First make sure you write well structured code and that it is nothing in the wrongplace / broken.
You have in the $(document).ready(function(){ only the .click event of the button, but you left the ajax request outside, I imagine you did that so it will also make the ajax request in the first page load
The problem is that now it will only make it in the first page load, but not when you click the button, on clicking button you are only getting the value of name.
I recommend you to try something like this:
<script>
$(document).ready(function() {
// bind button click and load data
$("#btn").click(function(){
loadData();
return false; // prevent browser behaviour of the button that would submit the form
}
// load data for the first time
loadData();
};
function loadData() {
var vname = $("#name").val;
$.post("addithandle1.php", { name:vname }, function(response, status) {
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
});
}
</script>
A few notes:
I would recommend always putting jquery code inside $(document).ready since that guarantees that jquery was loaded before running it
By default a form that has a submit button that you click, will get the form submitted by the browser, if you use ajax, you should prevent that behaviour, either on the button click event or on form with onsubmit="return false".

Foreach only prints one value from the array when using Ajax and onsubmitForm

I have a PHP script that calls the Twitter 1.1 API, and returns 50 ID numbers. Then I am using a Foreach argument to print the results individualy on to the page. I want to store each different ID number inside a button as a hidden value, and then use JQuery Ajax to post that value to a different PHP page for further processing without leaving or refreshing the page of 50 ID numbers.
If I use this Foreach argument, the 50 ID numbers are ALL the first result in the array, rather than being 50 individual ID numbers which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='RT' onsubmit='return submitForm();'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>
");
}
But, If I remove this section from the Foreach argument, 50 individual ID numbers are printed into into hidden values of the forms:
onsubmit='return submitForm();'
The problem is my JQuery script is listening for submitForm and without that line above the JQuery will not run. Here is my JQuery script:
<script>
function submitForm() {
$.ajax({type: 'POST', url: 'results.php', data: $('#RT').serialize()});
return false;
}
</script>
I know that removing onsubmit='return submitForm();' gives me 50 unique ID numbers from the Foreach, because this code will print 50 buttons which will each contain individual values. But because there is no JQuery script listening for submitForm I have to add method='post' action='results.php in order to POST the value of the button but this means the page results.php loads which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='form' method='post' action='results.php'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>");
}
So, I want the foreach to print 50 unique ID numbers, while also letting me use the JQuery Ajax script. I hope this is clear, I don't know how else to describe what I want to do :D
Okay, now I understand what you're trying to do. I would do it like this.
PHP:
<?php
foreach ($results as $arrResult) {
$tweetId = $arrResult['id_str'];
print('<button type="button" class="mark-tweet" data-tweet-id="' . $tweetId . '"><br/><br/>');
}
JavaScript:
$(function() {
$('.mark-tweet').click(function() {
var id = $(this).attr('data-tweet-id');
$.ajax({
type: 'POST',
url: 'results.php',
data: {tweetId : id}
});
})
.done(function() {
alert('The tweet has been deleted');
})
.fail(function() {
alert('Oops, something went wrong! Please try again.');
});
});
NOTE: I am not capitalizing the 'r' in $Results as you did. Only class names should start in capital letters (class as in OOP, not CSS)
OK, we've got you now. You're on the right track to use an ID, and this is straight-forward.
What you need to render are 50 buttons with onclick that will call your markTweet() JS function & pass it the ID -- and that can do the AJAX post. No form required.
Alternatively, you can render 50 forms with separate IDs ('form'.$tweetId), each with a hidden input & submit button (or just a <button>, since the BUTTON element can have a name & value distinct from its content), and an onclick that calls `postTweetForm('form${tweetId})' -- thus passing the ID of the selected form to your JS function.
Really, since you're doing it in JS, keeping the UI simple & letting JS do the work is easiest. Here's an example to get started. PHP:
foreach ($Results as $arrResult) {
$tweetId = $arrResult['id_str'];
print("<button type='button' onclick='markTweet('".$tweetId."');'><br>\n");
}
Javascript:
function markTweet (tweetId) {
$.post({
url: 'results.php',
data: {'tweetId': tweetId}
);
}
You should also put in a success handler into your AJAX post.. fade in a little green tick or something so the user knows it's worked, because it doesn't always. (I'll let you play with that.)
Try that.. and keep the question up. It's much improved now & may be able to help someone else.

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

edit in place and change value to database also?

I am using editable plugin to edit-in-place. I am able to do it on the web page but I want to change this value to the database also.
Here is the php/html code :
while($row = mysql_fetch_assoc($result))
{
echo "<tr class='highlighter'><td class='editable-1'>".$row['subcategory_name']."</td>";
echo "</tr>";
}
and the jquery code is as follows :
$(document).ready(function()
{
$('.editable-1').editable({onEdit:begin});
function begin(){
this.append('Click somewhere else to submit');
}
}
);
I am trying to use ajax but not getting the value when I am updating in textbox.
Here is what I am trying to do
$.ajax({
url:'change_subcat.php',
data:'NOT AVAILABLE'
});
Please tell me how to made changes also in database.
You will need to submit the data via ajax to the server, where you need a script to process the data and save it to your database.
It looks like in this plugin, you can attach a listener to the onEdit event that will submit your data, maybe something like this:
$('.editable-1').editable({onEdit: submitData});
function submitData (content) {
$.post('/save_to_db.php', { data: content.current });
}
From the documentation for this plugin, it appears that the callback is called with an object for an argument (content, in this case) that has previous and current properties. You should be able to get the new value of the editable field with content.current.

Check in ajax/jquery a form beform submit ( check the value whether it is in database)

ajax is not yet sothin i master.
I have two forms field
code :
name :
and the submit button like :
<form><input type=text name=code><input type =text name=name/></form>
I would like in php/jquery to check if the code the user fill exist in a table of my db.
If it does not exits, when the user leave the textfield to fill the next one, i would like to print a message like: this code is not in the db and then clean the fied. Until the user provide a valide code.
If your php service returns true or false for validation.
and the placeholder for the error is a label called
then an example (in jQuery) would be
$(document).ready(function() {
$("form").submit(function(e) {
var code = $("input[name='code']");
var error = $("#error");
e.preventDefault();
var form = this;
$.getJSON('urlToPhp',
{ code: code.val() },
function(valid) {
if (!valid) {
error.text(code.val() + ' is not found try another code...');
code.val('');
} else {
form.submit();
}
}
);
});
});
I've created a simple example at http://jsfiddle.net/nickywaites/e4rhf/ that will show you have to create a jQuery ajax post request.
I'm not too familiar with php so that part of it I'll have to leave aside although you can use something along the lines of $_POST["Name"].
Here is php example that I googled http://php4every1.com/tutorials/jquery-ajax-tutorial/ that might be better for you.

Categories