Updating database with jQuery AJAX works only one time - php

I'm trying to update a database by using jQuery. The function works just fine, but only once. I have to refresh the page and clear the cache if I want to update the database again. I'm using MODX Revolution, I'm not sure if that has anything to do with this problem. Here is the code:
<html>
<head>
<script language="javascript" type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$('#paina').submit( function updateTitle() {
var mail = $("#output").val();
$.ajax({
type: "POST",
url: "gettable.php",
data: "mail="+ mail,
cache: false,
success: function(data){
alert(mail);
}
});
return false;
});
});
</script>
<form id="paina" name="test" action="javascript:updateTitle()" method="post">
<input type="text" id="output">
<input type="Submit" value="Update">
</form>
</body>
</html>
PHP:
<?php
$mail=$_POST["mail"];
$mysqli = mysqli_connect("url", "user", "password", "database_name");
mysqli_query($mysqli, "UPDATE modx_site_content SET pagetitle='$mail' WHERE longtitle='jee'");
echo "Updated!";
$mysqli->close();

From the jQuery docs:
Note: Setting cache to false will only work correctly with HEAD and
GET requests
Ugly fix: append a random parameter to the query string:
$.ajax({
type: "POST",
url: "gettable.php",
data: "mail="+ mail + "&timestamp=" + new Date(), // Will append the current date in milliseconds since January 1, 1970 (correct me if I'm wrong).
cache: false,
success: function(data){
alert(mail);
}
});

Try changing the ajax to be to help debug, I have also added an object to data and set a sync to false to ensure the ajax finishes execution before the return
$(document).ready(function(){
$('#paina').submit( function() {
$.ajax({
type: "POST",
url: "gettable.php",
data: {mail: mail},
cache: false,
async: false,
success: function(data){
alert(mail);
},
error function(){
alert("Failed");
}
});
});
});
You don't need the action on your form either as jQuery is handling it
<form id="paina" name="test" action="" method="post">

Thanks for the tips. I found the solution, MODX Revolution uses xPDO Database Connections so I had to change PHP code to this:
$mail=$_POST["mail"];
$dsn = 'mysql:host=localhost;dbname=databasename;port=3306;charset=utf-8';
$xpdo = new xPDO($dsn,'user','password');
$results = $xpdo->query("UPDATE modx_site_content SET pagetitle='$mail' WHERE longtitle='jee'");

Related

Form not saving data to MySQL database

I am having trouble recording a single data (deckName) from this form to my MySQL database. I read and tried all the solutions I found over the web, but I cannot get it to work. Doing the MySQL command from the PHPMyAdmin work fine.
I need to save in the deck table of the db (id, name, cards) the values.
Jquery/Ajax script:
<script>
$(document).ready(function(){
$(document).on('submit','.save',function(){
var deckName = $('.deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: console.log('worked')
});
});
});
</script>
Form:
<div class="decklist">
<form method="post" id="decklist">
<input class="deck" id="deckN" type="text" value="Deck name"/>
<input class="save" type="submit" value="Save Deck"/>
</form>
<div class="list">
<ul class="d_list">
<li class='added_card' id='list_0'></li>
</ul>
</div>
</div>
submit.php:
<?php
if(isset($_POST["name"])&& strlen($_POST["name"])>0){
$deckName = $_POST["name"];
$cards = 0;
echo $deckName;
$conn = new mysqli("localhost:8080","root","","ken");
if($conn -> connect_errno){
die("Failed to connect: (". $conn->connect_errno. ")".$conn->connect_error);
}
$insert = $conn->query ("INSERT INTO `deck` (deck, cards) VALUES ($deckName, $cards)");
if ($insert){
echo 'Successfully saved '. $deckName;
$conn -> close();
}
}
?>
Also once I hit Save Deck for submit, the div get refreshed while I assume it shouldn't with ajax.
I tried using click instead of submit, and the console.log returned everything correctly from the ajax function and the div wasn't refreshing every time, but with submit logs don't show up anymore in console.
I don't get anything from the echo in submit.php, never.
Try using preventDefault; like so
$(document).on('submit','.save',function(e){
e.preventDefault;
Hope it solves your problem !
You have to put quotes around string values:
"INSERT INTO `deck` (deck, cards) VALUES ('$deckName', $cards)"
how about change js like this:
$(".decklist").on("click", ".save", function(){
$.post("submit.php", { name: deckName }).success(function(){
console.log('worked');
});
});
You need to bind on the form submit event :
$(document).ready(function(){
$("#decklist").on('submit',function(e){
e.preventDefault();
var deckName = $('.deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: function(response) {
console.log('worked')
}
});
});
});
$(document).ready(function(){
$("#decklist").on('submit',function(e){
e.preventDefault();
var deckName = $('#deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: function(response) {
console.log('worked')
}
});
});
});
it works form me, change $('#deck').val();

Load contents of alexa php results with parameters into html page - Maybe using jquery or ajax

I'm trying to load the alexa rank of a website as a piece of text into a standard html file. I want to avoid setting up the whole page as php so I've created a php file called rank.php which works
<?php
$url=$_GET["url"];
$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$url);
$rank=isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
echo $rank;
?>
I can load this to my server and call it with something like rank.php?url=google.com
This returns a number on the screen (in this case 1). So how do I get that number into a normal <p> tag in a html document.
Ie <p>Alex rank: </p>
I'm looking into jquery and using the get method but I'm getting lost.
eg putting this in the <head></head> tags
<script>
$(document).ready(function(){
$("#div1").load("code/rank.php?url=google.com");
});
</script>
Then in my html page adding
<p>Alex rank: <div id="div1"></div></p>
doesn't work for me.
I've also tried adding the following script within the <p></p> tag.
<script type="text/javascript">
function showGetResult( name )
{
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
}
showGetResult('test');
</script>
I just want a simple solution to pull that number across.
Any help greatly appreciated.
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
I made some tests - and it seems that this is a culprit:
dataType: 'text/html'
Why:
in documentation of jQuery - at http://api.jquery.com/jQuery.ajax/
dataType allowed values:
"xml"
"html"
"json"
"jsonp"
"text"
multiple, space-separated values
I tried
dataType: 'text'
Worked for me.
Be sure to put your script tag after if you are executing it inline of your page
<p>Alexa rank: <span id="div-1"></span></p>
<script>
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
</script>
But cleaner way to do it:
<html>
<head>
<script>
// comment:
// in jQuery
// $( yourFunction )
// is a shortcut for
// $(document).ready( yourFunction )
$(function(){
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
});
</script>
</head>
<body>
<p>Alexa rank: <span id="div-1"></span></p>
</body>
</html>
In this last code I am using cache: false because I feel it is good for this case. I am using dataType: 'text' because you are expecting just a number - so why not? It just fells more KISS for me. Perhaps it will work with 'html'.
By the way - there can be another place where another mistake can be hidden:
code/rank.php?url=google.com
If you current URL is
www.example.com/somefolder/
then it will be interpreted as
www.example.com**/somefolder/**code/rank.php?url=google.com
If your current URL is www.example.com/somefolder/another/
then it will be interpreted as
www.example.com**/somefolder/another/**code/rank.php?url=google.com
My advise - you can always use Firefox or Google Chrome Developer Tools > Network to see what is returning your ajax request - a '1' or 'PAGE 404 NOT FOUND' ^_^
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
I made some tests - and it seems that this is a culprit:
dataType: 'text/html'
Why:
in documentation of jQuery - at http://api.jquery.com/jQuery.ajax/
dataType allowed values:
"xml"
"html"
"json"
"jsonp"
"text"
multiple, space-separated values
I tried
dataType: 'text'
Worked for me.
Be sure to put your script tag after if you are executing it inline of your page
<p>Alexa rank: <span id="div-1"></span></p>
<script>
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
</script>
But cleaner way to do it:
<html>
<head>
<script>
// comment:
// in jQuery
// $( yourFunction )
// is a shortcut for
// $(document).ready( yourFunction )
$(function(){
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
});
</script>
</head>
<body>
<p>Alexa rank: <span id="div-1"></span></p>
</body>
</html>
In this last code I am using cache: false because I feel it is good for this case. I am using dataType: 'text' because you are expecting just a number - so why not? It just fells more KISS for me. Perhaps it will work with 'html'.
By the way - there can be another place where another mistake can be hidden:
code/rank.php?url=google.com
If you current URL is
www.example.com/somefolder/
then it will be interpreted as
www.example.com**/somefolder/**code/rank.php?url=google.com
If your current URL is www.example.com/somefolder/another/
then it will be interpreted as
www.example.com**/somefolder/another/**code/rank.php?url=google.com
My advise - you can always use Firefox or Google Chrome Developer Tools > Network to see what is returning your ajax request - a '1' or 'PAGE 404 NOT FOUND' ^_^
Answering comment:
Yes, you've got the gist of it right.
Here is one way how you could implement it
(it would be comfortable for my way of thinking and organizing code):
<html>
<head>
<script>
// defining tool:
function updateRankForSite( inUrl, $inInsertTo ) {
$.ajax({
url: 'code/rank.php?url=' + inUrl,
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
$inInsertTo.html(data);
}
});
}
</script>
<script>
// using tool:
$(function(){
outputRankForSite( 'google.com', $('#rank-google') );
outputRankForSite( 'yandex.com', $('#rank-yandex') );
// and here is example how to interact with user
$('button-1').click( function( event ) {
// comment
// event.preventDefault() blocks default behavior
// for clicking on ... tag
// that means you wouldn'd be redirected to href
event.preventDefault();
outputRankForSite(
'stackoverflow.com',
$('#rank-stackoverflow')
);
// comment:
// and you can leverage not just 'stackoverflow.com'
// but anything that user wants - he can
// put his request to <input="text" id="example-input" ...>
// and you could collect his input by using command like
// $('#example-input').val()
});
});
</script>
</head>
<body>
<p>Alexa rank for google.com: <span id="rank-google"></span></p>
<p>Alexa rank for yandex.com: <span id="rank-yandex"></span></p>
<p>
Alexa rank for stackoverflow.com (press button to get rank):
<span id="rank-stackoverflow"></span>
</p>
Press this button to update rank
</body>
</html>

POST-ing JSON to Laravel 4 with jQuery

I've been struggling with this for a while, I checked everything I could think of and I'm sure this should work.. but it doesn't.
The idea is simple - you have a form input of type "text". When you type a number in the input and click "Click me!", it should POST the data in JSON format to a Route (handled via Closure), which would then check if the input is in JSON format and if yes, make a database request, then return the data.
Here is my view (table.blade.php)
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<title>json test</title>
</head>
<body>
<form action="#">
<input type="text" name="articleID" id="articleid" placeholder="Enter article id" value=""/>
</form>
Click me!
<script>
$(document).ready(function(){
var a_id = $("#articleid").val();
var article = { id: a_id };
$("#trigger").click(function(){
console.log(article);
$.ajax({
type: "POST",
url: "/json",
data: article,
dataType: 'json',
success: function(data){
alert(data.title);
}
});
return false;
});
});
</script>
</body>
</html>
And my routes.php
Route::get('json',function(){
return View::make('table');
});
Route::post('json',function(){
if (Input::isJson())
{
$request = Input::all();
$article = Article::find($request['id']);
if (!is_null($article))
{
return Response::json($article);
}
else return Response::json(['error' => "Object not found"],404);
}
else return "not json";
});
I've got two problems with this:
console.log(article); prints Object { id=""} so JS doesn't seem
to pick up the value of the input
No matter what, I always receive the response "not json", even if I replace data: article with something like data: {id: 123} in the ajax call
UPDATE
Thanks to milz, the first issue is now fixed, I refactored the $(document).ready() function like so:
$("#trigger").click(function(){
var a_id = $("#articleid").val();
var article = { id: a_id };
console.log(article);
$.ajax({
type: "POST",
url: "/json",
data: article,
dataType: 'json',
success: function(data){
alert(data.title);
}
});
return false;
});
Now the object is properly set, however the backend still returns only "not json"...
I have no idea what I'm doing wrong here, I will appreciate any help! Thanks in advance!
Input::isJson() actually checks for the Content-Type header of the request. The only thing dataType does is telling jQuery what response to expect.
Try setting contentType
$.ajax({
type: "POST",
url: "/json",
data: article,
dataType: 'json',
contentType: 'application/json',
success: function(data){
alert(data.title);
}
});

AJAX POST DATA NOT WORKING

This is my jQuery-Ajax code:
<script>
$('#sbmt').click( function(){
$.ajax({
type: 'post',
data: $("#ajxfrm").serialize(),
url: "postdata.php",
cache: false,
success: function (data)
{
alert('updated table');
}
});
});
</script>
HTML CODE:
<form id="ajxfrm" method="post" action="">
<label>HIGH : </label> <input type="text" name="hi" id="hi"><br><br>
<label>LOW : </label><input type="text" name="lo" id="lo"><br><br>
<label>OPENING STOCK : </label><input type="text" name="opn" id="opn"><br><br>
<label>CLOSING STOCK : </label><input type="text" name="cls" id="cls">
<input type="submit" value="Submit" id="sbmt">
</form>
AND PHP CODE ON postdata.php file is :
require_once 'config.php';
$hi = $_POST['hi'];
$lo = $_POST['lo'];
$opn = $_POST['opn'];
$cls = $_POST['cls'];
echo $hi;
$postdata = "INSERT INTO htmdem ( high,low,open,close ) VALUES('$hi','$lo','$opn','$cls');";
mysql_query($postdata);
When posting via form without ajax the table is getting updated as it should, but while using AJAX its not. Please suggest what's wrong here. Many Thanks
Try this : Dont forget to set the form action to postdata.php
jQuery(function($) {
$('#ajxfrm').submit( function(e){
$.ajax({
type: 'post',
data: $(this).serialize(),
url: $(this).attr("action")
})
.done(function (data){
alert('updated table');
});
e.preventDefault();
});
});
Modify your html to add action to form:
<form id="ajxfrm" method="post" action="postdata.php">
Try handling form submit event instead:
$('#ajxfrm').submit(function(event){
$.ajax({
type: 'post',
data: $(this).serialize(),
url: $(this).attr("action"),
cache: false,
success: function (data)
{
alert('updated table');
}
});
return false; //to prevent form submission
//or event.preventDefault();
});
BTW, using success callback is deprecated and post requests are not cached so we also don't need cache:false
$('#ajxfrm').submit(function(event){
$.ajax({
type: 'post',
data: $(this).serialize(),
url: $(this).attr("action")
})
.done(function (data){
alert('updated table');
});
return false; //to prevent form submission
//or event.preventDefault();
});
change your input type="submit" to input type="button". that should do the trick I guess.
Assuming you have included the jquery library in your page,
First, run your page with with your firefox/chrome and use their firebug/console to verify that your ajax is actually posting data to your php page.
Second, modify your query execution in your php file, to catch query errors:
mysql_query($postdata) or die(mysql_error());
One of these cases will help you determine your problem
For Firefox: get the Firebug addon from https://getfirebug.com/
After installing it and restarting firefox, press F12. A console will open.
Run your ajax call and check in the console if data are being posted.

Typeahead input field and query passed to PHP with AJAX

I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call

Categories